@midscene/core 1.11.0 → 1.11.1-beta-20260819031908.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/es/agent/agent.mjs +11 -13
  2. package/dist/es/agent/agent.mjs.map +1 -1
  3. package/dist/es/agent/tasks.mjs +14 -6
  4. package/dist/es/agent/tasks.mjs.map +1 -1
  5. package/dist/es/agent/utils.mjs +1 -1
  6. package/dist/es/ai-model/prompt/planning/multi-turn-example.mjs +10 -10
  7. package/dist/es/ai-model/prompt/planning/multi-turn-example.mjs.map +1 -1
  8. package/dist/es/ai-model/prompt/planning/planning-response-example.mjs +4 -3
  9. package/dist/es/ai-model/prompt/planning/planning-response-example.mjs.map +1 -1
  10. package/dist/es/ai-model/prompt/planning/system-prompt.mjs +14 -10
  11. package/dist/es/ai-model/prompt/planning/system-prompt.mjs.map +1 -1
  12. package/dist/es/ai-model/workflows/grounding/planning-action-locate.mjs +1 -0
  13. package/dist/es/ai-model/workflows/grounding/planning-action-locate.mjs.map +1 -1
  14. package/dist/es/ai-model/workflows/planning/index.mjs +2 -2
  15. package/dist/es/ai-model/workflows/planning/planning-action-log.mjs +22 -0
  16. package/dist/es/ai-model/workflows/planning/planning-action-log.mjs.map +1 -0
  17. package/dist/es/ai-model/workflows/planning/standard-planning-parser.mjs +22 -3
  18. package/dist/es/ai-model/workflows/planning/standard-planning-parser.mjs.map +1 -1
  19. package/dist/es/ai-model/workflows/planning/standard-planning.mjs +19 -5
  20. package/dist/es/ai-model/workflows/planning/standard-planning.mjs.map +1 -1
  21. package/dist/es/types.mjs.map +1 -1
  22. package/dist/es/utils.mjs +2 -2
  23. package/dist/lib/agent/agent.js +11 -13
  24. package/dist/lib/agent/agent.js.map +1 -1
  25. package/dist/lib/agent/tasks.js +14 -6
  26. package/dist/lib/agent/tasks.js.map +1 -1
  27. package/dist/lib/agent/utils.js +1 -1
  28. package/dist/lib/ai-model/prompt/planning/multi-turn-example.js +10 -10
  29. package/dist/lib/ai-model/prompt/planning/multi-turn-example.js.map +1 -1
  30. package/dist/lib/ai-model/prompt/planning/planning-response-example.js +4 -3
  31. package/dist/lib/ai-model/prompt/planning/planning-response-example.js.map +1 -1
  32. package/dist/lib/ai-model/prompt/planning/system-prompt.js +14 -10
  33. package/dist/lib/ai-model/prompt/planning/system-prompt.js.map +1 -1
  34. package/dist/lib/ai-model/workflows/grounding/planning-action-locate.js +1 -0
  35. package/dist/lib/ai-model/workflows/grounding/planning-action-locate.js.map +1 -1
  36. package/dist/lib/ai-model/workflows/planning/index.js +3 -0
  37. package/dist/lib/ai-model/workflows/planning/planning-action-log.js +56 -0
  38. package/dist/lib/ai-model/workflows/planning/planning-action-log.js.map +1 -0
  39. package/dist/lib/ai-model/workflows/planning/standard-planning-parser.js +26 -4
  40. package/dist/lib/ai-model/workflows/planning/standard-planning-parser.js.map +1 -1
  41. package/dist/lib/ai-model/workflows/planning/standard-planning.js +18 -4
  42. package/dist/lib/ai-model/workflows/planning/standard-planning.js.map +1 -1
  43. package/dist/lib/types.js.map +1 -1
  44. package/dist/lib/utils.js +2 -2
  45. package/dist/types/agent/agent.d.ts +2 -1
  46. package/dist/types/agent/tasks.d.ts +2 -2
  47. package/dist/types/ai-model/prompt/planning/multi-turn-example.d.ts +3 -1
  48. package/dist/types/ai-model/prompt/planning/planning-response-example.d.ts +2 -2
  49. package/dist/types/ai-model/prompt/planning/system-prompt.d.ts +2 -0
  50. package/dist/types/ai-model/workflows/planning/index.d.ts +1 -1
  51. package/dist/types/ai-model/workflows/planning/planning-action-log.d.ts +2 -0
  52. package/dist/types/ai-model/workflows/planning/standard-planning-parser.d.ts +14 -2
  53. package/dist/types/ai-model/workflows/planning/types.d.ts +2 -2
  54. package/dist/types/device/index.d.ts +14 -14
  55. package/dist/types/types.d.ts +2 -1
  56. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"agent/tasks.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/agent/tasks.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/extraction';\nimport { multimodalPromptToChatMessages } 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 } from '@/device';\nimport type Service from '@/service';\nimport type { TaskRunner, TaskRunnerEvent } from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActProgressData,\n AiActProgressPhase,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n PlanningLocateParam,\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 { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\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 each task's planning feedback so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. This is the\n// single place that truncates feedback before it is sent to the model; action\n// implementations should hand over the untruncated value.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(feedback: string): string {\n if (feedback.length <= maxPlanningFeedbackLength) {\n return feedback;\n }\n\n return `${feedback.slice(0, maxPlanningFeedbackLength)}\n...[truncated, ${feedback.length - maxPlanningFeedbackLength} 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 providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\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 onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n actionSpace: DeviceAction[];\n },\n ) {\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.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n uiContext?: UIContext;\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 () =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn()),\n {\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\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(({ planningFeedback }) =>\n planningFeedback ? [truncatePlanningFeedback(planningFeedback)] : [],\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 defaultModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, defaultModel, 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\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 (param, 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 runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: { uiContext?: UIContext },\n ): Promise<ExecutionResult> {\n const session = this.createExecutionSession(title, options);\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionDefaultModel = { ...defaultModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionDefaultModel,\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 defaultModel: ModelRuntime,\n includeLocateInPlanning: boolean,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n imagesIncludeCount?: number,\n deepThink?: boolean,\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 return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n defaultModel,\n includeLocateInPlanning,\n aiActContext,\n cacheable,\n replanningCycleLimitOverride,\n imagesIncludeCount,\n deepThink,\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 PlanningLocateParam | 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 defaultModel: ModelRuntime,\n includeLocateInPlanning: boolean,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n imagesIncludeCount?: number,\n deepThink?: boolean,\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 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 onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n defaultModel = { ...defaultModel, executionId: runner.id };\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 referenceImageMessages = await multimodalPromptToChatMessages(\n userPromptToMultimodalPrompt(userPrompt),\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 deepThink,\n ...(subGoalStatus ? { subGoalStatus } : {}),\n ...(memoriesStatus ? { memoriesStatus } : {}),\n },\n executor: async (param, 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 setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(param.userInstruction, {\n context: planningUiContext,\n actionContext: param.aiActContext,\n actionSpace,\n modelRuntime: planningModel,\n conversationHistory,\n includeLocateInPlanning,\n imagesIncludeCount,\n deepThink,\n referenceImageMessages,\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 rawChoiceMessage: planError.rawChoiceMessage,\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 rawChoiceMessage,\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 rawChoiceMessage,\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 defaultModel,\n {\n cacheable,\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 // 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 = `Replanned ${replanningCycleLimit} times, exceeding the limit. Please configure a larger value for replanningCycleLimit (or use MIDSCENE_REPLANNING_CYCLE_LIMIT) to handle more complex tasks.`;\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 (param, 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 rawChoiceMessage: dump.taskInfo?.rawChoiceMessage,\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 executionOptions,\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 session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : undefined,\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,\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 { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\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 const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\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 );\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":["__webpack_require__","definition","key","Object","obj","prop","Symbol","debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","TaskExecutor","title","options","ExecutionSession","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","undefined","format","getReadableTimeString","plans","planningModel","defaultModel","userInstruction","yamlString","reportOptions","session","taskTitleStr","userPromptToString","task","param","executorContext","uiContext","assert","executionPlanningModel","executionDefaultModel","result","output","userPrompt","includeLocateInPlanning","aiActContext","cacheable","replanningCycleLimitOverride","imagesIncludeCount","deepThink","fileChooserAccept","deepLocate","abortSignal","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","referenceImageMessages","multimodalPromptToChatMessages","userPromptToMultimodalPrompt","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","action","Array","console","planImpl","standardPlan","planResult","setTimingFieldOnce","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","JSON","actions","thought","log","memory","usage","rawResponse","rawChoiceMessage","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","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":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBA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AQ,GAAGA,KAAK,QAAQ,GACzB;eAAI4H;eAAkB5H,KAAK,QAAQ;SAAC,GACpC4H;IACN;IACA,IAAIzH,WAAW,oBACbA,UAAU,kBAAkB,GAAGf;AAEnC"}
1
+ {"version":3,"file":"agent/tasks.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/agent/tasks.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/extraction';\nimport { multimodalPromptToChatMessages } 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 } from '@/device';\nimport type Service from '@/service';\nimport type { TaskRunner, TaskRunnerEvent } from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActEffort,\n AiActProgressData,\n AiActProgressPhase,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n PlanningLocateParam,\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 { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\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 each task's planning feedback so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. This is the\n// single place that truncates feedback before it is sent to the model; action\n// implementations should hand over the untruncated value.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(feedback: string): string {\n if (feedback.length <= maxPlanningFeedbackLength) {\n return feedback;\n }\n\n return `${feedback.slice(0, maxPlanningFeedbackLength)}\n...[truncated, ${feedback.length - maxPlanningFeedbackLength} 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 providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\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 onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n actionSpace: DeviceAction[];\n },\n ) {\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.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n uiContext?: UIContext;\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 () =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn()),\n {\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\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(({ planningFeedback }) =>\n planningFeedback ? [truncatePlanningFeedback(planningFeedback)] : [],\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 defaultModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, defaultModel, 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\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 (param, 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 runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: { uiContext?: UIContext },\n ): Promise<ExecutionResult> {\n const session = this.createExecutionSession(title, options);\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionDefaultModel = { ...defaultModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionDefaultModel,\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 defaultModel: 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 return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n defaultModel,\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 PlanningLocateParam | 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 defaultModel: 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 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 onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n defaultModel = { ...defaultModel, executionId: runner.id };\n\n const noIndividualLocateModel = planningModel.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 referenceImageMessages = await multimodalPromptToChatMessages(\n userPromptToMultimodalPrompt(userPrompt),\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 (param, executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n assert(param.effort, 'effort is required for Planning Plan 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 setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(param.userInstruction, {\n context: planningUiContext,\n actionContext: param.aiActContext,\n actionSpace,\n modelRuntime: planningModel,\n conversationHistory,\n includeLocateInPlanning,\n imagesIncludeCount: param.imagesIncludeCount,\n effort: param.effort,\n referenceImageMessages,\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 rawChoiceMessage: planError.rawChoiceMessage,\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 rawChoiceMessage,\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 rawChoiceMessage,\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 defaultModel,\n {\n cacheable,\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 // 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 = `Replanned ${replanningCycleLimit} times, exceeding the limit. Please configure a larger value for replanningCycleLimit (or use MIDSCENE_REPLANNING_CYCLE_LIMIT) to handle more complex tasks.`;\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 (param, 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 rawChoiceMessage: dump.taskInfo?.rawChoiceMessage,\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 executionOptions,\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 session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : undefined,\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,\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 { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\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 const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\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 );\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":["__webpack_require__","definition","key","Object","obj","prop","Symbol","debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","TaskExecutor","title","options","ExecutionSession","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","undefined","format","getReadableTimeString","plans","planningModel","defaultModel","userInstruction","yamlString","reportOptions","session","taskTitleStr","userPromptToString","task","param","executorContext","uiContext","assert","executionPlanningModel","executionDefaultModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","abortSignal","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","referenceImageMessages","multimodalPromptToChatMessages","userPromptToMultimodalPrompt","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","action","Array","console","planImpl","standardPlan","planResult","setTimingFieldOnce","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","JSON","actions","thought","log","memory","usage","rawResponse","rawChoiceMessage","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","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":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuEA,MAAMI,QAAQC,AAAAA,IAAAA,uBAAAA,QAAAA,AAAAA,EAAS;AACvB,MAAMC,UAAUD,AAAAA,IAAAA,uBAAAA,QAAAA,AAAAA,EAAS,wBAAwB;IAAE,SAAS;AAAK;AACjE,MAAME,wCAAwC;AAM9C,MAAMC,4BAA4B;AAElC,SAASC,yBAAyBC,QAAgB;IAChD,IAAIA,SAAS,MAAM,IAAIF,2BACrB,OAAOE;IAGT,OAAO,GAAGA,SAAS,KAAK,CAAC,GAAGF,2BAA2B;eAC1C,EAAEE,SAAS,MAAM,GAAGF,0BAA0B,iBAAiB,CAAC;AAC/E;AAKO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AC,WAAW,GAAG,IAAIC,yCAAAA,WAAWA,CAAC;YACjCH;YACAC;YACA,WAAWC,KAAK,SAAS;YACzB,aAAa,IAAI,CAAC,cAAc;YAChC,iBAAiBA,KAAK,eAAe;QACvC;IACF;AA+8BF;AAkBO,SAASzB,mCACdjG,IAAmB,EACnBG,SAAgC;IAEhC,MAAMyH,SAASzH,WAAW;IAC1B,IAAIyH,UAAUA,OAAO,MAAM,GAAG,GAAG;QAC/B,MAAMC,gBAAyC,EAAE;QACjD,IAAK,IAAI1G,IAAI,GAAGA,IAAIyG,OAAO,MAAM,GAAG,GAAGzG,IAAK;YAC1C,MAAM2G,QAAQF,MAAM,CAACzG,EAAE;YACvB0G,cAAc,IAAI,CAAC;gBACjB,MAAM;gBACN,IAAIC,MAAM,UAAU;gBACpB,YAAYA;gBACZ,aAAa,CAAC,eAAe,EAAE3G,IAAI,EAAE,CAAC,EAAEyG,OAAO,MAAM,EAAE;gBACvD,QAAQ;YACV;QACF;QAKA5H,KAAK,QAAQ,GAAGA,KAAK,QAAQ,GACzB;eAAI6H;eAAkB7H,KAAK,QAAQ;SAAC,GACpC6H;IACN;IACA,IAAI1H,WAAW,oBACbA,UAAU,kBAAkB,GAAGf;AAEnC"}
@@ -232,7 +232,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
232
232
  return;
233
233
  }
234
234
  }
235
- const getMidsceneVersion = ()=>"1.11.0";
235
+ const getMidsceneVersion = ()=>"1.11.1-beta-20260819031908.0";
236
236
  const parsePrompt = (prompt)=>{
237
237
  if ('string' == typeof prompt) return {
238
238
  textPrompt: prompt,
@@ -41,7 +41,7 @@ const sampleReturnEmailSubGoal = {
41
41
  index: 3,
42
42
  description: 'Return the filled email address'
43
43
  };
44
- const buildPlanningMultiTurnExample = ({ includeSubGoals, locatePromptSpec, actionOutputProtocol })=>{
44
+ const buildPlanningMultiTurnExample = ({ includeSubGoals, includeThought, includeLog, locatePromptSpec, actionOutputProtocol })=>{
45
45
  const renderSubGoalsContent = (content, fallbackContent = '')=>includeSubGoals ? content : fallbackContent;
46
46
  const tapNameFieldExample = (0, external_action_example_js_namespaceObject.buildActionExample)((0, external_action_example_js_namespaceObject.createSampleTapAction)('Name input field in the registration form'), {
47
47
  locatePromptSpec,
@@ -74,7 +74,7 @@ Below is an example of a multi-turn conversation for "fill out the registration
74
74
  **Your response:**
75
75
 
76
76
  ${(0, external_planning_response_example_js_namespaceObject.buildPlanningResponseExample)({
77
- planning: `The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. ${renderSubGoalsContent("I'll break this down into sub-goals and start with the Name field.", 'I should start by clicking on the Name field.')} Note: The instruction is to fill the form only (not submit), and return the email at the end.`,
77
+ planning: includeThought ? `The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. ${renderSubGoalsContent("I'll break this down into sub-goals and start with the Name field.", 'I should start by clicking on the Name field.')} Note: The instruction is to fill the form only (not submit), and return the email at the end.` : void 0,
78
78
  updateSubGoals: includeSubGoals ? [
79
79
  {
80
80
  ...sampleNameSubGoal,
@@ -89,7 +89,7 @@ ${(0, external_planning_response_example_js_namespaceObject.buildPlanningRespons
89
89
  status: 'pending'
90
90
  }
91
91
  ] : void 0,
92
- log: 'Click on the Name field to start filling the form',
92
+ log: includeLog ? 'Click on the Name field to start filling the form' : void 0,
93
93
  actionExample: tapNameFieldExample
94
94
  })}
95
95
 
@@ -121,8 +121,8 @@ ${renderSubGoalsContent((0, external_sub_goals_text_js_namespaceObject.buildSubG
121
121
  **Your response:**
122
122
 
123
123
  ${(0, external_planning_response_example_js_namespaceObject.buildPlanningResponseExample)({
124
- planning: `The Name field is now focused. I need to type 'John' into this field. ${renderSubGoalsContent('Current sub-goal is running, will be completed after input.', "After this, I'll need to fill the Email field as well.")}`,
125
- log: "Typing 'John' into the Name field",
124
+ planning: includeThought ? `The Name field is now focused. I need to type 'John' into this field. ${renderSubGoalsContent('Current sub-goal is running, will be completed after input.', "After this, I'll need to fill the Email field as well.")}` : void 0,
125
+ log: includeLog ? "Typing 'John' into the Name field" : void 0,
126
126
  actionExample: inputNameExample
127
127
  })}
128
128
 
@@ -155,12 +155,12 @@ ${renderSubGoalsContent((0, external_sub_goals_text_js_namespaceObject.buildSubG
155
155
  **Your response:**
156
156
 
157
157
  ${(0, external_planning_response_example_js_namespaceObject.buildPlanningResponseExample)({
158
- planning: `The Name field now shows 'John'. ${renderSubGoalsContent('Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.', "Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.")}`,
158
+ planning: includeThought ? `The Name field now shows 'John'. ${renderSubGoalsContent('Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.', "Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.")}` : void 0,
159
159
  markSubGoalsDone: includeSubGoals ? [
160
160
  1
161
161
  ] : void 0,
162
162
  memory: includeSubGoals ? "Name field has been filled with 'John'" : void 0,
163
- log: 'Moving to the Email field',
163
+ log: includeLog ? 'Moving to the Email field' : void 0,
164
164
  actionExample: tapEmailFieldExample
165
165
  })}
166
166
 
@@ -192,8 +192,8 @@ ${renderSubGoalsContent((0, external_sub_goals_text_js_namespaceObject.buildSubG
192
192
  **Your response:**
193
193
 
194
194
  ${(0, external_planning_response_example_js_namespaceObject.buildPlanningResponseExample)({
195
- planning: `The Email field is now focused. I'll enter 'john@example.com'. ${renderSubGoalsContent('After this, sub-goal 2 will be complete and my task will be done.', 'After this, both required fields will be filled and my task will be complete.')}`,
196
- log: 'Typing email address into the Email field',
195
+ planning: includeThought ? `The Email field is now focused. I'll enter 'john@example.com'. ${renderSubGoalsContent('After this, sub-goal 2 will be complete and my task will be done.', 'After this, both required fields will be filled and my task will be complete.')}` : void 0,
196
+ log: includeLog ? 'Typing email address into the Email field' : void 0,
197
197
  actionExample: inputEmailExample
198
198
  })}
199
199
 
@@ -226,7 +226,7 @@ ${renderSubGoalsContent((0, external_sub_goals_text_js_namespaceObject.buildSubG
226
226
  **Your response:**
227
227
 
228
228
  ${(0, external_planning_response_example_js_namespaceObject.buildPlanningResponseExample)({
229
- planning: `Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. ${renderSubGoalsContent("Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.", "The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.")}`,
229
+ planning: includeThought ? `Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. ${renderSubGoalsContent("Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.", "The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.")}` : void 0,
230
230
  markSubGoalsDone: includeSubGoals ? [
231
231
  2,
232
232
  3
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/prompt/planning/multi-turn-example.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/prompt/planning/multi-turn-example.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { LocateResultPromptSpec } from '../../shared/model-locate-result';\nimport {\n buildActionExample,\n createSampleInputAction,\n createSampleTapAction,\n} from './action-example';\nimport type { PlanningActionOutputProtocol } from './action-output-protocol';\nimport { buildPlanningResponseExample } from './planning-response-example';\nimport { buildSubGoalsText } from './sub-goals-text';\n\nconst sampleNameSubGoal = {\n index: 1,\n description: \"Fill in the Name field with 'John'\",\n};\nconst sampleEmailSubGoal = {\n index: 2,\n description: \"Fill in the Email field with 'john@example.com'\",\n};\nconst sampleReturnEmailSubGoal = {\n index: 3,\n description: 'Return the filled email address',\n};\n\nexport const buildPlanningMultiTurnExample = ({\n includeSubGoals,\n locatePromptSpec,\n actionOutputProtocol,\n}: {\n includeSubGoals: boolean;\n locatePromptSpec?: LocateResultPromptSpec;\n actionOutputProtocol: PlanningActionOutputProtocol;\n}) => {\n const renderSubGoalsContent = (content: string, fallbackContent = '') =>\n includeSubGoals ? content : fallbackContent;\n\n const tapNameFieldExample = buildActionExample(\n createSampleTapAction('Name input field in the registration form'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 2,\n actionOutputProtocol,\n },\n );\n const inputNameExample = buildActionExample(createSampleInputAction('John'), {\n actionOutputProtocol,\n });\n const tapEmailFieldExample = buildActionExample(\n createSampleTapAction('Email input field in the registration form'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 3,\n actionOutputProtocol,\n },\n );\n const inputEmailExample = buildActionExample(\n createSampleInputAction('john@example.com'),\n { actionOutputProtocol },\n );\n\n return `\n## Multi-turn Conversation Example\n\nBelow is an example of a multi-turn conversation for \"fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address\":\n\n### Turn 1 - Initial instruction\n\n**User message:**\n<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>\n\n**Screenshot:** [Shows a registration form with empty Name and Email fields]\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: `The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. ${renderSubGoalsContent(\n \"I'll break this down into sub-goals and start with the Name field.\",\n 'I should start by clicking on the Name field.',\n )} Note: The instruction is to fill the form only (not submit), and return the email at the end.`,\n updateSubGoals: includeSubGoals\n ? [\n {\n ...sampleNameSubGoal,\n status: 'pending',\n },\n {\n ...sampleEmailSubGoal,\n status: 'pending',\n },\n {\n ...sampleReturnEmailSubGoal,\n status: 'pending',\n },\n ]\n : undefined,\n log: 'Click on the Name field to start filling the form',\n actionExample: tapNameFieldExample,\n})}\n\n### Turn 2 - After clicking Name field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n {\n ...sampleNameSubGoal,\n status: 'running',\n logs: ['Click on the Name field to start filling the form'],\n },\n { ...sampleEmailSubGoal, status: 'pending' },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name field now focused/active]\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: `The Name field is now focused. I need to type 'John' into this field. ${renderSubGoalsContent(\n 'Current sub-goal is running, will be completed after input.',\n \"After this, I'll need to fill the Email field as well.\",\n )}`,\n log: \"Typing 'John' into the Name field\",\n actionExample: inputNameExample,\n})}\n\n### Turn 3 - After entering name\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n {\n ...sampleNameSubGoal,\n status: 'running',\n logs: [\n 'Click on the Name field to start filling the form',\n \"Typing 'John' into the Name field\",\n ],\n },\n { ...sampleEmailSubGoal, status: 'pending' },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name field containing 'John']\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: `The Name field now shows 'John'. ${renderSubGoalsContent(\n 'Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.',\n \"Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.\",\n )}`,\n markSubGoalsDone: includeSubGoals ? [1] : undefined,\n memory: includeSubGoals\n ? \"Name field has been filled with 'John'\"\n : undefined,\n log: 'Moving to the Email field',\n actionExample: tapEmailFieldExample,\n})}\n\n### Turn 4 - After clicking Email field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n { ...sampleNameSubGoal, status: 'finished' },\n {\n ...sampleEmailSubGoal,\n status: 'running',\n logs: ['Moving to the Email field'],\n },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name='John' and Email field focused]\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: `The Email field is now focused. I'll enter 'john@example.com'. ${renderSubGoalsContent(\n 'After this, sub-goal 2 will be complete and my task will be done.',\n 'After this, both required fields will be filled and my task will be complete.',\n )}`,\n log: 'Typing email address into the Email field',\n actionExample: inputEmailExample,\n})}\n\n### Turn 5 - After entering email (${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')})\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n { ...sampleNameSubGoal, status: 'finished' },\n {\n ...sampleEmailSubGoal,\n status: 'running',\n logs: [\n 'Moving to the Email field',\n 'Typing email address into the Email field',\n ],\n },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: `Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. ${renderSubGoalsContent(\n \"Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.\",\n \"The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.\",\n )}`,\n markSubGoalsDone: includeSubGoals ? [2, 3] : undefined,\n complete: {\n success: true,\n message: 'john@example.com',\n },\n})}\n`;\n};\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","sampleNameSubGoal","sampleEmailSubGoal","sampleReturnEmailSubGoal","buildPlanningMultiTurnExample","includeSubGoals","locatePromptSpec","actionOutputProtocol","renderSubGoalsContent","content","fallbackContent","tapNameFieldExample","buildActionExample","createSampleTapAction","inputNameExample","createSampleInputAction","tapEmailFieldExample","inputEmailExample","buildPlanningResponseExample","undefined","buildSubGoalsText"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;ACIA,MAAMI,oBAAoB;IACxB,OAAO;IACP,aAAa;AACf;AACA,MAAMC,qBAAqB;IACzB,OAAO;IACP,aAAa;AACf;AACA,MAAMC,2BAA2B;IAC/B,OAAO;IACP,aAAa;AACf;AAEO,MAAMC,gCAAgC,CAAC,EAC5CC,eAAe,EACfC,gBAAgB,EAChBC,oBAAoB,EAKrB;IACC,MAAMC,wBAAwB,CAACC,SAAiBC,kBAAkB,EAAE,GAClEL,kBAAkBI,UAAUC;IAE9B,MAAMC,sBAAsBC,AAAAA,IAAAA,2CAAAA,kBAAAA,AAAAA,EAC1BC,AAAAA,IAAAA,2CAAAA,qBAAAA,AAAAA,EAAsB,8CACtB;QACEP;QACA,0BAA0B;QAC1BC;IACF;IAEF,MAAMO,mBAAmBF,AAAAA,IAAAA,2CAAAA,kBAAAA,AAAAA,EAAmBG,AAAAA,IAAAA,2CA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C7C,UAAU;YACR,SAAS;YACT,SAAS;QACX;IACF,GAAG;AACH,CAAC;AACD"}
1
+ {"version":3,"file":"ai-model/prompt/planning/multi-turn-example.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/prompt/planning/multi-turn-example.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { LocateResultPromptSpec } from '../../shared/model-locate-result';\nimport {\n buildActionExample,\n createSampleInputAction,\n createSampleTapAction,\n} from './action-example';\nimport type { PlanningActionOutputProtocol } from './action-output-protocol';\nimport { buildPlanningResponseExample } from './planning-response-example';\nimport { buildSubGoalsText } from './sub-goals-text';\n\nconst sampleNameSubGoal = {\n index: 1,\n description: \"Fill in the Name field with 'John'\",\n};\nconst sampleEmailSubGoal = {\n index: 2,\n description: \"Fill in the Email field with 'john@example.com'\",\n};\nconst sampleReturnEmailSubGoal = {\n index: 3,\n description: 'Return the filled email address',\n};\n\nexport const buildPlanningMultiTurnExample = ({\n includeSubGoals,\n includeThought,\n includeLog,\n locatePromptSpec,\n actionOutputProtocol,\n}: {\n includeSubGoals: boolean;\n includeThought: boolean;\n includeLog: boolean;\n locatePromptSpec?: LocateResultPromptSpec;\n actionOutputProtocol: PlanningActionOutputProtocol;\n}) => {\n const renderSubGoalsContent = (content: string, fallbackContent = '') =>\n includeSubGoals ? content : fallbackContent;\n\n const tapNameFieldExample = buildActionExample(\n createSampleTapAction('Name input field in the registration form'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 2,\n actionOutputProtocol,\n },\n );\n const inputNameExample = buildActionExample(createSampleInputAction('John'), {\n actionOutputProtocol,\n });\n const tapEmailFieldExample = buildActionExample(\n createSampleTapAction('Email input field in the registration form'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 3,\n actionOutputProtocol,\n },\n );\n const inputEmailExample = buildActionExample(\n createSampleInputAction('john@example.com'),\n { actionOutputProtocol },\n );\n\n return `\n## Multi-turn Conversation Example\n\nBelow is an example of a multi-turn conversation for \"fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address\":\n\n### Turn 1 - Initial instruction\n\n**User message:**\n<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>\n\n**Screenshot:** [Shows a registration form with empty Name and Email fields]\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: includeThought\n ? `The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. ${renderSubGoalsContent(\n \"I'll break this down into sub-goals and start with the Name field.\",\n 'I should start by clicking on the Name field.',\n )} Note: The instruction is to fill the form only (not submit), and return the email at the end.`\n : undefined,\n updateSubGoals: includeSubGoals\n ? [\n {\n ...sampleNameSubGoal,\n status: 'pending',\n },\n {\n ...sampleEmailSubGoal,\n status: 'pending',\n },\n {\n ...sampleReturnEmailSubGoal,\n status: 'pending',\n },\n ]\n : undefined,\n log: includeLog\n ? 'Click on the Name field to start filling the form'\n : undefined,\n actionExample: tapNameFieldExample,\n})}\n\n### Turn 2 - After clicking Name field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n {\n ...sampleNameSubGoal,\n status: 'running',\n logs: ['Click on the Name field to start filling the form'],\n },\n { ...sampleEmailSubGoal, status: 'pending' },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name field now focused/active]\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: includeThought\n ? `The Name field is now focused. I need to type 'John' into this field. ${renderSubGoalsContent(\n 'Current sub-goal is running, will be completed after input.',\n \"After this, I'll need to fill the Email field as well.\",\n )}`\n : undefined,\n log: includeLog ? \"Typing 'John' into the Name field\" : undefined,\n actionExample: inputNameExample,\n})}\n\n### Turn 3 - After entering name\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n {\n ...sampleNameSubGoal,\n status: 'running',\n logs: [\n 'Click on the Name field to start filling the form',\n \"Typing 'John' into the Name field\",\n ],\n },\n { ...sampleEmailSubGoal, status: 'pending' },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name field containing 'John']\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: includeThought\n ? `The Name field now shows 'John'. ${renderSubGoalsContent(\n 'Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.',\n \"Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.\",\n )}`\n : undefined,\n markSubGoalsDone: includeSubGoals ? [1] : undefined,\n memory: includeSubGoals\n ? \"Name field has been filled with 'John'\"\n : undefined,\n log: includeLog ? 'Moving to the Email field' : undefined,\n actionExample: tapEmailFieldExample,\n})}\n\n### Turn 4 - After clicking Email field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n { ...sampleNameSubGoal, status: 'finished' },\n {\n ...sampleEmailSubGoal,\n status: 'running',\n logs: ['Moving to the Email field'],\n },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name='John' and Email field focused]\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: includeThought\n ? `The Email field is now focused. I'll enter 'john@example.com'. ${renderSubGoalsContent(\n 'After this, sub-goal 2 will be complete and my task will be done.',\n 'After this, both required fields will be filled and my task will be complete.',\n )}`\n : undefined,\n log: includeLog ? 'Typing email address into the Email field' : undefined,\n actionExample: inputEmailExample,\n})}\n\n### Turn 5 - After entering email (${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')})\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n${renderSubGoalsContent(\n buildSubGoalsText([\n { ...sampleNameSubGoal, status: 'finished' },\n {\n ...sampleEmailSubGoal,\n status: 'running',\n logs: [\n 'Moving to the Email field',\n 'Typing email address into the Email field',\n ],\n },\n { ...sampleReturnEmailSubGoal, status: 'pending' },\n ]),\n)}\n\n**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']\n\n**Your response:**\n\n${buildPlanningResponseExample({\n planning: includeThought\n ? `Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. ${renderSubGoalsContent(\n \"Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.\",\n \"The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.\",\n )}`\n : undefined,\n markSubGoalsDone: includeSubGoals ? [2, 3] : undefined,\n complete: {\n success: true,\n message: 'john@example.com',\n },\n})}\n`;\n};\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","sampleNameSubGoal","sampleEmailSubGoal","sampleReturnEmailSubGoal","buildPlanningMultiTurnExample","includeSubGoals","includeThought","includeLog","locatePromptSpec","actionOutputProtocol","renderSubGoalsContent","content","fallbackContent","tapNameFieldExample","buildActionExample","createSampleTapAction","inputNameExample","createSampleInputAction","tapEmailFieldExample","inputEmailExample","buildPlanningResponseExample","undefined","buildSubGoalsText"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO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webpack_exports__, {
27
27
  buildPlanningResponseExample: ()=>buildPlanningResponseExample
28
28
  });
29
29
  const buildPlanningResponseExample = (input)=>{
30
- const sections = [
30
+ const sections = input.planning ? [
31
31
  `<planning>${input.planning}</planning>`
32
- ];
32
+ ] : [];
33
33
  if (input.updateSubGoals?.length) {
34
34
  const subGoals = input.updateSubGoals.map(({ index, status, description })=>` <sub-goal index="${index}" status="${status}">${description}</sub-goal>`).join('\n');
35
35
  sections.push(`<update-plan-content>\n${subGoals}\n</update-plan-content>`);
@@ -42,7 +42,8 @@ const buildPlanningResponseExample = (input)=>{
42
42
  if (input.complete) sections.push(`<complete success="${input.complete.success}">${input.complete.message}</complete>`);
43
43
  else {
44
44
  if (!input.actionExample) throw new Error('Cannot build planning response example without an action example');
45
- sections.push(`<log>${input.log}</log>`, input.actionExample);
45
+ if (input.log) sections.push(`<log>${input.log}</log>`);
46
+ sections.push(input.actionExample);
46
47
  }
47
48
  return sections.join('\n');
48
49
  };
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/prompt/planning/planning-response-example.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/prompt/planning/planning-response-example.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { SubGoalStatus } from '@/types';\n\ntype PlanningSubGoalExample = {\n index: number;\n status: Extract<SubGoalStatus, 'pending' | 'finished'>;\n description: string;\n};\n\ntype PlanningResponseActionExample = {\n log: string;\n actionExample: string | undefined;\n complete?: never;\n};\n\ntype PlanningResponseCompleteExample = {\n complete: {\n success: boolean;\n message: string;\n };\n log?: never;\n actionExample?: never;\n};\n\ntype BuildPlanningResponseExampleInput = {\n planning: string;\n updateSubGoals?: PlanningSubGoalExample[];\n markSubGoalsDone?: number[];\n memory?: string;\n} & (PlanningResponseActionExample | PlanningResponseCompleteExample);\n\nexport const buildPlanningResponseExample = (\n input: BuildPlanningResponseExampleInput,\n) => {\n const sections = [`<planning>${input.planning}</planning>`];\n\n if (input.updateSubGoals?.length) {\n const subGoals = input.updateSubGoals\n .map(\n ({ index, status, description }) =>\n ` <sub-goal index=\"${index}\" status=\"${status}\">${description}</sub-goal>`,\n )\n .join('\\n');\n sections.push(`<update-plan-content>\\n${subGoals}\\n</update-plan-content>`);\n }\n\n if (input.markSubGoalsDone?.length) {\n const subGoals = input.markSubGoalsDone\n .map((index) => ` <sub-goal index=\"${index}\" status=\"finished\" />`)\n .join('\\n');\n sections.push(`<mark-sub-goal-done>\\n${subGoals}\\n</mark-sub-goal-done>`);\n }\n\n if (input.memory) {\n sections.push(`<memory>${input.memory}</memory>`);\n }\n\n if (input.complete) {\n sections.push(\n `<complete success=\"${input.complete.success}\">${input.complete.message}</complete>`,\n );\n } else {\n if (!input.actionExample) {\n throw new Error(\n 'Cannot build planning response example without an action example',\n );\n }\n sections.push(`<log>${input.log}</log>`, input.actionExample);\n }\n\n return sections.join('\\n');\n};\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","buildPlanningResponseExample","input","sections","subGoals","index","status","description","Error"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;I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CAAC,OAAO,CAAC,WAAW,CAAC;SAEjF;QACL,IAAI,CAACA,MAAM,aAAa,EACtB,MAAM,IAAIM,MACR;QAGJL,SAAS,IAAI,CAAC,CAAC,KAAK,EAAED,MAAM,GAAG,CAAC,MAAM,CAAC,EAAEA,MAAM,aAAa;IAC9D;IAEA,OAAOC,SAAS,IAAI,CAAC;AACvB"}
1
+ {"version":3,"file":"ai-model/prompt/planning/planning-response-example.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/prompt/planning/planning-response-example.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { SubGoalStatus } from '@/types';\n\ntype PlanningSubGoalExample = {\n index: number;\n status: Extract<SubGoalStatus, 'pending' | 'finished'>;\n description: string;\n};\n\ntype PlanningResponseActionExample = {\n log?: string;\n actionExample: string | undefined;\n complete?: never;\n};\n\ntype PlanningResponseCompleteExample = {\n complete: {\n success: boolean;\n message: string;\n };\n log?: never;\n actionExample?: never;\n};\n\ntype BuildPlanningResponseExampleInput = {\n planning?: string;\n updateSubGoals?: PlanningSubGoalExample[];\n markSubGoalsDone?: number[];\n memory?: string;\n} & (PlanningResponseActionExample | PlanningResponseCompleteExample);\n\nexport const buildPlanningResponseExample = (\n input: BuildPlanningResponseExampleInput,\n) => {\n const sections = input.planning\n ? [`<planning>${input.planning}</planning>`]\n : [];\n\n if (input.updateSubGoals?.length) {\n const subGoals = input.updateSubGoals\n .map(\n ({ index, status, description }) =>\n ` <sub-goal index=\"${index}\" status=\"${status}\">${description}</sub-goal>`,\n )\n .join('\\n');\n sections.push(`<update-plan-content>\\n${subGoals}\\n</update-plan-content>`);\n }\n\n if (input.markSubGoalsDone?.length) {\n const subGoals = input.markSubGoalsDone\n .map((index) => ` <sub-goal index=\"${index}\" status=\"finished\" />`)\n .join('\\n');\n sections.push(`<mark-sub-goal-done>\\n${subGoals}\\n</mark-sub-goal-done>`);\n }\n\n if (input.memory) {\n sections.push(`<memory>${input.memory}</memory>`);\n }\n\n if (input.complete) {\n sections.push(\n `<complete success=\"${input.complete.success}\">${input.complete.message}</complete>`,\n );\n } else {\n if (!input.actionExample) {\n throw new Error(\n 'Cannot build planning response example without an action example',\n );\n }\n if (input.log) {\n sections.push(`<log>${input.log}</log>`);\n }\n sections.push(input.actionExample);\n }\n\n return sections.join('\\n');\n};\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","buildPlanningResponseExample","input","sections","subGoals","index","status","description","Error"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;ACwBO,MAAMI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("./action-example.js"
34
34
  const external_action_output_protocol_js_namespaceObject = require("./action-output-protocol.js");
35
35
  const external_multi_turn_example_js_namespaceObject = require("./multi-turn-example.js");
36
36
  async function buildStandardPlanningSystemPrompt(input) {
37
- const { actionSpace, includeLocateInPlanning, locatePromptSpec, includeSubGoals, actionOutputProtocol = external_action_output_protocol_js_namespaceObject.defaultMidsceneActionOutputProtocol } = input;
37
+ const { actionSpace, includeLocateInPlanning, locatePromptSpec, includeSubGoals, includeThought = true, includeLog = true, actionOutputProtocol = external_action_output_protocol_js_namespaceObject.defaultMidsceneActionOutputProtocol } = input;
38
38
  const preferredLanguage = (0, env_namespaceObject.getPreferredLanguage)();
39
39
  if (includeLocateInPlanning && !locatePromptSpec) throw new Error((0, errors_js_namespaceObject.planningModelFamilyRequiredForLocateMessage)());
40
40
  const actionList = (0, external_action_description_js_namespaceObject.buildActionSpaceDescription)(actionSpace, {
@@ -46,12 +46,14 @@ async function buildStandardPlanningSystemPrompt(input) {
46
46
  const actionOutputTagsText = actionOutputProtocol.actionOutputTagNames.map((tagName)=>`<${tagName}>`).join(', ');
47
47
  const shouldIncludeSubGoals = includeSubGoals ?? false;
48
48
  const renderSubGoalsContent = (content, fallbackContent = '')=>shouldIncludeSubGoals ? content : fallbackContent;
49
+ const renderThoughtContent = (content, fallbackContent = '')=>includeThought ? content : fallbackContent;
50
+ const renderLogContent = (content, fallbackContent = '')=>includeLog ? content : fallbackContent;
49
51
  const completionCheckStepNumber = shouldIncludeSubGoals ? 3 : 2;
50
52
  const actionStepNumber = completionCheckStepNumber + 1;
51
53
  return `
52
54
  Target: You are an expert to manipulate the UI to accomplish the user's instruction. User will give you an instruction, some screenshots, background knowledge and previous logs indicating what have been done. Your task is to accomplish the instruction by thinking through the path to complete the task and give the next action to execute.
53
55
 
54
- ## Step 1: ${renderSubGoalsContent('Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)', 'Observe (related tags: <planning>)')}
56
+ ## Step 1: ${renderSubGoalsContent('Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)', renderThoughtContent('Observe (related tags: <planning>)', 'Observe'))}
55
57
 
56
58
  First, observe the current screenshot and previous logs${renderSubGoalsContent(", then break down the user's instruction into multiple high-level sub-goals. Update the status of sub-goals based on what you see in the current screenshot.", ' to understand the current state.')}
57
59
 
@@ -60,13 +62,13 @@ ${renderSubGoalsContent(`### Observation Guidelines
60
62
  - Treat visible summaries, thumbnails, cropped content, and partially visible lists as potentially incomplete when the task depends on precise details.
61
63
  - If the current view does not provide enough information to decide safely, use available UI affordances such as opening details, expanding content, previewing, enlarging, zooming, or scrolling before acting.`)}
62
64
 
63
- ### <planning> tag (REQUIRED)
65
+ ${renderThoughtContent(`### <planning> tag (REQUIRED)
64
66
 
65
67
  REQUIRED: You MUST always output the <planning> tag. Never skip it.
66
68
 
67
69
  Include your planning details in the <planning> tag. It should answer: ${renderSubGoalsContent("What is the user's requirement? What is the current state based on the screenshot? Are all sub-goals completed? If not, what should be the next action?", 'What is the current state based on the screenshot? What should be the next action?')} Write it naturally without numbering or section headers.
68
70
 
69
- CRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: "fill out the form" means only fill fields, do NOT submit; "click the button" means only click, do NOT wait for page load or verify results; "type 'hello'" means only type, do NOT press Enter.
71
+ CRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: "fill out the form" means only fill fields, do NOT submit; "click the button" means only click, do NOT wait for page load or verify results; "type 'hello'" means only type, do NOT press Enter.`)}
70
72
 
71
73
  ${renderSubGoalsContent(`### <update-plan-content> tag
72
74
 
@@ -210,7 +212,7 @@ ${renderSubGoalsContent('', `**Page navigation restriction:**
210
212
  - the 'message' is the information that will be provided to the user. If the user asks for a specific format, strictly follow that.
211
213
  - If you output <complete>, do NOT output ${actionOutputTagsText}. The task ends here.
212
214
 
213
- ## Step ${actionStepNumber}: Determine Next Action (related tags: <log>, ${actionOutputTagsText}, <error>)
215
+ ## Step ${actionStepNumber}: Determine Next Action (related tags: ${renderLogContent('<log>, ')}${actionOutputTagsText}, <error>)
214
216
 
215
217
  ONLY if the task is not complete: Think what the next action is according to the current screenshot${renderSubGoalsContent(' and the plan')}.
216
218
 
@@ -233,7 +235,7 @@ ${includeLocateInPlanning ? (0, external_locate_grounding_rules_js_namespaceObje
233
235
 
234
236
  ${actionList}
235
237
 
236
- ### Log to give user feedback (preamble message)
238
+ ${renderLogContent(`### Log to give user feedback (preamble message)
237
239
 
238
240
  The <log> tag is a brief preamble message to the user explaining what you're about to do. It should follow these principles and examples:
239
241
 
@@ -246,7 +248,7 @@ The <log> tag is a brief preamble message to the user explaining what you're abo
246
248
  - <log>Click the login button</log>
247
249
  - <log>Scroll to find the 'Yes' button in popup</log>
248
250
  - <log>Previous actions failed to find the 'Yes' button, i will try again</log>
249
- - <log>Go back to find the login button</log>
251
+ - <log>Go back to find the login button</log>`)}
250
252
 
251
253
  ### If there is some action to do ...
252
254
 
@@ -274,9 +276,9 @@ For example:
274
276
 
275
277
  Return in XML format following this decision flow:
276
278
 
277
- **Always include (REQUIRED):**
279
+ ${renderThoughtContent(`**Always include (REQUIRED):**
278
280
  <!-- Step 1: Observe and Plan -->
279
- <planning>Your planning details here. NEVER skip this tag.</planning>
281
+ <planning>Your planning details here. NEVER skip this tag.</planning>`)}
280
282
  ${renderSubGoalsContent(`<!-- required when no update-plan-content is provided in the previous response -->
281
283
  <update-plan-content>...</update-plan-content>
282
284
 
@@ -295,7 +297,7 @@ ${renderSubGoalsContent(`<!-- required when no update-plan-content is provided i
295
297
 
296
298
  **Path B: If the ${renderSubGoalsContent('goal is NOT complete', 'instruction is NOT fulfilled')} yet (Step ${actionStepNumber})**
297
299
  <!-- Determine next action -->
298
- <log>...</log>
300
+ ${renderLogContent('<log>...</log>')}
299
301
  ${actionOutputProtocol.actionOutputPlaceholder}
300
302
 
301
303
  <!-- OR if there's an error -->
@@ -303,6 +305,8 @@ ${actionOutputProtocol.actionOutputPlaceholder}
303
305
 
304
306
  ${(0, external_multi_turn_example_js_namespaceObject.buildPlanningMultiTurnExample)({
305
307
  includeSubGoals: shouldIncludeSubGoals,
308
+ includeThought,
309
+ includeLog,
306
310
  locatePromptSpec,
307
311
  actionOutputProtocol
308
312
  })}`;