@midscene/core 1.12.8-beta-20260916030003.0 → 1.12.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/es/agent/task-builder.mjs +5 -10
  2. package/dist/es/agent/task-builder.mjs.map +1 -1
  3. package/dist/es/agent/utils.mjs +1 -1
  4. package/dist/es/ai-model/prompt/planning/system-prompt.mjs +19 -1
  5. package/dist/es/ai-model/prompt/planning/system-prompt.mjs.map +1 -1
  6. package/dist/es/ai-model/workflows/planning/custom-planning.mjs +1 -2
  7. package/dist/es/ai-model/workflows/planning/custom-planning.mjs.map +1 -1
  8. package/dist/es/ai-model/workflows/planning/locate-normalization.mjs +25 -26
  9. package/dist/es/ai-model/workflows/planning/locate-normalization.mjs.map +1 -1
  10. package/dist/es/ai-model/workflows/planning/parse-planning-actions.mjs +44 -0
  11. package/dist/es/ai-model/workflows/planning/parse-planning-actions.mjs.map +1 -0
  12. package/dist/es/ai-model/workflows/planning/standard-planning.mjs +8 -8
  13. package/dist/es/ai-model/workflows/planning/standard-planning.mjs.map +1 -1
  14. package/dist/es/common.mjs +4 -1
  15. package/dist/es/common.mjs.map +1 -1
  16. package/dist/es/device/index.mjs +22 -45
  17. package/dist/es/device/index.mjs.map +1 -1
  18. package/dist/es/report-html-template.mjs +1 -1
  19. package/dist/es/utils.mjs +1 -1
  20. package/dist/lib/agent/task-builder.js +4 -9
  21. package/dist/lib/agent/task-builder.js.map +1 -1
  22. package/dist/lib/agent/utils.js +1 -1
  23. package/dist/lib/ai-model/prompt/planning/system-prompt.js +19 -1
  24. package/dist/lib/ai-model/prompt/planning/system-prompt.js.map +1 -1
  25. package/dist/lib/ai-model/workflows/planning/custom-planning.js +1 -2
  26. package/dist/lib/ai-model/workflows/planning/custom-planning.js.map +1 -1
  27. package/dist/lib/ai-model/workflows/planning/locate-normalization.js +28 -26
  28. package/dist/lib/ai-model/workflows/planning/locate-normalization.js.map +1 -1
  29. package/dist/lib/ai-model/workflows/planning/parse-planning-actions.js +78 -0
  30. package/dist/lib/ai-model/workflows/planning/parse-planning-actions.js.map +1 -0
  31. package/dist/lib/ai-model/workflows/planning/standard-planning.js +8 -8
  32. package/dist/lib/ai-model/workflows/planning/standard-planning.js.map +1 -1
  33. package/dist/lib/common.js +7 -1
  34. package/dist/lib/common.js.map +1 -1
  35. package/dist/lib/device/index.js +21 -50
  36. package/dist/lib/device/index.js.map +1 -1
  37. package/dist/lib/report-html-template.js +1 -1
  38. package/dist/lib/utils.js +1 -1
  39. package/dist/types/ai-model/workflows/planning/locate-normalization.d.ts +5 -3
  40. package/dist/types/ai-model/workflows/planning/parse-planning-actions.d.ts +7 -0
  41. package/dist/types/common.d.ts +1 -0
  42. package/dist/types/device/index.d.ts +6 -25
  43. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  import { findAllMidsceneLocatorField, parseActionParam } from "../ai-model/index.mjs";
2
- import { findActionInActionSpaceOrThrow } from "../common.mjs";
2
+ import { findActionInActionSpaceOrThrow, validateRequiredLocateFields } from "../common.mjs";
3
3
  import { setTimingFieldOnce } from "../task-timing.mjs";
4
4
  import { ServiceError } from "../types.mjs";
5
5
  import { sleep } from "../utils.mjs";
@@ -99,19 +99,16 @@ class TaskBuilder {
99
99
  const action = findActionInActionSpaceOrThrow(planType, actionSpace);
100
100
  const param = plan.param;
101
101
  const locateFields = findAllMidsceneLocatorField(action.paramSchema);
102
- const requiredLocateFields = findAllMidsceneLocatorField(action.paramSchema, true);
102
+ validateRequiredLocateFields(param, action.paramSchema);
103
103
  locateFields.forEach((field)=>{
104
- if (param[field]) {
104
+ if (param?.[field]) {
105
105
  const locatePlan = locatePlanForLocate(param[field]);
106
106
  debug('will prepend locate param for field', `action.type=${planType}`, `param=${JSON.stringify(param[field])}`, `locatePlan=${JSON.stringify(locatePlan)}`, `hasLocatedPixelResult=${ifLocateParamHasLocatedPixelResult(param[field])}`);
107
107
  const locateTask = this.createLocateTask(locatePlan, param[field], context, (result)=>{
108
108
  param[field] = result;
109
109
  });
110
110
  context.tasks.push(locateTask);
111
- } else {
112
- assert(!requiredLocateFields.includes(field), `Required locate field '${field}' is not provided for action ${planType}`);
113
- debug(`field '${field}' is not provided for action ${planType}`);
114
- }
111
+ } else debug(`field '${field}' is not provided for action ${planType}`);
115
112
  });
116
113
  const task = {
117
114
  type: 'Action Space',
@@ -123,9 +120,7 @@ class TaskBuilder {
123
120
  debug('executing action', planType, param, `taskContext.element.center: ${taskContext.element?.center}`);
124
121
  const uiContext = taskContext.uiContext;
125
122
  assert(uiContext, 'uiContext is required for Action task');
126
- requiredLocateFields.forEach((field)=>{
127
- assert(param[field], `field '${field}' is required for action ${planType} but not provided. Cannot execute action ${planType}.`);
128
- });
123
+ validateRequiredLocateFields(param, action.paramSchema);
129
124
  setTimingFieldOnce(timing, 'beforeInvokeActionHookStart');
130
125
  const delayBeforeRunner = action.delayBeforeRunner ?? 200;
131
126
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"agent/task-builder.mjs","sources":["../../../src/agent/task-builder.ts"],"sourcesContent":["import { findAllMidsceneLocatorField, parseActionParam } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { findActionInActionSpaceOrThrow } from '@/common';\nimport type { AbstractInterface } from '@/device';\nimport type Service from '@/service';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport type {\n AIUsageInfo,\n DetailedLocateParam,\n DeviceAction,\n ElementCacheFeature,\n ExecutionTaskActionApply,\n ExecutionTaskApply,\n ExecutionTaskHitBy,\n ExecutionTaskPlanningLocateApply,\n LocateResultElement,\n LocateResultWithDump,\n PlanningAction,\n Rect,\n ServiceDump,\n} from '@/types';\nimport { ServiceError } from '@/types';\nimport { sleep } from '@/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport type { TaskCache } from './task-cache';\nimport { withUsageIntent } from './usage-intent';\nimport {\n ifLocateParamHasLocatedPixelResult,\n matchElementFromCache,\n matchElementFromPlan,\n transformLogicalElementToScreenshot,\n} from './utils';\n\nconst debug = getDebug('agent:task-builder');\n\n/**\n * Check if a cache object is non-empty\n */\nfunction hasNonEmptyCache(cache: unknown): boolean {\n return (\n cache !== null &&\n cache !== undefined &&\n typeof cache === 'object' &&\n Object.keys(cache).length > 0\n );\n}\n\nfunction invalidLocateElementReason(\n element: LocateResultElement,\n): string | undefined {\n const values = [element.center?.[0], element.center?.[1]];\n if (\n element.center?.length !== 2 ||\n values.some((value) => typeof value !== 'number' || !Number.isFinite(value))\n ) {\n return `Invalid locate result coordinates: ${JSON.stringify(element)}`;\n }\n return undefined;\n}\n\ntype LocateParamWithDeprecatedAlias = DetailedLocateParam & {\n deepThink?: boolean;\n};\n\nfunction normalizeLocateParam(\n param: string | DetailedLocateParam,\n): DetailedLocateParam {\n if (typeof param === 'string') {\n return { prompt: param };\n }\n\n const { deepThink, ...rest } = param as LocateParamWithDeprecatedAlias;\n const deepLocate = rest.deepLocate ?? deepThink;\n\n return deepLocate === undefined ? rest : { ...rest, deepLocate };\n}\n\nexport function locatePlanForLocate(param: string | DetailedLocateParam) {\n const locate = normalizeLocateParam(param);\n const locatePlan: PlanningAction<DetailedLocateParam> = {\n type: 'Locate',\n param: locate,\n thought: '',\n };\n return locatePlan;\n}\n\ninterface TaskBuilderDeps {\n interfaceInstance: AbstractInterface;\n service: Service;\n taskCache?: TaskCache;\n actionSpace: DeviceAction[];\n waitAfterAction?: number;\n}\n\ninterface BuildOptions {\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n}\n\ninterface PlanBuildContext {\n tasks: ExecutionTaskApply[];\n planningModel: ModelRuntime;\n defaultModel: ModelRuntime;\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n}\n\nexport class TaskBuilder {\n private readonly interface: AbstractInterface;\n\n private readonly service: Service;\n\n private readonly taskCache?: TaskCache;\n\n private readonly actionSpace: DeviceAction[];\n\n private readonly waitAfterAction?: number;\n\n constructor({\n interfaceInstance,\n service,\n taskCache,\n actionSpace,\n waitAfterAction,\n }: TaskBuilderDeps) {\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = taskCache;\n this.actionSpace = actionSpace;\n this.waitAfterAction = waitAfterAction;\n }\n\n public async build(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: BuildOptions,\n ): Promise<{ tasks: ExecutionTaskApply[] }> {\n const tasks: ExecutionTaskApply[] = [];\n const cacheable = options?.cacheable;\n\n const context: PlanBuildContext = {\n tasks,\n planningModel,\n defaultModel,\n cacheable,\n deepLocate: options?.deepLocate,\n abortSignal: options?.abortSignal,\n };\n\n type PlanHandler = (plan: PlanningAction) => Promise<void> | void;\n\n const planHandlers = new Map<string, PlanHandler>([\n [\n 'Locate',\n (plan) =>\n this.handleLocatePlan(\n plan as PlanningAction<DetailedLocateParam>,\n context,\n ),\n ],\n ['Finished', (plan) => this.handleFinishedPlan(plan, context)],\n ]);\n\n const defaultHandler: PlanHandler = (plan) =>\n this.handleActionPlan(plan, context);\n\n for (const plan of plans) {\n const handler = planHandlers.get(plan.type) ?? defaultHandler;\n await handler(plan);\n }\n\n return {\n tasks,\n };\n }\n\n private handleFinishedPlan(\n plan: PlanningAction,\n context: PlanBuildContext,\n ): void {\n const taskActionFinished: ExecutionTaskActionApply<null> = {\n type: 'Action Space',\n subType: 'Finished',\n param: null,\n thought: plan.thought,\n executor: async () => {},\n };\n context.tasks.push(taskActionFinished);\n }\n\n private async handleLocatePlan(\n plan: PlanningAction<DetailedLocateParam>,\n context: PlanBuildContext,\n ): Promise<void> {\n const taskLocate = this.createLocateTask(plan, plan.param, context);\n context.tasks.push(taskLocate);\n }\n\n private async handleActionPlan(\n plan: PlanningAction,\n context: PlanBuildContext,\n ): Promise<void> {\n const planType = plan.type;\n const actionSpace = this.actionSpace;\n const action = findActionInActionSpaceOrThrow(planType, actionSpace);\n const param = plan.param;\n\n const locateFields = findAllMidsceneLocatorField(action.paramSchema);\n\n const requiredLocateFields = findAllMidsceneLocatorField(\n action.paramSchema,\n true,\n );\n\n locateFields.forEach((field) => {\n if (param[field]) {\n // Always use createLocateTask for all locate params.\n // This ensures cache writing happens even when locatedPixelResult is available\n const locatePlan = locatePlanForLocate(param[field]);\n debug(\n 'will prepend locate param for field',\n `action.type=${planType}`,\n `param=${JSON.stringify(param[field])}`,\n `locatePlan=${JSON.stringify(locatePlan)}`,\n `hasLocatedPixelResult=${ifLocateParamHasLocatedPixelResult(param[field])}`,\n );\n const locateTask = this.createLocateTask(\n locatePlan,\n param[field],\n context,\n (result) => {\n param[field] = result;\n },\n );\n context.tasks.push(locateTask);\n } else {\n assert(\n !requiredLocateFields.includes(field),\n `Required locate field '${field}' is not provided for action ${planType}`,\n );\n debug(`field '${field}' is not provided for action ${planType}`);\n }\n });\n\n const task: ExecutionTaskApply<\n 'Action Space',\n any,\n { success: boolean; action: string; param: any },\n void\n > = {\n type: 'Action Space',\n subType: planType,\n thought: plan.thought,\n param: plan.param,\n executor: async (taskContext) => {\n const timing = taskContext.task.timing;\n\n debug(\n 'executing action',\n planType,\n param,\n `taskContext.element.center: ${taskContext.element?.center}`,\n );\n\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Action task');\n\n requiredLocateFields.forEach((field) => {\n assert(\n param[field],\n `field '${field}' is required for action ${planType} but not provided. Cannot execute action ${planType}.`,\n );\n });\n\n setTimingFieldOnce(timing, 'beforeInvokeActionHookStart');\n const delayBeforeRunner = action.delayBeforeRunner ?? 200;\n try {\n await Promise.all([\n (async () => {\n if (this.interface.beforeInvokeAction) {\n debug(\n `will call \"beforeInvokeAction\" for interface with action name ${action.name}`,\n );\n await this.interface.beforeInvokeAction(action.name, param);\n debug(\n `called \"beforeInvokeAction\" for interface with action name ${action.name}`,\n );\n }\n })(),\n delayBeforeRunner > 0\n ? sleep(delayBeforeRunner)\n : Promise.resolve(),\n ]);\n } catch (originalError: any) {\n const originalMessage =\n originalError?.message || String(originalError);\n throw new Error(\n `error in running beforeInvokeAction for ${action.name}: ${originalMessage}`,\n { cause: originalError },\n );\n }\n setTimingFieldOnce(timing, 'beforeInvokeActionHookEnd');\n\n const { shrunkShotToLogicalRatio } = uiContext;\n if (shrunkShotToLogicalRatio === undefined) {\n throw new Error(\n 'shrunkShotToLogicalRatio is not defined in Action task',\n );\n }\n\n const parsedParam = (() => {\n if (!action.paramSchema) {\n return param;\n }\n\n try {\n return parseActionParam(param, action.paramSchema, {\n shrunkShotToLogicalRatio,\n });\n } catch (error: any) {\n throw new Error(\n `Invalid parameters for action ${action.name}: ${error.message}\\nParameters: ${JSON.stringify(param)}`,\n { cause: error },\n );\n }\n })();\n\n setTimingFieldOnce(timing, 'callActionStart');\n\n debug('calling action', action.name);\n const actionFn = action.call.bind(this.interface);\n const actionResult = await actionFn(parsedParam, taskContext);\n setTimingFieldOnce(timing, 'callActionEnd');\n debug('called action', action.name, 'result:', actionResult);\n\n setTimingFieldOnce(timing, 'afterInvokeActionHookStart');\n\n const delayAfterRunner =\n action.delayAfterRunner ?? this.waitAfterAction ?? 300;\n if (delayAfterRunner > 0) {\n await sleep(delayAfterRunner);\n }\n\n try {\n if (this.interface.afterInvokeAction) {\n debug(\n `will call \"afterInvokeAction\" for interface with action name ${action.name}`,\n );\n await this.interface.afterInvokeAction(action.name, parsedParam);\n debug(\n `called \"afterInvokeAction\" for interface with action name ${action.name}`,\n );\n }\n } catch (originalError: any) {\n const originalMessage =\n originalError?.message || String(originalError);\n throw new Error(\n `error in running afterInvokeAction for ${action.name}: ${originalMessage}`,\n { cause: originalError },\n );\n }\n\n setTimingFieldOnce(timing, 'afterInvokeActionHookEnd');\n\n return {\n output: actionResult,\n };\n },\n };\n\n context.tasks.push(task);\n }\n\n private createLocateTask(\n plan: PlanningAction<DetailedLocateParam>,\n detailedLocateParam: DetailedLocateParam | string,\n context: PlanBuildContext,\n onResult?: (result: LocateResultElement) => void,\n ): ExecutionTaskPlanningLocateApply {\n const { cacheable, defaultModel, deepLocate, abortSignal } = context;\n\n let locateParam = normalizeLocateParam(detailedLocateParam);\n\n if (cacheable !== undefined) {\n locateParam = {\n ...locateParam,\n cacheable,\n };\n }\n\n if (deepLocate && !locateParam.deepLocate) {\n locateParam = {\n ...locateParam,\n deepLocate: true,\n };\n }\n\n const taskLocator: ExecutionTaskPlanningLocateApply = {\n type: 'Planning',\n subType: 'Locate',\n param: locateParam,\n thought: plan.thought,\n executor: async (taskContext) => {\n const { task } = taskContext;\n let { uiContext } = taskContext;\n const paramWithLocatedPixelResult = ifLocateParamHasLocatedPixelResult(\n locateParam,\n )\n ? locateParam\n : undefined;\n\n assert(\n locateParam?.prompt || paramWithLocatedPixelResult,\n `No prompt or id or position or locatedPixelResult to locate, param=${JSON.stringify(\n locateParam,\n )}`,\n );\n\n if (!uiContext) {\n uiContext = await this.service.contextRetrieverFn();\n }\n\n assert(uiContext, 'uiContext is required for Service task');\n\n const { shrunkShotToLogicalRatio } = uiContext;\n\n if (shrunkShotToLogicalRatio === undefined) {\n throw new Error(\n 'shrunkShotToLogicalRatio is not defined in locate task',\n );\n }\n\n let locateDump: ServiceDump | undefined;\n let locateResult: LocateResultWithDump | undefined;\n\n const applyDump = (dump?: ServiceDump) => {\n if (!dump) {\n return;\n }\n locateDump = 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, 'default');\n task.searchArea = dump.taskInfo?.searchArea;\n if (dump.taskInfo?.searchAreaUsage) {\n // The deepLocate search-area call belongs to the same locate task,\n // so it shares the companion usage intent.\n task.searchAreaUsage = withUsageIntent(\n dump.taskInfo.searchAreaUsage,\n 'default',\n );\n }\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n const planLocatedElement = paramWithLocatedPixelResult\n ? matchElementFromPlan(paramWithLocatedPixelResult)\n : undefined;\n\n // from locatedPixelResult (direct plan hit)\n // when deepLocate is enabled, locatedPixelResult should be used as search\n // area hint, not as a final direct hit\n const elementFromPlan = locateParam.deepLocate\n ? undefined\n : planLocatedElement;\n const isPlanDirectHit = !!elementFromPlan;\n\n // from xpath\n let rectFromXpath: Rect | undefined;\n if (\n !isPlanDirectHit &&\n locateParam.xpath &&\n this.interface.rectMatchesCacheFeature\n ) {\n try {\n rectFromXpath = await this.interface.rectMatchesCacheFeature({\n xpaths: [locateParam.xpath],\n });\n } catch {\n // xpath locate failed, allow fallback to cache or AI locate\n }\n }\n\n const elementFromXpath = rectFromXpath\n ? transformLogicalElementToScreenshot(\n {\n center: [\n rectFromXpath.left + rectFromXpath.width / 2,\n rectFromXpath.top + rectFromXpath.height / 2,\n ],\n description:\n typeof locateParam.prompt === 'string'\n ? locateParam.prompt\n : locateParam.prompt?.prompt || '',\n rect: rectFromXpath,\n },\n shrunkShotToLogicalRatio,\n )\n : undefined;\n\n const isXpathHit = !!elementFromXpath;\n\n const cachePrompt = locateParam.prompt;\n const locateCacheRecord = this.taskCache?.matchLocateCache(cachePrompt);\n const cacheEntry = locateCacheRecord?.cacheContent?.cache;\n\n const elementFromCacheResult =\n isPlanDirectHit || isXpathHit\n ? null\n : await matchElementFromCache(\n {\n taskCache: this.taskCache,\n interfaceInstance: this.interface,\n },\n cacheEntry,\n cachePrompt,\n locateParam.cacheable,\n );\n\n // elementFromCacheResult is in logical coordinates, which should be transformed to screenshot coordinates;\n const elementFromCache = elementFromCacheResult\n ? transformLogicalElementToScreenshot(\n elementFromCacheResult,\n shrunkShotToLogicalRatio,\n )\n : undefined;\n\n const isCacheHit = !!elementFromCache;\n\n let elementFromAiLocate: LocateResultElement | null | undefined;\n const timing = taskContext.task.timing;\n if (!isXpathHit && !isCacheHit && !isPlanDirectHit) {\n try {\n setTimingFieldOnce(timing, 'callAiStart');\n locateResult = await this.service.locate(\n locateParam,\n {\n context: uiContext,\n planLocatedElement,\n },\n defaultModel,\n abortSignal,\n );\n applyDump(locateResult.dump);\n elementFromAiLocate = locateResult.element;\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n }\n\n const element =\n elementFromPlan ||\n elementFromXpath ||\n elementFromCache ||\n elementFromAiLocate;\n\n if (element) {\n const invalidElementReason = invalidLocateElementReason(element);\n if (invalidElementReason) {\n if (locateDump) {\n throw new ServiceError(invalidElementReason, locateDump);\n }\n throw new Error(invalidElementReason);\n }\n }\n\n // Check if locate cache already exists (for planHitFlag case)\n const locateCacheAlreadyExists = hasNonEmptyCache(\n locateCacheRecord?.cacheContent?.cache,\n );\n\n let currentCacheEntry: ElementCacheFeature | undefined;\n // Write cache if:\n // 1. element found\n // 2. taskCache enabled\n // 3. not a cache hit (otherwise we'd be writing what we just read)\n // 4. not already cached for plan hit case (avoid redundant writes), OR allow update if cache validation failed\n // 5. cacheable is not explicitly false\n if (\n element &&\n this.taskCache &&\n !isCacheHit &&\n (!isPlanDirectHit || !locateCacheAlreadyExists) &&\n locateParam.cacheable !== false\n ) {\n if (this.interface.cacheFeatureForPoint) {\n try {\n // Transform coordinates to logical space for cacheFeatureForPoint\n // cacheFeatureForPoint needs logical coordinates to locate elements in DOM\n const pointForCache: [number, number] = [\n Math.round(element.center[0] / shrunkShotToLogicalRatio),\n Math.round(element.center[1] / shrunkShotToLogicalRatio),\n ];\n\n const feature = await this.interface.cacheFeatureForPoint(\n pointForCache,\n {\n targetDescription:\n typeof locateParam.prompt === 'string'\n ? locateParam.prompt\n : locateParam.prompt?.prompt,\n modelRuntime: defaultModel,\n },\n );\n if (hasNonEmptyCache(feature)) {\n debug(\n 'update cache, prompt: %s, cache: %o',\n cachePrompt,\n feature,\n );\n currentCacheEntry = feature;\n this.taskCache.updateOrAppendCacheRecord(\n {\n type: 'locate',\n prompt: cachePrompt,\n cache: feature,\n },\n locateCacheRecord,\n );\n } else {\n debug(\n 'no cache data returned, skip cache update, prompt: %s',\n cachePrompt,\n );\n }\n } catch (error) {\n debug('cacheFeatureForPoint failed: %s', error);\n }\n } else {\n debug('cacheFeatureForPoint is not supported, skip cache update');\n }\n }\n\n if (!element) {\n if (locateDump) {\n throw new ServiceError(\n `Element not found : ${locateParam.prompt}`,\n locateDump,\n );\n }\n throw new Error(`Element not found: ${locateParam.prompt}`);\n }\n\n let hitBy: ExecutionTaskHitBy | undefined;\n\n if (isPlanDirectHit && paramWithLocatedPixelResult) {\n hitBy = {\n from: 'Plan',\n context: {\n locatedPixelResult:\n paramWithLocatedPixelResult.locatedPixelResult,\n },\n };\n } else if (isXpathHit) {\n hitBy = {\n from: 'User expected path',\n context: {\n xpath: locateParam.xpath,\n },\n };\n } else if (isCacheHit) {\n hitBy = {\n from: 'Cache',\n context: {\n cacheEntry,\n cacheToSave: currentCacheEntry,\n },\n };\n }\n\n const promptDisplay = locateParam.promptDisplay;\n const elementForAction = promptDisplay\n ? {\n ...element,\n description: promptDisplay,\n }\n : element;\n\n if (promptDisplay && locateDump?.matchedElement) {\n locateDump.matchedElement = locateDump.matchedElement.map(\n (matchedElement) => ({\n ...matchedElement,\n description: promptDisplay,\n }),\n );\n }\n\n onResult?.(elementForAction);\n\n return {\n output: {\n element: {\n ...elementForAction,\n // backward compatibility for aiLocate, which return value needs a dpr field\n dpr: uiContext.deprecatedDpr,\n },\n },\n hitBy,\n };\n },\n };\n\n return taskLocator;\n }\n}\n"],"names":["debug","getDebug","hasNonEmptyCache","cache","Object","invalidLocateElementReason","element","values","value","Number","JSON","normalizeLocateParam","param","deepThink","rest","deepLocate","undefined","locatePlanForLocate","locate","locatePlan","TaskBuilder","plans","planningModel","defaultModel","options","tasks","cacheable","context","planHandlers","Map","plan","defaultHandler","handler","taskActionFinished","taskLocate","planType","actionSpace","action","findActionInActionSpaceOrThrow","locateFields","findAllMidsceneLocatorField","requiredLocateFields","field","ifLocateParamHasLocatedPixelResult","locateTask","result","assert","task","taskContext","timing","uiContext","setTimingFieldOnce","delayBeforeRunner","Promise","sleep","originalError","originalMessage","String","Error","shrunkShotToLogicalRatio","parsedParam","parseActionParam","error","actionFn","actionResult","delayAfterRunner","detailedLocateParam","onResult","abortSignal","locateParam","taskLocator","paramWithLocatedPixelResult","locateDump","locateResult","applyDump","dump","withUsageIntent","planLocatedElement","matchElementFromPlan","elementFromPlan","isPlanDirectHit","rectFromXpath","elementFromXpath","transformLogicalElementToScreenshot","isXpathHit","cachePrompt","locateCacheRecord","cacheEntry","elementFromCacheResult","matchElementFromCache","elementFromCache","isCacheHit","elementFromAiLocate","ServiceError","invalidElementReason","locateCacheAlreadyExists","currentCacheEntry","pointForCache","Math","feature","hitBy","promptDisplay","elementForAction","matchedElement","interfaceInstance","service","taskCache","waitAfterAction"],"mappings":";;;;;;;;;;;;;;;;;;;AAkCA,MAAMA,QAAQC,SAAS;AAKvB,SAASC,iBAAiBC,KAAc;IACtC,OACEA,QAAAA,SAEA,AAAiB,YAAjB,OAAOA,SACPC,OAAO,IAAI,CAACD,OAAO,MAAM,GAAG;AAEhC;AAEA,SAASE,2BACPC,OAA4B;IAE5B,MAAMC,SAAS;QAACD,QAAQ,MAAM,EAAE,CAAC,EAAE;QAAEA,QAAQ,MAAM,EAAE,CAAC,EAAE;KAAC;IACzD,IACEA,QAAQ,MAAM,EAAE,WAAW,KAC3BC,OAAO,IAAI,CAAC,CAACC,QAAU,AAAiB,YAAjB,OAAOA,SAAsB,CAACC,OAAO,QAAQ,CAACD,SAErE,OAAO,CAAC,mCAAmC,EAAEE,KAAK,SAAS,CAACJ,UAAU;AAG1E;AAMA,SAASK,qBACPC,KAAmC;IAEnC,IAAI,AAAiB,YAAjB,OAAOA,OACT,OAAO;QAAE,QAAQA;IAAM;IAGzB,MAAM,EAAEC,SAAS,EAAE,GAAGC,MAAM,GAAGF;IAC/B,MAAMG,aAAaD,KAAK,UAAU,IAAID;IAEtC,OAAOE,A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AiB,aAAjB;QAEA,uBAAiB,eAAjB;QAEA,uBAAiB,mBAAjB;QASE,IAAI,CAAC,SAAS,GAAGH;QACjB,IAAI,CAAC,OAAO,GAAGC;QACf,IAAI,CAAC,SAAS,GAAGC;QACjB,IAAI,CAAC,WAAW,GAAGtE;QACnB,IAAI,CAAC,eAAe,GAAGuE;IACzB;AA2kBF"}
1
+ {"version":3,"file":"agent/task-builder.mjs","sources":["../../../src/agent/task-builder.ts"],"sourcesContent":["import { findAllMidsceneLocatorField, parseActionParam } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport {\n findActionInActionSpaceOrThrow,\n validateRequiredLocateFields,\n} from '@/common';\nimport type { AbstractInterface } from '@/device';\nimport type Service from '@/service';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport type {\n AIUsageInfo,\n DetailedLocateParam,\n DeviceAction,\n ElementCacheFeature,\n ExecutionTaskActionApply,\n ExecutionTaskApply,\n ExecutionTaskHitBy,\n ExecutionTaskPlanningLocateApply,\n LocateResultElement,\n LocateResultWithDump,\n PlanningAction,\n Rect,\n ServiceDump,\n} from '@/types';\nimport { ServiceError } from '@/types';\nimport { sleep } from '@/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport type { TaskCache } from './task-cache';\nimport { withUsageIntent } from './usage-intent';\nimport {\n ifLocateParamHasLocatedPixelResult,\n matchElementFromCache,\n matchElementFromPlan,\n transformLogicalElementToScreenshot,\n} from './utils';\n\nconst debug = getDebug('agent:task-builder');\n\n/**\n * Check if a cache object is non-empty\n */\nfunction hasNonEmptyCache(cache: unknown): boolean {\n return (\n cache !== null &&\n cache !== undefined &&\n typeof cache === 'object' &&\n Object.keys(cache).length > 0\n );\n}\n\nfunction invalidLocateElementReason(\n element: LocateResultElement,\n): string | undefined {\n const values = [element.center?.[0], element.center?.[1]];\n if (\n element.center?.length !== 2 ||\n values.some((value) => typeof value !== 'number' || !Number.isFinite(value))\n ) {\n return `Invalid locate result coordinates: ${JSON.stringify(element)}`;\n }\n return undefined;\n}\n\ntype LocateParamWithDeprecatedAlias = DetailedLocateParam & {\n deepThink?: boolean;\n};\n\nfunction normalizeLocateParam(\n param: string | DetailedLocateParam,\n): DetailedLocateParam {\n if (typeof param === 'string') {\n return { prompt: param };\n }\n\n const { deepThink, ...rest } = param as LocateParamWithDeprecatedAlias;\n const deepLocate = rest.deepLocate ?? deepThink;\n\n return deepLocate === undefined ? rest : { ...rest, deepLocate };\n}\n\nexport function locatePlanForLocate(param: string | DetailedLocateParam) {\n const locate = normalizeLocateParam(param);\n const locatePlan: PlanningAction<DetailedLocateParam> = {\n type: 'Locate',\n param: locate,\n thought: '',\n };\n return locatePlan;\n}\n\ninterface TaskBuilderDeps {\n interfaceInstance: AbstractInterface;\n service: Service;\n taskCache?: TaskCache;\n actionSpace: DeviceAction[];\n waitAfterAction?: number;\n}\n\ninterface BuildOptions {\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n}\n\ninterface PlanBuildContext {\n tasks: ExecutionTaskApply[];\n planningModel: ModelRuntime;\n defaultModel: ModelRuntime;\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n}\n\nexport class TaskBuilder {\n private readonly interface: AbstractInterface;\n\n private readonly service: Service;\n\n private readonly taskCache?: TaskCache;\n\n private readonly actionSpace: DeviceAction[];\n\n private readonly waitAfterAction?: number;\n\n constructor({\n interfaceInstance,\n service,\n taskCache,\n actionSpace,\n waitAfterAction,\n }: TaskBuilderDeps) {\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = taskCache;\n this.actionSpace = actionSpace;\n this.waitAfterAction = waitAfterAction;\n }\n\n public async build(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: BuildOptions,\n ): Promise<{ tasks: ExecutionTaskApply[] }> {\n const tasks: ExecutionTaskApply[] = [];\n const cacheable = options?.cacheable;\n\n const context: PlanBuildContext = {\n tasks,\n planningModel,\n defaultModel,\n cacheable,\n deepLocate: options?.deepLocate,\n abortSignal: options?.abortSignal,\n };\n\n type PlanHandler = (plan: PlanningAction) => Promise<void> | void;\n\n const planHandlers = new Map<string, PlanHandler>([\n [\n 'Locate',\n (plan) =>\n this.handleLocatePlan(\n plan as PlanningAction<DetailedLocateParam>,\n context,\n ),\n ],\n ['Finished', (plan) => this.handleFinishedPlan(plan, context)],\n ]);\n\n const defaultHandler: PlanHandler = (plan) =>\n this.handleActionPlan(plan, context);\n\n for (const plan of plans) {\n const handler = planHandlers.get(plan.type) ?? defaultHandler;\n await handler(plan);\n }\n\n return {\n tasks,\n };\n }\n\n private handleFinishedPlan(\n plan: PlanningAction,\n context: PlanBuildContext,\n ): void {\n const taskActionFinished: ExecutionTaskActionApply<null> = {\n type: 'Action Space',\n subType: 'Finished',\n param: null,\n thought: plan.thought,\n executor: async () => {},\n };\n context.tasks.push(taskActionFinished);\n }\n\n private async handleLocatePlan(\n plan: PlanningAction<DetailedLocateParam>,\n context: PlanBuildContext,\n ): Promise<void> {\n const taskLocate = this.createLocateTask(plan, plan.param, context);\n context.tasks.push(taskLocate);\n }\n\n private async handleActionPlan(\n plan: PlanningAction,\n context: PlanBuildContext,\n ): Promise<void> {\n const planType = plan.type;\n const actionSpace = this.actionSpace;\n const action = findActionInActionSpaceOrThrow(planType, actionSpace);\n const param = plan.param;\n\n const locateFields = findAllMidsceneLocatorField(action.paramSchema);\n\n validateRequiredLocateFields(param, action.paramSchema);\n\n locateFields.forEach((field) => {\n if (param?.[field]) {\n // Always use createLocateTask for all locate params.\n // This ensures cache writing happens even when locatedPixelResult is available\n const locatePlan = locatePlanForLocate(param[field]);\n debug(\n 'will prepend locate param for field',\n `action.type=${planType}`,\n `param=${JSON.stringify(param[field])}`,\n `locatePlan=${JSON.stringify(locatePlan)}`,\n `hasLocatedPixelResult=${ifLocateParamHasLocatedPixelResult(param[field])}`,\n );\n const locateTask = this.createLocateTask(\n locatePlan,\n param[field],\n context,\n (result) => {\n param[field] = result;\n },\n );\n context.tasks.push(locateTask);\n } else {\n debug(`field '${field}' is not provided for action ${planType}`);\n }\n });\n\n const task: ExecutionTaskApply<\n 'Action Space',\n any,\n { success: boolean; action: string; param: any },\n void\n > = {\n type: 'Action Space',\n subType: planType,\n thought: plan.thought,\n param: plan.param,\n executor: async (taskContext) => {\n const timing = taskContext.task.timing;\n\n debug(\n 'executing action',\n planType,\n param,\n `taskContext.element.center: ${taskContext.element?.center}`,\n );\n\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Action task');\n\n validateRequiredLocateFields(param, action.paramSchema);\n\n setTimingFieldOnce(timing, 'beforeInvokeActionHookStart');\n const delayBeforeRunner = action.delayBeforeRunner ?? 200;\n try {\n await Promise.all([\n (async () => {\n if (this.interface.beforeInvokeAction) {\n debug(\n `will call \"beforeInvokeAction\" for interface with action name ${action.name}`,\n );\n await this.interface.beforeInvokeAction(action.name, param);\n debug(\n `called \"beforeInvokeAction\" for interface with action name ${action.name}`,\n );\n }\n })(),\n delayBeforeRunner > 0\n ? sleep(delayBeforeRunner)\n : Promise.resolve(),\n ]);\n } catch (originalError: any) {\n const originalMessage =\n originalError?.message || String(originalError);\n throw new Error(\n `error in running beforeInvokeAction for ${action.name}: ${originalMessage}`,\n { cause: originalError },\n );\n }\n setTimingFieldOnce(timing, 'beforeInvokeActionHookEnd');\n\n const { shrunkShotToLogicalRatio } = uiContext;\n if (shrunkShotToLogicalRatio === undefined) {\n throw new Error(\n 'shrunkShotToLogicalRatio is not defined in Action task',\n );\n }\n\n const parsedParam = (() => {\n if (!action.paramSchema) {\n return param;\n }\n\n try {\n return parseActionParam(param, action.paramSchema, {\n shrunkShotToLogicalRatio,\n });\n } catch (error: any) {\n throw new Error(\n `Invalid parameters for action ${action.name}: ${error.message}\\nParameters: ${JSON.stringify(param)}`,\n { cause: error },\n );\n }\n })();\n\n setTimingFieldOnce(timing, 'callActionStart');\n\n debug('calling action', action.name);\n const actionFn = action.call.bind(this.interface);\n const actionResult = await actionFn(parsedParam, taskContext);\n setTimingFieldOnce(timing, 'callActionEnd');\n debug('called action', action.name, 'result:', actionResult);\n\n setTimingFieldOnce(timing, 'afterInvokeActionHookStart');\n\n const delayAfterRunner =\n action.delayAfterRunner ?? this.waitAfterAction ?? 300;\n if (delayAfterRunner > 0) {\n await sleep(delayAfterRunner);\n }\n\n try {\n if (this.interface.afterInvokeAction) {\n debug(\n `will call \"afterInvokeAction\" for interface with action name ${action.name}`,\n );\n await this.interface.afterInvokeAction(action.name, parsedParam);\n debug(\n `called \"afterInvokeAction\" for interface with action name ${action.name}`,\n );\n }\n } catch (originalError: any) {\n const originalMessage =\n originalError?.message || String(originalError);\n throw new Error(\n `error in running afterInvokeAction for ${action.name}: ${originalMessage}`,\n { cause: originalError },\n );\n }\n\n setTimingFieldOnce(timing, 'afterInvokeActionHookEnd');\n\n return {\n output: actionResult,\n };\n },\n };\n\n context.tasks.push(task);\n }\n\n private createLocateTask(\n plan: PlanningAction<DetailedLocateParam>,\n detailedLocateParam: DetailedLocateParam | string,\n context: PlanBuildContext,\n onResult?: (result: LocateResultElement) => void,\n ): ExecutionTaskPlanningLocateApply {\n const { cacheable, defaultModel, deepLocate, abortSignal } = context;\n\n let locateParam = normalizeLocateParam(detailedLocateParam);\n\n if (cacheable !== undefined) {\n locateParam = {\n ...locateParam,\n cacheable,\n };\n }\n\n if (deepLocate && !locateParam.deepLocate) {\n locateParam = {\n ...locateParam,\n deepLocate: true,\n };\n }\n\n const taskLocator: ExecutionTaskPlanningLocateApply = {\n type: 'Planning',\n subType: 'Locate',\n param: locateParam,\n thought: plan.thought,\n executor: async (taskContext) => {\n const { task } = taskContext;\n let { uiContext } = taskContext;\n const paramWithLocatedPixelResult = ifLocateParamHasLocatedPixelResult(\n locateParam,\n )\n ? locateParam\n : undefined;\n\n assert(\n locateParam?.prompt || paramWithLocatedPixelResult,\n `No prompt or id or position or locatedPixelResult to locate, param=${JSON.stringify(\n locateParam,\n )}`,\n );\n\n if (!uiContext) {\n uiContext = await this.service.contextRetrieverFn();\n }\n\n assert(uiContext, 'uiContext is required for Service task');\n\n const { shrunkShotToLogicalRatio } = uiContext;\n\n if (shrunkShotToLogicalRatio === undefined) {\n throw new Error(\n 'shrunkShotToLogicalRatio is not defined in locate task',\n );\n }\n\n let locateDump: ServiceDump | undefined;\n let locateResult: LocateResultWithDump | undefined;\n\n const applyDump = (dump?: ServiceDump) => {\n if (!dump) {\n return;\n }\n locateDump = 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, 'default');\n task.searchArea = dump.taskInfo?.searchArea;\n if (dump.taskInfo?.searchAreaUsage) {\n // The deepLocate search-area call belongs to the same locate task,\n // so it shares the companion usage intent.\n task.searchAreaUsage = withUsageIntent(\n dump.taskInfo.searchAreaUsage,\n 'default',\n );\n }\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n const planLocatedElement = paramWithLocatedPixelResult\n ? matchElementFromPlan(paramWithLocatedPixelResult)\n : undefined;\n\n // from locatedPixelResult (direct plan hit)\n // when deepLocate is enabled, locatedPixelResult should be used as search\n // area hint, not as a final direct hit\n const elementFromPlan = locateParam.deepLocate\n ? undefined\n : planLocatedElement;\n const isPlanDirectHit = !!elementFromPlan;\n\n // from xpath\n let rectFromXpath: Rect | undefined;\n if (\n !isPlanDirectHit &&\n locateParam.xpath &&\n this.interface.rectMatchesCacheFeature\n ) {\n try {\n rectFromXpath = await this.interface.rectMatchesCacheFeature({\n xpaths: [locateParam.xpath],\n });\n } catch {\n // xpath locate failed, allow fallback to cache or AI locate\n }\n }\n\n const elementFromXpath = rectFromXpath\n ? transformLogicalElementToScreenshot(\n {\n center: [\n rectFromXpath.left + rectFromXpath.width / 2,\n rectFromXpath.top + rectFromXpath.height / 2,\n ],\n description:\n typeof locateParam.prompt === 'string'\n ? locateParam.prompt\n : locateParam.prompt?.prompt || '',\n rect: rectFromXpath,\n },\n shrunkShotToLogicalRatio,\n )\n : undefined;\n\n const isXpathHit = !!elementFromXpath;\n\n const cachePrompt = locateParam.prompt;\n const locateCacheRecord = this.taskCache?.matchLocateCache(cachePrompt);\n const cacheEntry = locateCacheRecord?.cacheContent?.cache;\n\n const elementFromCacheResult =\n isPlanDirectHit || isXpathHit\n ? null\n : await matchElementFromCache(\n {\n taskCache: this.taskCache,\n interfaceInstance: this.interface,\n },\n cacheEntry,\n cachePrompt,\n locateParam.cacheable,\n );\n\n // elementFromCacheResult is in logical coordinates, which should be transformed to screenshot coordinates;\n const elementFromCache = elementFromCacheResult\n ? transformLogicalElementToScreenshot(\n elementFromCacheResult,\n shrunkShotToLogicalRatio,\n )\n : undefined;\n\n const isCacheHit = !!elementFromCache;\n\n let elementFromAiLocate: LocateResultElement | null | undefined;\n const timing = taskContext.task.timing;\n if (!isXpathHit && !isCacheHit && !isPlanDirectHit) {\n try {\n setTimingFieldOnce(timing, 'callAiStart');\n locateResult = await this.service.locate(\n locateParam,\n {\n context: uiContext,\n planLocatedElement,\n },\n defaultModel,\n abortSignal,\n );\n applyDump(locateResult.dump);\n elementFromAiLocate = locateResult.element;\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n }\n\n const element =\n elementFromPlan ||\n elementFromXpath ||\n elementFromCache ||\n elementFromAiLocate;\n\n if (element) {\n const invalidElementReason = invalidLocateElementReason(element);\n if (invalidElementReason) {\n if (locateDump) {\n throw new ServiceError(invalidElementReason, locateDump);\n }\n throw new Error(invalidElementReason);\n }\n }\n\n // Check if locate cache already exists (for planHitFlag case)\n const locateCacheAlreadyExists = hasNonEmptyCache(\n locateCacheRecord?.cacheContent?.cache,\n );\n\n let currentCacheEntry: ElementCacheFeature | undefined;\n // Write cache if:\n // 1. element found\n // 2. taskCache enabled\n // 3. not a cache hit (otherwise we'd be writing what we just read)\n // 4. not already cached for plan hit case (avoid redundant writes), OR allow update if cache validation failed\n // 5. cacheable is not explicitly false\n if (\n element &&\n this.taskCache &&\n !isCacheHit &&\n (!isPlanDirectHit || !locateCacheAlreadyExists) &&\n locateParam.cacheable !== false\n ) {\n if (this.interface.cacheFeatureForPoint) {\n try {\n // Transform coordinates to logical space for cacheFeatureForPoint\n // cacheFeatureForPoint needs logical coordinates to locate elements in DOM\n const pointForCache: [number, number] = [\n Math.round(element.center[0] / shrunkShotToLogicalRatio),\n Math.round(element.center[1] / shrunkShotToLogicalRatio),\n ];\n\n const feature = await this.interface.cacheFeatureForPoint(\n pointForCache,\n {\n targetDescription:\n typeof locateParam.prompt === 'string'\n ? locateParam.prompt\n : locateParam.prompt?.prompt,\n modelRuntime: defaultModel,\n },\n );\n if (hasNonEmptyCache(feature)) {\n debug(\n 'update cache, prompt: %s, cache: %o',\n cachePrompt,\n feature,\n );\n currentCacheEntry = feature;\n this.taskCache.updateOrAppendCacheRecord(\n {\n type: 'locate',\n prompt: cachePrompt,\n cache: feature,\n },\n locateCacheRecord,\n );\n } else {\n debug(\n 'no cache data returned, skip cache update, prompt: %s',\n cachePrompt,\n );\n }\n } catch (error) {\n debug('cacheFeatureForPoint failed: %s', error);\n }\n } else {\n debug('cacheFeatureForPoint is not supported, skip cache update');\n }\n }\n\n if (!element) {\n if (locateDump) {\n throw new ServiceError(\n `Element not found : ${locateParam.prompt}`,\n locateDump,\n );\n }\n throw new Error(`Element not found: ${locateParam.prompt}`);\n }\n\n let hitBy: ExecutionTaskHitBy | undefined;\n\n if (isPlanDirectHit && paramWithLocatedPixelResult) {\n hitBy = {\n from: 'Plan',\n context: {\n locatedPixelResult:\n paramWithLocatedPixelResult.locatedPixelResult,\n },\n };\n } else if (isXpathHit) {\n hitBy = {\n from: 'User expected path',\n context: {\n xpath: locateParam.xpath,\n },\n };\n } else if (isCacheHit) {\n hitBy = {\n from: 'Cache',\n context: {\n cacheEntry,\n cacheToSave: currentCacheEntry,\n },\n };\n }\n\n const promptDisplay = locateParam.promptDisplay;\n const elementForAction = promptDisplay\n ? {\n ...element,\n description: promptDisplay,\n }\n : element;\n\n if (promptDisplay && locateDump?.matchedElement) {\n locateDump.matchedElement = locateDump.matchedElement.map(\n (matchedElement) => ({\n ...matchedElement,\n description: promptDisplay,\n }),\n );\n }\n\n onResult?.(elementForAction);\n\n return {\n output: {\n element: {\n ...elementForAction,\n // backward compatibility for aiLocate, which return value needs a dpr field\n dpr: uiContext.deprecatedDpr,\n },\n },\n hitBy,\n };\n },\n };\n\n return taskLocator;\n }\n}\n"],"names":["debug","getDebug","hasNonEmptyCache","cache","Object","invalidLocateElementReason","element","values","value","Number","JSON","normalizeLocateParam","param","deepThink","rest","deepLocate","undefined","locatePlanForLocate","locate","locatePlan","TaskBuilder","plans","planningModel","defaultModel","options","tasks","cacheable","context","planHandlers","Map","plan","defaultHandler","handler","taskActionFinished","taskLocate","planType","actionSpace","action","findActionInActionSpaceOrThrow","locateFields","findAllMidsceneLocatorField","validateRequiredLocateFields","field","ifLocateParamHasLocatedPixelResult","locateTask","result","task","taskContext","timing","uiContext","assert","setTimingFieldOnce","delayBeforeRunner","Promise","sleep","originalError","originalMessage","String","Error","shrunkShotToLogicalRatio","parsedParam","parseActionParam","error","actionFn","actionResult","delayAfterRunner","detailedLocateParam","onResult","abortSignal","locateParam","taskLocator","paramWithLocatedPixelResult","locateDump","locateResult","applyDump","dump","withUsageIntent","planLocatedElement","matchElementFromPlan","elementFromPlan","isPlanDirectHit","rectFromXpath","elementFromXpath","transformLogicalElementToScreenshot","isXpathHit","cachePrompt","locateCacheRecord","cacheEntry","elementFromCacheResult","matchElementFromCache","elementFromCache","isCacheHit","elementFromAiLocate","ServiceError","invalidElementReason","locateCacheAlreadyExists","currentCacheEntry","pointForCache","Math","feature","hitBy","promptDisplay","elementForAction","matched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BACV,aAAa+F;gBACf,IACA/F;gBAEJ,IAAI+F,iBAAiB7B,YAAY,gBAC/BA,WAAW,cAAc,GAAGA,WAAW,cAAc,CAAC,GAAG,CACvD,CAAC+B,iBAAoB;wBACnB,GAAGA,cAAc;wBACjB,aAAaF;oBACf;gBAIJlC,WAAWmC;gBAEX,OAAO;oBACL,QAAQ;wBACN,SAAS;4BACP,GAAGA,gBAAgB;4BAEnB,KAAKrD,UAAU,aAAa;wBAC9B;oBACF;oBACAmD;gBACF;YACF;QACF;QAEA,OAAO9B;IACT;IA1kBA,YAAY,EACVkC,iBAAiB,EACjBC,OAAO,EACPC,SAAS,EACTtE,WAAW,EACXuE,eAAe,EACC,CAAE;QAhBpB,uBAAiB,aAAjB;QAEA,uBAAiB,WAAjB;QAEA,uBAAiB,aAAjB;QAEA,uBAAiB,eAAjB;QAEA,uBAAiB,mBAAjB;QASE,IAAI,CAAC,SAAS,GAAGH;QACjB,IAAI,CAAC,OAAO,GAAGC;QACf,IAAI,CAAC,SAAS,GAAGC;QACjB,IAAI,CAAC,WAAW,GAAGtE;QACnB,IAAI,CAAC,eAAe,GAAGuE;IACzB;AA+jBF"}
@@ -153,7 +153,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
153
153
  return;
154
154
  }
155
155
  }
156
- const getMidsceneVersion = ()=>"1.12.8-beta-20260916030003.0";
156
+ const getMidsceneVersion = ()=>"1.12.8";
157
157
  const parsePrompt = (prompt)=>{
158
158
  if ('string' == typeof prompt) return {
159
159
  textPrompt: prompt,
@@ -199,10 +199,28 @@ ONLY if the task is not complete: Think what the next action is according to the
199
199
  ### Action Guidelines
200
200
 
201
201
  ${hasRunAdbShell ? "- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action." : ''}
202
- - For touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.
202
+ - If Swipe is available in the current Action Space, for touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.
203
203
  - When editing existing text in a UI field, preserve all existing text by moving the cursor and typing/deleting the minimal necessary characters.
204
204
  - For insert/prepend/append edits, use CursorMove when the caret must be adjusted precisely, then use Input with mode "typeOnly" for inserted characters and KeyboardPress for newlines or deletion. If the caret lands in the wrong position, recover with CursorMove, KeyboardPress, or undo and retry cursor placement; do not switch to replace as a fallback for cursor placement failures.
205
205
 
206
+ ### Interpreting Scroll and Swipe Directions
207
+
208
+ Scroll and swipe directions can be ambiguous: they may refer to off-screen content to reveal, visible content movement, or the physical movement of a finger, pointer, or scroll wheel. Infer the intended result from the user's goal, the interaction target, the current UI, and common usage in the user's language, rather than mechanically copying the user's direction word.
209
+
210
+ In the current Action Space, \`direction\` has the following meanings:
211
+
212
+ - Scroll follows the traditional mouse-wheel convention (with natural scrolling disabled). Its direction refers to the off-screen content to reveal; under this convention, it matches the wheel movement direction and is opposite to the content movement direction.
213
+ - Swipe follows the finger-movement convention. Its direction refers to finger movement; for controls where content follows the finger, it matches the content movement direction and is opposite to the direction from which off-screen content is revealed.
214
+
215
+ Use the following priority order:
216
+
217
+ 1. Prioritize the user's goal or expected result, even when it conflicts with a direction word. For example, for "swipe the date picker down to increase the date", if dates increase from top to bottom, use Swipe up to move a larger date from below into the selected position.
218
+ 2. Otherwise, if the user specifies a moving object or movement path, follow that object's physical movement. For example, "swipe the finger to the left" means Swipe left; "move the page content from top to bottom" means moving content downward, corresponding to Swipe down on a page where content follows the finger.
219
+ 3. Otherwise, consider the interaction target and common usage in the user's language. For content browsing, such as pages and lists, scroll directions usually refer to the off-screen content the user wants to see. For directly manipulated controls, such as sliders and wheel pickers, swipe directions usually refer to the intended movement of the control's movable part. For example, the Chinese "往下滑一下页面" and English "scroll down the page" usually mean revealing content below, corresponding to Scroll down; the Chinese "向右滑动滑块" and English "slide the slider to the right" usually mean moving the slider right, corresponding to Swipe right if using Swipe.
220
+ 4. If the intent remains ambiguous, use the Scroll and Swipe direction definitions above.
221
+
222
+ After interpreting the intent, choose an appropriate Action from the current Action Space and use its supported parameters to achieve the intended result. Some actions support start and end points instead of \`direction\`. When using \`direction\`, ensure its value achieves the intended result according to the selected Action's definition.
223
+
206
224
  ${includeLocateInPlanning ? locateGroundingRules() : ''}
207
225
 
208
226
  ### ${planningProtocol.actionSpaceProtocol.title}
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/prompt/planning/system-prompt.mjs","sources":["../../../../../src/ai-model/prompt/planning/system-prompt.ts"],"sourcesContent":["import type { DeviceAction } from '@/types';\nimport { getPreferredLanguage } from '@midscene/shared/env';\nimport type { StandardPlanningProtocol } from '../../model-adapter/planning-protocol';\nimport type { LocateResultPromptSpec } from '../../shared/model-locate-result';\nimport { planningModelFamilyRequiredForLocateMessage } from '../../shared/model-locate-result/errors';\nimport { locateGroundingRules } from '../locate';\nimport {\n buildActionOutputExample,\n createSampleTapAction,\n} from './action-output-example';\nimport { buildPlanningActionSpaceDescription } from './action-space-description';\nimport { buildPlanningMultiTurnExample } from './multi-turn-example';\n\ntype BuildStandardPlanningSystemPromptInput = {\n actionSpace: DeviceAction<any>[];\n includeSubGoals?: boolean;\n includeThought?: boolean;\n includeLog?: boolean;\n planningProtocol: StandardPlanningProtocol;\n} & (\n | {\n includeLocateInPlanning: true;\n locatePromptSpec: LocateResultPromptSpec;\n }\n | {\n includeLocateInPlanning: false;\n locatePromptSpec?: never;\n }\n);\n\nexport async function buildStandardPlanningSystemPrompt(\n input: BuildStandardPlanningSystemPromptInput,\n) {\n const {\n actionSpace,\n includeLocateInPlanning,\n locatePromptSpec,\n includeSubGoals,\n includeThought = true,\n includeLog = true,\n planningProtocol,\n } = input;\n const actionOutputProtocol = planningProtocol.actionOutputProtocol;\n const preferredLanguage = getPreferredLanguage();\n\n if (includeLocateInPlanning && !locatePromptSpec) {\n throw new Error(planningModelFamilyRequiredForLocateMessage());\n }\n\n const actionSpaceDescription = buildPlanningActionSpaceDescription({\n actionSpace,\n locatePromptSpec,\n planningProtocol,\n });\n const hasRunAdbShell = actionSpace.some(\n (action) => action.name === 'RunAdbShell',\n );\n const actionOutputTagsText = actionOutputProtocol.actionOutputTagNames\n .map((tagName) => `<${tagName}>`)\n .join(', ');\n\n const shouldIncludeSubGoals = includeSubGoals ?? false;\n const renderSubGoalsContent = (content: string, fallbackContent = '') =>\n shouldIncludeSubGoals ? content : fallbackContent;\n const renderThoughtContent = (content: string, fallbackContent = '') =>\n includeThought ? content : fallbackContent;\n const renderLogContent = (content: string, fallbackContent = '') =>\n includeLog ? content : fallbackContent;\n\n // Step numbering adjusts based on whether sub-goals are included\n // When includeSubGoals=false, memory step is skipped\n const completionCheckStepNumber = shouldIncludeSubGoals ? 3 : 2;\n const actionStepNumber = completionCheckStepNumber + 1;\n\n return `\nTarget: 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.\n\n## Step 1: ${renderSubGoalsContent(\n 'Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)',\n renderThoughtContent('Observe (related tags: <planning>)', 'Observe'),\n )}\n\nFirst, observe the current screenshot and previous logs${renderSubGoalsContent(\n \", 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.\",\n ' to understand the current state.',\n )}\n\n${renderSubGoalsContent(`### Observation Guidelines\n\n- Treat visible summaries, thumbnails, cropped content, and partially visible lists as potentially incomplete when the task depends on precise details.\n- 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.`)}\n\n${renderThoughtContent(`### <planning> tag (REQUIRED)\n\nREQUIRED: You MUST always output the <planning> tag. Never skip it.\n\nWrite the content of the <planning> tag in ${preferredLanguage}.\n\nInclude your planning details in the <planning> tag. It should answer: ${renderSubGoalsContent(\n \"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?\",\n 'What is the current state based on the screenshot? What should be the next action?',\n)} Write it naturally without numbering or section headers.\n\nCRITICAL - 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.`)}\n\n${renderSubGoalsContent(`### <update-plan-content> tag\n\nUse this structure to give or update your plan:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished|pending\">sub goal description</sub-goal>\n <sub-goal index=\"2\" status=\"finished|pending\">sub goal description</sub-goal>\n ...\n</update-plan-content>\n\n### <mark-sub-goal-done> tag\n\nUse this structure to mark a sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nIMPORTANT: You MUST only mark a sub-goal as \"finished\" AFTER you have confirmed the task is actually completed by observing the result in the screenshot. Do NOT mark a sub-goal as done just because you expect the next action will complete it. Wait until you see visual confirmation in the screenshot that the sub-goal has been achieved.\n\n### Note\n\nDuring execution, you can call <update-plan-content> at any time to update the plan based on the latest screenshot and completed sub-goals.\n\n### Example\n\nIf the user wants to \"log in to a system using username and password, complete all to-do items, and submit a registration form\", you can break it down into the following sub-goals:\n\n<planning>...</planning>\n<update-plan-content>\n <sub-goal index=\"1\" status=\"pending\">Log in to the system</sub-goal>\n <sub-goal index=\"2\" status=\"pending\">Complete all to-do items</sub-goal>\n <sub-goal index=\"3\" status=\"pending\">Submit the registration form</sub-goal>\n</update-plan-content>\n\nAfter logging in and seeing the to-do items, you can mark the sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nAt this point, the status of all sub-goals is:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished\" />\n <sub-goal index=\"2\" status=\"pending\" />\n <sub-goal index=\"3\" status=\"pending\" />\n</update-plan-content>\n\nAfter some time, when the last sub-goal is also completed, you can mark it as done as well:\n\n<mark-sub-goal-done>\n <sub-goal index=\"3\" status=\"finished\" />\n</mark-sub-goal-done>`)}\n\n${renderSubGoalsContent(`## Step 2: Memory Data from Current Screenshot (related tags: <memory>)\n\nUse <memory> to record clear, task-relevant information from the current screenshot that may be needed in later steps. The current screenshot will not be available later, so memory should preserve enough detail for future reasoning, verification, or action.\n\n- Record information completely and exactly as shown. Do not summarize, translate, normalize, or merge values that may matter later.\n- When recording an item, include the item itself, its exact task-relevant details, and the visible cue or UI context that identifies where it came from when relevant.\n- Keep similar or repeated items as separate memory entries unless their task-relevant details are confirmed to be the same.\n- After navigation, scrolling, editing, deletion, saving, or other screen changes, treat remembered positions, order, indexes, and UI bindings as references only. Re-check the current screen before acting on them.\n\nExamples:\n- If you need to find an item and later assert its details, record the item name and the exact details needed for the assertion, such as status, price, date, owner, description, or other visible fields.\n- If you need to compare multiple similar results, record each candidate separately with its exact distinguishing details and visible context.\n- If you need to copy information from one place to another, record the exact source value and the target field or UI cue it should be mapped to.\n\nDon't use this tag if no information needs to be preserved.`)}\n\n## Step ${completionCheckStepNumber}: ${renderSubGoalsContent(\n 'Check if Goal is Accomplished',\n 'Check if the Instruction is Fulfilled',\n )} (related tags: <complete>)\n\nDetermine if the entire task is completed${renderSubGoalsContent(' based on the current screenshot and the status of all sub-goals')}.\n\n### CRITICAL: The User's Instruction is the Supreme Authority\n\nThe user's instruction defines the EXACT scope of what you must accomplish. You MUST follow it precisely - nothing more, nothing less. Violating this rule may cause severe consequences such as data loss, unintended operations, or system failures.\n\n**Explicit instructions vs. High-level goals:**\n- If the user gives you **explicit operation steps** (e.g., \"click X\", \"type Y\", \"fill out the form\"), treat them as exact commands. Execute ONLY those steps, nothing more.\n- If the user gives you a **high-level goal** (e.g., \"log in to the system\", \"complete the purchase\"), you may determine the necessary steps to achieve it.\n\n**What \"${renderSubGoalsContent('goal accomplished', 'instruction fulfilled')}\" means:**\n- The ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} when you have done EXACTLY what the user asked - no extra steps, no assumptions.\n- Do NOT perform any action beyond the explicit instruction, even if it seems logical or helpful.\n\n**Examples - Explicit instructions (execute exactly, no extra steps):**\n- \"fill out the form\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when all fields are filled. Do NOT submit the form.\n- \"click the login button\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} once clicked. Do NOT wait for page load or verify login success.\n- \"type 'hello' in the search box\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when 'hello' is typed. Do NOT press Enter or trigger search.\n- \"select the first item\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when selected. Do NOT proceed to checkout.\n\n**Change completion:**\n- If the requested outcome is a durable change, such as create, edit, update, delete, save, send, submit, apply, or publish, do not stop at an unsaved draft, open editor, temporary input, transient selection, or staged value. Continue through the app/page's normal completion control such as Save, Done, Confirm, OK, Submit, Apply, Send, or Publish before completing, so the result remains after leaving the screen.\n- If the user only asks for an intermediate UI state, such as typing text, selecting an option, filling fields, or opening a screen without saving/submitting/applying, stop once that exact state is reached.\n\n**Special case - Scrollable option lists and dropdowns:**\n- When choosing an item from a scrollable select, dropdown, listbox, menu, or similar option list, first open the control if it is closed. Once the list is open, interact with the list itself, not the page.\n- If the target option is visible in the open list, Tap that exact option immediately.\n- If the list is open but the target option is not visible, try to find it by scrolling the open list/dropdown before giving up or interacting with other elements.\n- For an open dropdown/list, prefer small incremental Scroll actions with an explicit distance (typically 50-120 pixels) and a locate target describing the open list/dropdown. Do NOT omit distance while searching within a list, because the default scroll distance can skip over relevant options and cause oscillation.\n- While searching within an open dropdown/list, use short scrolls so intermediate options are not skipped.\n- After selecting the target, if the trigger text or result text shows the requested option, treat the current selection step as fulfilled and continue evaluating the remaining user instruction.\n\n**Special case - Text hidden by a narrow input field:**\n- CRITICAL PRIORITY OVERRIDE - Input verification after an input action:\n- This rule overrides the general requirement to verify the exact target text from the screenshot.\n- If the previous step already executed an input action, and the current input field is not empty, you MUST directly treat that input as successful.\n- In this situation, do NOT use the visible text in the screenshot to decide that the input is incomplete, incorrect, missing characters, out of order, or needs correction.\n- Do NOT perform ClearInput, another Input, KeyboardPress, or any other action intended to \"fix the input content\" just because the visible text looks different from the target text, has abnormal character order, missing characters, abnormal spacing, suspicious visual recognition results, or appears to have selected/highlighted text.\n- The general rule \"do EXACTLY what the user asked\" still applies to the intended input value you execute, but it MUST NOT be enforced by re-validating the visible text in the screenshot after the input action.\n- Differences in visible text must be assumed to be caused by clipping, horizontal scrolling, narrow input fields, text selection, caret position, or visual recognition errors rather than input failure.\n- Retry input only when the input field is clearly still empty, or when the page shows an explicit error message.\n\n**Special case - Assertion instructions:**\n- If the user's instruction includes an assertion (e.g., \"verify that...\", \"check that...\", \"assert...\"), and you observe from the screenshot that the assertion condition is NOT satisfied and cannot be satisfied, mark ${renderSubGoalsContent('the goal', 'it')} as failed (success=\"false\").\n- If the page is still loading (e.g., you see a loading spinner, skeleton screen, or progress bar), do NOT assert yet. Wait for the page to finish loading before evaluating the assertion.\n\n### Completion Criteria for Process-required Instructions\n\nIf the user's instruction includes explicit operation steps, ordering requirements, or action requirements, it is a process-required instruction.\n\nFor process-required instructions, do NOT treat the task as complete only because the current screenshot already shows the final expected state. Do NOT infer that earlier steps were executed from the final UI state.\n\nYou may output <complete success=\"true\"> only when the current execution history, previous logs, or the screenshot after the most recent action proves that every explicit step required by the user has been completed, and the final check condition is also satisfied.\n\nIf any explicit step lacks completion evidence in the current execution history, continue with the next missing step instead of outputting <complete>, even if the current screenshot appears to satisfy the final condition.\n\n${renderSubGoalsContent(\n '',\n `**Page navigation restriction:**\n- Unless the user's instruction explicitly asks you to click a link, jump to another page, or navigate to a URL, you MUST complete the task on the current page only.\n- Do NOT navigate away from the current page on your own initiative (e.g., do not click links that lead to other pages, do not use browser back/forward, do not open new URLs).\n- If the task cannot be accomplished on the current page and the user has not instructed you to navigate, report it as a failure (success=\"false\") instead of attempting to navigate to other pages.`,\n)}\n\n### Output Rules\n\n- If the task is NOT complete, skip this section and continue to Step ${actionStepNumber}.\n- Use the <complete success=\"true|false\">message</complete> tag to output the result if the goal is accomplished or failed.\n - the 'success' attribute is required. ${renderSubGoalsContent('It means whether the expected goal is accomplished based on what you observe in the current screenshot and the current execution history. ')}No matter what errors occurred during execution, set success=\"true\" only when the current execution history shows that all steps required by the user have been completed and the final state satisfies the requirement. If the user asks for explicit operation steps or an ordered workflow, do not treat those steps as completed only because the current screenshot already shows the final expected state. If the ${renderSubGoalsContent('expected goal is not accomplished and cannot be accomplished', 'instruction is not fulfilled and cannot be fulfilled')}, set success=\"false\".\n - the 'message' is the information that will be provided to the user. If the user asks for a specific format, strictly follow that.\n- If you output <complete>, do NOT output ${actionOutputTagsText}. The task ends here.\n\n## Step ${actionStepNumber}: Determine Next Action (related tags: ${renderLogContent('<log>, ')}${actionOutputTagsText}, <error>)\n\nONLY if the task is not complete: Think what the next action is according to the current screenshot${renderSubGoalsContent(' and the plan')}.\n\n- Don't give extra actions or plans beyond the instruction or the plan. For example, don't try to submit the form if the instruction is only to fill something.\n- Consider the current screenshot and give the action that is most likely to accomplish the instruction. For example, if the next step is to click a button but it's not visible in the screenshot, you should try to find it first instead of give a click action.\n- Make sure the previous actions are completed successfully. Otherwise, retry or do something else to recover.\n- Give just the next ONE action you should do (if any)\n- If there are some error messages reported by the previous actions, don't give up, try parse a new action to recover. If the error persists for more than 3 times, you should think this is an error and set the \"error\" field to the error message.\n\n### Action Guidelines\n\n${\n hasRunAdbShell\n ? \"- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action.\"\n : ''\n}\n- For touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.\n- When editing existing text in a UI field, preserve all existing text by moving the cursor and typing/deleting the minimal necessary characters.\n- For insert/prepend/append edits, use CursorMove when the caret must be adjusted precisely, then use Input with mode \"typeOnly\" for inserted characters and KeyboardPress for newlines or deletion. If the caret lands in the wrong position, recover with CursorMove, KeyboardPress, or undo and retry cursor placement; do not switch to replace as a fallback for cursor placement failures.\n\n${includeLocateInPlanning ? locateGroundingRules() : ''}\n\n### ${planningProtocol.actionSpaceProtocol.title}\n\n${actionSpaceDescription}\n\n${renderLogContent(`### Log to give user feedback (preamble message)\n\nThe <log> tag is a brief preamble message to the user explaining what you're about to do. It should follow these principles and examples:\n\n- **Use ${preferredLanguage}**\n- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words or Chinese characters for quick updates).\n- **Build on prior context**: if this is not the first action to be done, use the preamble message to connect the dots with what's been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n\n**Examples:**\n- <log>Click the login button</log>\n- <log>Scroll to find the 'Yes' button in popup</log>\n- <log>Previous actions failed to find the 'Yes' button, i will try again</log>\n- <log>Go back to find the login button</log>`)}\n\n### If there is some action to do ...\n\n${actionOutputProtocol.actionOutputRules}\n\nFor example:\n${buildActionOutputExample(\n createSampleTapAction('Add to cart button for Sauce Labs Backpack'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 1,\n buildActionOutput: actionOutputProtocol.buildActionOutput,\n },\n)}\n\n### If you think there is an error ...\n\n- Use the <error> tag to output the error message.\n\nFor example:\n<error>Unable to find the required element on the page</error>\n\n### If there is no action to do ...\n\n- Don't output ${actionOutputTagsText} if there is no action to do.\n\n## Return Format\n\nReturn in XML format following this decision flow:\n\n${planningProtocol.responsePrefix ?? ''}\n\n${renderThoughtContent(`**Always include (REQUIRED):**\n<!-- Step 1: Observe and Plan -->\n<planning>Your planning details here. NEVER skip this tag.</planning>`)}\n${renderSubGoalsContent(`<!-- required when no update-plan-content is provided in the previous response -->\n<update-plan-content>...</update-plan-content>\n\n<!-- required when any sub-goal is completed -->\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\n<!-- Step 2: Memory data from current screenshot if needed -->\n<memory>...</memory>`)}\n\n**Then choose ONE of the following paths:**\n\n**Path A: If the ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} or failed (Step ${completionCheckStepNumber})**\n<complete success=\"true|false\">...</complete>\n\n**Path B: If the ${renderSubGoalsContent('goal is NOT complete', 'instruction is NOT fulfilled')} yet (Step ${actionStepNumber})**\n<!-- Determine next action -->\n${renderLogContent('<log>...</log>')}\n${actionOutputProtocol.actionOutputPlaceholder}\n\n<!-- OR if there's an error -->\n<error>...</error>\n\n${buildPlanningMultiTurnExample({\n includeSubGoals: shouldIncludeSubGoals,\n includeThought,\n includeLog,\n locatePromptSpec,\n actionOutputProtocol,\n prefix: planningProtocol.responsePrefix,\n})}`;\n}\n"],"names":["buildStandardPlanningSystemPrompt","input","actionSpace","includeLocateInPlanning","locatePromptSpec","includeSubGoals","includeThought","includeLog","planningProtocol","actionOutputProtocol","preferredLanguage","getPreferredLanguage","Error","planningModelFamilyRequiredForLocateMessage","actionSpaceDescription","buildPlanningActionSpaceDescription","hasRunAdbShell","action","actionOutputTagsText","tagName","shouldIncludeSubGoals","renderSubGoalsContent","content","fallbackContent","renderThoughtContent","renderLogContent","completionCheckStepNumber","actionStepNumber","locateGroundingRules","buildActionOutputExample","createSampleTapAction","buildPlanningMultiTurnExample"],"mappings":";;;;;;AA8BO,eAAeA,kCACpBC,KAA6C;IAE7C,MAAM,EACJC,WAAW,EACXC,uBAAuB,EACvBC,gBAAgB,EAChBC,eAAe,EACfC,iBAAiB,IAAI,EACrBC,aAAa,IAAI,EACjBC,gBAAgB,EACjB,GAAGP;IACJ,MAAMQ,uBAAuBD,iBAAiB,oBAAoB;IAClE,MAAME,oBAAoBC;IAE1B,IAAIR,2BAA2B,CAACC,kBAC9B,MAAM,IAAIQ,MAAMC;IAGlB,MAAMC,yBAAyBC,oCAAoC;QACjEb;QACAE;QACAI;IACF;IACA,MAAMQ,iBAAiBd,YAAY,IAAI,CACr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A8B;QAC9B,iBAAiBX;QACjBd;QACAC;QACAH;QACAK;QACA,QAAQD,iBAAiB,cAAc;IACzC,IAAI;AACJ"}
1
+ {"version":3,"file":"ai-model/prompt/planning/system-prompt.mjs","sources":["../../../../../src/ai-model/prompt/planning/system-prompt.ts"],"sourcesContent":["import type { DeviceAction } from '@/types';\nimport { getPreferredLanguage } from '@midscene/shared/env';\nimport type { StandardPlanningProtocol } from '../../model-adapter/planning-protocol';\nimport type { LocateResultPromptSpec } from '../../shared/model-locate-result';\nimport { planningModelFamilyRequiredForLocateMessage } from '../../shared/model-locate-result/errors';\nimport { locateGroundingRules } from '../locate';\nimport {\n buildActionOutputExample,\n createSampleTapAction,\n} from './action-output-example';\nimport { buildPlanningActionSpaceDescription } from './action-space-description';\nimport { buildPlanningMultiTurnExample } from './multi-turn-example';\n\ntype BuildStandardPlanningSystemPromptInput = {\n actionSpace: DeviceAction<any>[];\n includeSubGoals?: boolean;\n includeThought?: boolean;\n includeLog?: boolean;\n planningProtocol: StandardPlanningProtocol;\n} & (\n | {\n includeLocateInPlanning: true;\n locatePromptSpec: LocateResultPromptSpec;\n }\n | {\n includeLocateInPlanning: false;\n locatePromptSpec?: never;\n }\n);\n\nexport async function buildStandardPlanningSystemPrompt(\n input: BuildStandardPlanningSystemPromptInput,\n) {\n const {\n actionSpace,\n includeLocateInPlanning,\n locatePromptSpec,\n includeSubGoals,\n includeThought = true,\n includeLog = true,\n planningProtocol,\n } = input;\n const actionOutputProtocol = planningProtocol.actionOutputProtocol;\n const preferredLanguage = getPreferredLanguage();\n\n if (includeLocateInPlanning && !locatePromptSpec) {\n throw new Error(planningModelFamilyRequiredForLocateMessage());\n }\n\n const actionSpaceDescription = buildPlanningActionSpaceDescription({\n actionSpace,\n locatePromptSpec,\n planningProtocol,\n });\n const hasRunAdbShell = actionSpace.some(\n (action) => action.name === 'RunAdbShell',\n );\n const actionOutputTagsText = actionOutputProtocol.actionOutputTagNames\n .map((tagName) => `<${tagName}>`)\n .join(', ');\n\n const shouldIncludeSubGoals = includeSubGoals ?? false;\n const renderSubGoalsContent = (content: string, fallbackContent = '') =>\n shouldIncludeSubGoals ? content : fallbackContent;\n const renderThoughtContent = (content: string, fallbackContent = '') =>\n includeThought ? content : fallbackContent;\n const renderLogContent = (content: string, fallbackContent = '') =>\n includeLog ? content : fallbackContent;\n\n // Step numbering adjusts based on whether sub-goals are included\n // When includeSubGoals=false, memory step is skipped\n const completionCheckStepNumber = shouldIncludeSubGoals ? 3 : 2;\n const actionStepNumber = completionCheckStepNumber + 1;\n\n return `\nTarget: 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.\n\n## Step 1: ${renderSubGoalsContent(\n 'Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)',\n renderThoughtContent('Observe (related tags: <planning>)', 'Observe'),\n )}\n\nFirst, observe the current screenshot and previous logs${renderSubGoalsContent(\n \", 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.\",\n ' to understand the current state.',\n )}\n\n${renderSubGoalsContent(`### Observation Guidelines\n\n- Treat visible summaries, thumbnails, cropped content, and partially visible lists as potentially incomplete when the task depends on precise details.\n- 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.`)}\n\n${renderThoughtContent(`### <planning> tag (REQUIRED)\n\nREQUIRED: You MUST always output the <planning> tag. Never skip it.\n\nWrite the content of the <planning> tag in ${preferredLanguage}.\n\nInclude your planning details in the <planning> tag. It should answer: ${renderSubGoalsContent(\n \"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?\",\n 'What is the current state based on the screenshot? What should be the next action?',\n)} Write it naturally without numbering or section headers.\n\nCRITICAL - 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.`)}\n\n${renderSubGoalsContent(`### <update-plan-content> tag\n\nUse this structure to give or update your plan:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished|pending\">sub goal description</sub-goal>\n <sub-goal index=\"2\" status=\"finished|pending\">sub goal description</sub-goal>\n ...\n</update-plan-content>\n\n### <mark-sub-goal-done> tag\n\nUse this structure to mark a sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nIMPORTANT: You MUST only mark a sub-goal as \"finished\" AFTER you have confirmed the task is actually completed by observing the result in the screenshot. Do NOT mark a sub-goal as done just because you expect the next action will complete it. Wait until you see visual confirmation in the screenshot that the sub-goal has been achieved.\n\n### Note\n\nDuring execution, you can call <update-plan-content> at any time to update the plan based on the latest screenshot and completed sub-goals.\n\n### Example\n\nIf the user wants to \"log in to a system using username and password, complete all to-do items, and submit a registration form\", you can break it down into the following sub-goals:\n\n<planning>...</planning>\n<update-plan-content>\n <sub-goal index=\"1\" status=\"pending\">Log in to the system</sub-goal>\n <sub-goal index=\"2\" status=\"pending\">Complete all to-do items</sub-goal>\n <sub-goal index=\"3\" status=\"pending\">Submit the registration form</sub-goal>\n</update-plan-content>\n\nAfter logging in and seeing the to-do items, you can mark the sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nAt this point, the status of all sub-goals is:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished\" />\n <sub-goal index=\"2\" status=\"pending\" />\n <sub-goal index=\"3\" status=\"pending\" />\n</update-plan-content>\n\nAfter some time, when the last sub-goal is also completed, you can mark it as done as well:\n\n<mark-sub-goal-done>\n <sub-goal index=\"3\" status=\"finished\" />\n</mark-sub-goal-done>`)}\n\n${renderSubGoalsContent(`## Step 2: Memory Data from Current Screenshot (related tags: <memory>)\n\nUse <memory> to record clear, task-relevant information from the current screenshot that may be needed in later steps. The current screenshot will not be available later, so memory should preserve enough detail for future reasoning, verification, or action.\n\n- Record information completely and exactly as shown. Do not summarize, translate, normalize, or merge values that may matter later.\n- When recording an item, include the item itself, its exact task-relevant details, and the visible cue or UI context that identifies where it came from when relevant.\n- Keep similar or repeated items as separate memory entries unless their task-relevant details are confirmed to be the same.\n- After navigation, scrolling, editing, deletion, saving, or other screen changes, treat remembered positions, order, indexes, and UI bindings as references only. Re-check the current screen before acting on them.\n\nExamples:\n- If you need to find an item and later assert its details, record the item name and the exact details needed for the assertion, such as status, price, date, owner, description, or other visible fields.\n- If you need to compare multiple similar results, record each candidate separately with its exact distinguishing details and visible context.\n- If you need to copy information from one place to another, record the exact source value and the target field or UI cue it should be mapped to.\n\nDon't use this tag if no information needs to be preserved.`)}\n\n## Step ${completionCheckStepNumber}: ${renderSubGoalsContent(\n 'Check if Goal is Accomplished',\n 'Check if the Instruction is Fulfilled',\n )} (related tags: <complete>)\n\nDetermine if the entire task is completed${renderSubGoalsContent(' based on the current screenshot and the status of all sub-goals')}.\n\n### CRITICAL: The User's Instruction is the Supreme Authority\n\nThe user's instruction defines the EXACT scope of what you must accomplish. You MUST follow it precisely - nothing more, nothing less. Violating this rule may cause severe consequences such as data loss, unintended operations, or system failures.\n\n**Explicit instructions vs. High-level goals:**\n- If the user gives you **explicit operation steps** (e.g., \"click X\", \"type Y\", \"fill out the form\"), treat them as exact commands. Execute ONLY those steps, nothing more.\n- If the user gives you a **high-level goal** (e.g., \"log in to the system\", \"complete the purchase\"), you may determine the necessary steps to achieve it.\n\n**What \"${renderSubGoalsContent('goal accomplished', 'instruction fulfilled')}\" means:**\n- The ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} when you have done EXACTLY what the user asked - no extra steps, no assumptions.\n- Do NOT perform any action beyond the explicit instruction, even if it seems logical or helpful.\n\n**Examples - Explicit instructions (execute exactly, no extra steps):**\n- \"fill out the form\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when all fields are filled. Do NOT submit the form.\n- \"click the login button\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} once clicked. Do NOT wait for page load or verify login success.\n- \"type 'hello' in the search box\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when 'hello' is typed. Do NOT press Enter or trigger search.\n- \"select the first item\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when selected. Do NOT proceed to checkout.\n\n**Change completion:**\n- If the requested outcome is a durable change, such as create, edit, update, delete, save, send, submit, apply, or publish, do not stop at an unsaved draft, open editor, temporary input, transient selection, or staged value. Continue through the app/page's normal completion control such as Save, Done, Confirm, OK, Submit, Apply, Send, or Publish before completing, so the result remains after leaving the screen.\n- If the user only asks for an intermediate UI state, such as typing text, selecting an option, filling fields, or opening a screen without saving/submitting/applying, stop once that exact state is reached.\n\n**Special case - Scrollable option lists and dropdowns:**\n- When choosing an item from a scrollable select, dropdown, listbox, menu, or similar option list, first open the control if it is closed. Once the list is open, interact with the list itself, not the page.\n- If the target option is visible in the open list, Tap that exact option immediately.\n- If the list is open but the target option is not visible, try to find it by scrolling the open list/dropdown before giving up or interacting with other elements.\n- For an open dropdown/list, prefer small incremental Scroll actions with an explicit distance (typically 50-120 pixels) and a locate target describing the open list/dropdown. Do NOT omit distance while searching within a list, because the default scroll distance can skip over relevant options and cause oscillation.\n- While searching within an open dropdown/list, use short scrolls so intermediate options are not skipped.\n- After selecting the target, if the trigger text or result text shows the requested option, treat the current selection step as fulfilled and continue evaluating the remaining user instruction.\n\n**Special case - Text hidden by a narrow input field:**\n- CRITICAL PRIORITY OVERRIDE - Input verification after an input action:\n- This rule overrides the general requirement to verify the exact target text from the screenshot.\n- If the previous step already executed an input action, and the current input field is not empty, you MUST directly treat that input as successful.\n- In this situation, do NOT use the visible text in the screenshot to decide that the input is incomplete, incorrect, missing characters, out of order, or needs correction.\n- Do NOT perform ClearInput, another Input, KeyboardPress, or any other action intended to \"fix the input content\" just because the visible text looks different from the target text, has abnormal character order, missing characters, abnormal spacing, suspicious visual recognition results, or appears to have selected/highlighted text.\n- The general rule \"do EXACTLY what the user asked\" still applies to the intended input value you execute, but it MUST NOT be enforced by re-validating the visible text in the screenshot after the input action.\n- Differences in visible text must be assumed to be caused by clipping, horizontal scrolling, narrow input fields, text selection, caret position, or visual recognition errors rather than input failure.\n- Retry input only when the input field is clearly still empty, or when the page shows an explicit error message.\n\n**Special case - Assertion instructions:**\n- If the user's instruction includes an assertion (e.g., \"verify that...\", \"check that...\", \"assert...\"), and you observe from the screenshot that the assertion condition is NOT satisfied and cannot be satisfied, mark ${renderSubGoalsContent('the goal', 'it')} as failed (success=\"false\").\n- If the page is still loading (e.g., you see a loading spinner, skeleton screen, or progress bar), do NOT assert yet. Wait for the page to finish loading before evaluating the assertion.\n\n### Completion Criteria for Process-required Instructions\n\nIf the user's instruction includes explicit operation steps, ordering requirements, or action requirements, it is a process-required instruction.\n\nFor process-required instructions, do NOT treat the task as complete only because the current screenshot already shows the final expected state. Do NOT infer that earlier steps were executed from the final UI state.\n\nYou may output <complete success=\"true\"> only when the current execution history, previous logs, or the screenshot after the most recent action proves that every explicit step required by the user has been completed, and the final check condition is also satisfied.\n\nIf any explicit step lacks completion evidence in the current execution history, continue with the next missing step instead of outputting <complete>, even if the current screenshot appears to satisfy the final condition.\n\n${renderSubGoalsContent(\n '',\n `**Page navigation restriction:**\n- Unless the user's instruction explicitly asks you to click a link, jump to another page, or navigate to a URL, you MUST complete the task on the current page only.\n- Do NOT navigate away from the current page on your own initiative (e.g., do not click links that lead to other pages, do not use browser back/forward, do not open new URLs).\n- If the task cannot be accomplished on the current page and the user has not instructed you to navigate, report it as a failure (success=\"false\") instead of attempting to navigate to other pages.`,\n)}\n\n### Output Rules\n\n- If the task is NOT complete, skip this section and continue to Step ${actionStepNumber}.\n- Use the <complete success=\"true|false\">message</complete> tag to output the result if the goal is accomplished or failed.\n - the 'success' attribute is required. ${renderSubGoalsContent('It means whether the expected goal is accomplished based on what you observe in the current screenshot and the current execution history. ')}No matter what errors occurred during execution, set success=\"true\" only when the current execution history shows that all steps required by the user have been completed and the final state satisfies the requirement. If the user asks for explicit operation steps or an ordered workflow, do not treat those steps as completed only because the current screenshot already shows the final expected state. If the ${renderSubGoalsContent('expected goal is not accomplished and cannot be accomplished', 'instruction is not fulfilled and cannot be fulfilled')}, set success=\"false\".\n - the 'message' is the information that will be provided to the user. If the user asks for a specific format, strictly follow that.\n- If you output <complete>, do NOT output ${actionOutputTagsText}. The task ends here.\n\n## Step ${actionStepNumber}: Determine Next Action (related tags: ${renderLogContent('<log>, ')}${actionOutputTagsText}, <error>)\n\nONLY if the task is not complete: Think what the next action is according to the current screenshot${renderSubGoalsContent(' and the plan')}.\n\n- Don't give extra actions or plans beyond the instruction or the plan. For example, don't try to submit the form if the instruction is only to fill something.\n- Consider the current screenshot and give the action that is most likely to accomplish the instruction. For example, if the next step is to click a button but it's not visible in the screenshot, you should try to find it first instead of give a click action.\n- Make sure the previous actions are completed successfully. Otherwise, retry or do something else to recover.\n- Give just the next ONE action you should do (if any)\n- If there are some error messages reported by the previous actions, don't give up, try parse a new action to recover. If the error persists for more than 3 times, you should think this is an error and set the \"error\" field to the error message.\n\n### Action Guidelines\n\n${\n hasRunAdbShell\n ? \"- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action.\"\n : ''\n}\n- If Swipe is available in the current Action Space, for touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.\n- When editing existing text in a UI field, preserve all existing text by moving the cursor and typing/deleting the minimal necessary characters.\n- For insert/prepend/append edits, use CursorMove when the caret must be adjusted precisely, then use Input with mode \"typeOnly\" for inserted characters and KeyboardPress for newlines or deletion. If the caret lands in the wrong position, recover with CursorMove, KeyboardPress, or undo and retry cursor placement; do not switch to replace as a fallback for cursor placement failures.\n\n### Interpreting Scroll and Swipe Directions\n\nScroll and swipe directions can be ambiguous: they may refer to off-screen content to reveal, visible content movement, or the physical movement of a finger, pointer, or scroll wheel. Infer the intended result from the user's goal, the interaction target, the current UI, and common usage in the user's language, rather than mechanically copying the user's direction word.\n\nIn the current Action Space, \\`direction\\` has the following meanings:\n\n- Scroll follows the traditional mouse-wheel convention (with natural scrolling disabled). Its direction refers to the off-screen content to reveal; under this convention, it matches the wheel movement direction and is opposite to the content movement direction.\n- Swipe follows the finger-movement convention. Its direction refers to finger movement; for controls where content follows the finger, it matches the content movement direction and is opposite to the direction from which off-screen content is revealed.\n\nUse the following priority order:\n\n1. Prioritize the user's goal or expected result, even when it conflicts with a direction word. For example, for \"swipe the date picker down to increase the date\", if dates increase from top to bottom, use Swipe up to move a larger date from below into the selected position.\n2. Otherwise, if the user specifies a moving object or movement path, follow that object's physical movement. For example, \"swipe the finger to the left\" means Swipe left; \"move the page content from top to bottom\" means moving content downward, corresponding to Swipe down on a page where content follows the finger.\n3. Otherwise, consider the interaction target and common usage in the user's language. For content browsing, such as pages and lists, scroll directions usually refer to the off-screen content the user wants to see. For directly manipulated controls, such as sliders and wheel pickers, swipe directions usually refer to the intended movement of the control's movable part. For example, the Chinese \"往下滑一下页面\" and English \"scroll down the page\" usually mean revealing content below, corresponding to Scroll down; the Chinese \"向右滑动滑块\" and English \"slide the slider to the right\" usually mean moving the slider right, corresponding to Swipe right if using Swipe.\n4. If the intent remains ambiguous, use the Scroll and Swipe direction definitions above.\n\nAfter interpreting the intent, choose an appropriate Action from the current Action Space and use its supported parameters to achieve the intended result. Some actions support start and end points instead of \\`direction\\`. When using \\`direction\\`, ensure its value achieves the intended result according to the selected Action's definition.\n\n${includeLocateInPlanning ? locateGroundingRules() : ''}\n\n### ${planningProtocol.actionSpaceProtocol.title}\n\n${actionSpaceDescription}\n\n${renderLogContent(`### Log to give user feedback (preamble message)\n\nThe <log> tag is a brief preamble message to the user explaining what you're about to do. It should follow these principles and examples:\n\n- **Use ${preferredLanguage}**\n- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words or Chinese characters for quick updates).\n- **Build on prior context**: if this is not the first action to be done, use the preamble message to connect the dots with what's been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n\n**Examples:**\n- <log>Click the login button</log>\n- <log>Scroll to find the 'Yes' button in popup</log>\n- <log>Previous actions failed to find the 'Yes' button, i will try again</log>\n- <log>Go back to find the login button</log>`)}\n\n### If there is some action to do ...\n\n${actionOutputProtocol.actionOutputRules}\n\nFor example:\n${buildActionOutputExample(\n createSampleTapAction('Add to cart button for Sauce Labs Backpack'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 1,\n buildActionOutput: actionOutputProtocol.buildActionOutput,\n },\n)}\n\n### If you think there is an error ...\n\n- Use the <error> tag to output the error message.\n\nFor example:\n<error>Unable to find the required element on the page</error>\n\n### If there is no action to do ...\n\n- Don't output ${actionOutputTagsText} if there is no action to do.\n\n## Return Format\n\nReturn in XML format following this decision flow:\n\n${planningProtocol.responsePrefix ?? ''}\n\n${renderThoughtContent(`**Always include (REQUIRED):**\n<!-- Step 1: Observe and Plan -->\n<planning>Your planning details here. NEVER skip this tag.</planning>`)}\n${renderSubGoalsContent(`<!-- required when no update-plan-content is provided in the previous response -->\n<update-plan-content>...</update-plan-content>\n\n<!-- required when any sub-goal is completed -->\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\n<!-- Step 2: Memory data from current screenshot if needed -->\n<memory>...</memory>`)}\n\n**Then choose ONE of the following paths:**\n\n**Path A: If the ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} or failed (Step ${completionCheckStepNumber})**\n<complete success=\"true|false\">...</complete>\n\n**Path B: If the ${renderSubGoalsContent('goal is NOT complete', 'instruction is NOT fulfilled')} yet (Step ${actionStepNumber})**\n<!-- Determine next action -->\n${renderLogContent('<log>...</log>')}\n${actionOutputProtocol.actionOutputPlaceholder}\n\n<!-- OR if there's an error -->\n<error>...</error>\n\n${buildPlanningMultiTurnExample({\n includeSubGoals: shouldIncludeSubGoals,\n includeThought,\n includeLog,\n locatePromptSpec,\n actionOutputProtocol,\n prefix: planningProtocol.responsePrefix,\n})}`;\n}\n"],"names":["buildStandardPlanningSystemPrompt","input","actionSpace","includeLocateInPlanning","locatePromptSpec","includeSubGoals","includeThought","includeLog","planningProtocol","actionOutputProtocol","preferredLanguage","getPreferredLanguage","Error","planningModelFamilyRequiredForLocateMessage","actionSpaceDescription","buildPlanningActionSpaceDescription","hasRunAdbShell","action","actionOutputTagsText","tagName","shouldIncludeSubGoals","renderSubGoalsContent","content","fallbackContent","renderThoughtContent","renderLogContent","completionCheckStepNumber","actionStepNumber","locateGroundingRules","buildActionOutputExample","createSampleTapAction","buildPlanningMultiTurnExample"],"mappings":";;;;;;AA8BO,eAAeA,kCACpBC,KAA6C;IAE7C,MAAM,EACJC,WAAW,EACXC,uBAAuB,EACvBC,gBAAgB,EAChBC,eAAe,EACfC,iBAAiB,IAAI,EACrBC,aAAa,IAAI,EACjBC,gBAAgB,EACjB,GAAGP;IACJ,MAAMQ,uBAAuBD,iBAAiB,oBAAoB;IAClE,MAAME,oBAAoBC;IAE1B,IAAIR,2BAA2B,CAACC,kBAC9B,MAAM,IAAIQ,MAAMC;IAGlB,MAAMC,yBAAyBC,oCAAoC;QACjEb;QACAE;QACAI;IACF;IACA,MAAMQ,iBAAiBd,YAAY,IAAI,CACrC,CAACe,SAAWA,AAAgB,kBAAhBA,OAAO,IAAI;IAEzB,MAAMC,uBAAuBT,qBAAqB,oBAAoB,CACnE,GAAG,CAAC,CAACU,UAAY,CAAC,CAAC,EAAEA,QAAQ,CAAC,CAAC,EAC/B,IAAI,CAAC;IAER,MAAMC,wBAAwBf,mBAAmB;IACjD,MAAMgB,wBAAwB,CAACC,SAAiBC,kBAAkB,EAAE,GAClEH,wBAAwBE,UAAUC;IACpC,MAAMC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AgE,wDAAwD;;0CAE7sB,EAAEH,qBAAqB;;QAEzD,EAAES,iBAAiB,uCAAuC,EAAEF,iBAAiB,aAAaP,qBAAqB;;mGAEpB,EAAEG,sBAAsB,iBAAiB;;;;;;;;;;AAU5I,EACEL,iBACI,4GACA,GACL;;;;;;;;;;;;;;;;;;;;;;;AAuBD,EAAEb,0BAA0ByB,yBAAyB,GAAG;;IAEpD,EAAEpB,iBAAiB,mBAAmB,CAAC,KAAK,CAAC;;AAEjD,EAAEM,uBAAuB;;AAEzB,EAAEW,iBAAiB,CAAC;;;;QAIZ,EAAEf,kBAAkB;;;;;;;;;6CASiB,CAAC,EAAE;;;;AAIhD,EAAED,qBAAqB,iBAAiB,CAAC;;;AAGzC,EAAEoB,yBACAC,sBAAsB,+CACtB;QACE1B;QACA,0BAA0B;QAC1B,mBAAmBK,qBAAqB,iBAAiB;IAC3D,GACA;;;;;;;;;;;eAWa,EAAES,qBAAqB;;;;;;AAMtC,EAAEV,iBAAiB,cAAc,IAAI,GAAG;;AAExC,EAAEgB,qBAAqB,CAAC;;qEAE6C,CAAC,EAAE;AACxE,EAAEH,sBAAsB,CAAC;;;;;;;;;oBASL,CAAC,EAAE;;;;iBAIN,EAAEA,sBAAsB,wBAAwB,4BAA4B,iBAAiB,EAAEK,0BAA0B;;;iBAGzH,EAAEL,sBAAsB,wBAAwB,gCAAgC,WAAW,EAAEM,iBAAiB;;AAE/H,EAAEF,iBAAiB,kBAAkB;AACrC,EAAEhB,qBAAqB,uBAAuB,CAAC;;;;;AAK/C,EAAEsB,8BAA8B;QAC9B,iBAAiBX;QACjBd;QACAC;QACAH;QACAK;QACA,QAAQD,iBAAiB,cAAc;IACzC,IAAI;AACJ"}
@@ -102,8 +102,7 @@ async function runCustomPlanning(userInstruction, options, config) {
102
102
  preparedSize: preparedImage.preparedSize,
103
103
  contentSize: preparedImage.contentSize
104
104
  },
105
- acceptBbox2dAlias: preparedOptions.modelRuntime.adapter.acceptBbox2dAlias,
106
- parseRawLocateParameter: (value)=>value
105
+ acceptBbox2dAlias: preparedOptions.modelRuntime.adapter.acceptBbox2dAlias
107
106
  });
108
107
  shouldContinuePlanning = config.shouldContinuePlanning(parsed, actions);
109
108
  } catch (parseError) {
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/workflows/planning/custom-planning.mjs","sources":["../../../../../src/ai-model/workflows/planning/custom-planning.ts"],"sourcesContent":["import type { PlanningAIResponse, PlanningAction } from '@/types';\nimport type { ChatCompletionMessageParam } from 'openai/resources/index';\nimport { ScreenshotItem } from '../../../screenshot-item';\nimport type {\n CustomPlanningInput,\n CustomPlanningMessageConfig,\n ResolvedCustomPlanningDefinition,\n} from '../../model-adapter/custom-planning-types';\nimport { prepareModelImage } from '../../model-adapter/image-preprocess';\nimport type { ParsedPlanningLocateParameter } from '../../model-adapter/planning-protocol';\nimport {\n AIResponseParseError,\n callAIWithStringResponse,\n} from '../../service-caller/index';\nimport {\n type PreparedUserPrompt,\n preparedReferenceImagesToChatMessages,\n} from '../../shared/multimodal-prompt';\nimport { normalizePlanningActionLocateFields } from './locate-normalization';\nimport type { PlanOptions } from './types';\n\nfunction appendActionContext(\n systemPrompt: string,\n actionContext?: string,\n): string {\n return systemPrompt + (actionContext ? `${actionContext}\\n` : '');\n}\n\nexport function buildCustomPlanningMessages<TParsed>(\n input: CustomPlanningInput,\n config: CustomPlanningMessageConfig<TParsed>,\n): ChatCompletionMessageParam[] {\n const { options } = input;\n const { conversationHistory, context, actionContext } = options;\n const systemPrompt = appendActionContext(\n config.buildSystemPrompt(),\n actionContext,\n );\n const userInstructionText = input.userInstruction.text;\n const userInstruction = config.buildUserInstruction\n ? config.buildUserInstruction(userInstructionText)\n : userInstructionText;\n const referenceImageMessages = preparedReferenceImagesToChatMessages(\n input.userInstruction.referenceImages,\n );\n\n if (conversationHistory.pendingFeedbackMessage) {\n conversationHistory.append({\n role: 'user',\n content: [\n {\n type: 'text',\n text: `${conversationHistory.pendingFeedbackMessage}. The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.`,\n },\n ],\n });\n conversationHistory.resetPendingFeedbackMessageIfExists();\n }\n\n conversationHistory.append({\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: { url: context.screenshot.base64 },\n },\n ],\n });\n\n if (config.systemPromptPlacement === 'system-message') {\n return [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [{ type: 'text', text: userInstruction }],\n },\n ...referenceImageMessages,\n ...conversationHistory.snapshot(config.historyImageLimit),\n ];\n }\n\n return [\n {\n role: 'user',\n content: `${systemPrompt}${userInstruction}`,\n },\n ...referenceImageMessages,\n ...conversationHistory.snapshot(config.historyImageLimit),\n ];\n}\n\nexport async function runCustomPlanning<TParsed>(\n userInstruction: PreparedUserPrompt,\n options: PlanOptions,\n config: ResolvedCustomPlanningDefinition<TParsed>,\n): Promise<PlanningAIResponse> {\n const { context } = options;\n const preparedImage = await prepareModelImage({\n imageBase64: context.screenshot.base64,\n width: context.shotSize.width,\n height: context.shotSize.height,\n policy: options.modelRuntime.adapter.imagePreprocess,\n });\n const preparedOptions: PlanOptions = {\n ...options,\n context: {\n ...context,\n screenshot: ScreenshotItem.create(\n preparedImage.imageBase64,\n context.screenshot.capturedAt,\n ),\n shotSize: preparedImage.preparedSize,\n },\n };\n const input: CustomPlanningInput = {\n userInstruction,\n options: preparedOptions,\n coordinateSystem: config.coordinateSystem,\n };\n\n const messages = buildCustomPlanningMessages(input, config.messages);\n const { content, usage, rawChoiceMessage } = await callAIWithStringResponse(\n messages,\n preparedOptions.modelRuntime,\n {\n abortSignal: preparedOptions.abortSignal,\n requiresOriginalImageDetail: preparedOptions.includeLocateInPlanning,\n },\n );\n\n let parsed: TParsed;\n let actions: PlanningAction[];\n let shouldContinuePlanning: boolean;\n\n try {\n parsed = config.parseResponse(content, input);\n actions = config.transformActions(parsed, input);\n normalizePlanningActionLocateFields(actions, {\n actionSpace: preparedOptions.actionSpace,\n includeLocateInPlanning: preparedOptions.includeLocateInPlanning,\n locateResultCodec: config.coordinateNormalizer,\n locateResultContext: {\n preparedSize: preparedImage.preparedSize,\n contentSize: preparedImage.contentSize,\n },\n acceptBbox2dAlias: preparedOptions.modelRuntime.adapter.acceptBbox2dAlias,\n parseRawLocateParameter: (value) =>\n value as ParsedPlanningLocateParameter,\n });\n shouldContinuePlanning = config.shouldContinuePlanning(parsed, actions);\n } catch (parseError) {\n const errorMessage = `Parse error: ${\n parseError instanceof Error ? parseError.message : String(parseError)\n }`;\n throw new AIResponseParseError(\n errorMessage,\n JSON.stringify(content, undefined, 2),\n usage,\n rawChoiceMessage,\n );\n }\n\n const assistantContent = config.messages.buildAssistantContent?.(\n parsed,\n content,\n input,\n );\n // UI-TARS and Auto-GLM define their own assistant history format.\n if (assistantContent) {\n options.conversationHistory.append({\n role: 'assistant',\n content: assistantContent,\n });\n }\n\n return {\n actions,\n log: config.buildResponseLog(parsed, content),\n usage,\n shouldContinuePlanning,\n rawResponse: JSON.stringify(content, undefined, 2),\n rawChoiceMessage,\n };\n}\n"],"names":["appendActionContext","systemPrompt","actionContext","buildCustomPlanningMessages","input","config","options","conversationHistory","context","userInstructionText","userInstruction","referenceImageMessages","preparedReferenceImagesToChatMessages","runCustomPlanning","preparedImage","prepareModelImage","preparedOptions","ScreenshotItem","messages","content","usage","rawChoiceMessage","callAIWithStringResponse","parsed","actions","shouldContinuePlanning","normalizePlanningActionLocateFields","value","parseError","errorMessage","Error","String","AIResponseParseError","JSON","undefined","assistantContent"],"mappings":";;;;;AAqBA,SAASA,oBACPC,YAAoB,EACpBC,aAAsB;IAEtB,OAAOD,eAAgBC,CAAAA,gBAAgB,GAAGA,cAAc,EAAE,CAAC,GAAG,EAAC;AACjE;AAEO,SAASC,4BACdC,KAA0B,EAC1BC,MAA4C;IAE5C,MAAM,EAAEC,OAAO,EAAE,GAAGF;IACpB,MAAM,EAAEG,mBAAmB,EAAEC,OAAO,EAAEN,aAAa,EAAE,GAAGI;IACxD,MAAML,eAAeD,oBACnBK,OAAO,iBAAiB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,mBAAmB,CAAC,MAAM,CAAC;QACjC,MAAM;QACN,SAAS6B;IACX;IAGF,OAAO;QACLX;QACA,KAAKnB,OAAO,gBAAgB,CAACkB,QAAQJ;QACrCC;QACAK;QACA,aAAaQ,KAAK,SAAS,CAACd,SAASe,QAAW;QAChDb;IACF;AACF"}
1
+ {"version":3,"file":"ai-model/workflows/planning/custom-planning.mjs","sources":["../../../../../src/ai-model/workflows/planning/custom-planning.ts"],"sourcesContent":["import type { PlanningAIResponse, PlanningAction } from '@/types';\nimport type { ChatCompletionMessageParam } from 'openai/resources/index';\nimport { ScreenshotItem } from '../../../screenshot-item';\nimport type {\n CustomPlanningInput,\n CustomPlanningMessageConfig,\n ResolvedCustomPlanningDefinition,\n} from '../../model-adapter/custom-planning-types';\nimport { prepareModelImage } from '../../model-adapter/image-preprocess';\nimport {\n AIResponseParseError,\n callAIWithStringResponse,\n} from '../../service-caller/index';\nimport {\n type PreparedUserPrompt,\n preparedReferenceImagesToChatMessages,\n} from '../../shared/multimodal-prompt';\nimport { normalizePlanningActionLocateFields } from './locate-normalization';\nimport type { PlanOptions } from './types';\n\nfunction appendActionContext(\n systemPrompt: string,\n actionContext?: string,\n): string {\n return systemPrompt + (actionContext ? `${actionContext}\\n` : '');\n}\n\nexport function buildCustomPlanningMessages<TParsed>(\n input: CustomPlanningInput,\n config: CustomPlanningMessageConfig<TParsed>,\n): ChatCompletionMessageParam[] {\n const { options } = input;\n const { conversationHistory, context, actionContext } = options;\n const systemPrompt = appendActionContext(\n config.buildSystemPrompt(),\n actionContext,\n );\n const userInstructionText = input.userInstruction.text;\n const userInstruction = config.buildUserInstruction\n ? config.buildUserInstruction(userInstructionText)\n : userInstructionText;\n const referenceImageMessages = preparedReferenceImagesToChatMessages(\n input.userInstruction.referenceImages,\n );\n\n if (conversationHistory.pendingFeedbackMessage) {\n conversationHistory.append({\n role: 'user',\n content: [\n {\n type: 'text',\n text: `${conversationHistory.pendingFeedbackMessage}. The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.`,\n },\n ],\n });\n conversationHistory.resetPendingFeedbackMessageIfExists();\n }\n\n conversationHistory.append({\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: { url: context.screenshot.base64 },\n },\n ],\n });\n\n if (config.systemPromptPlacement === 'system-message') {\n return [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [{ type: 'text', text: userInstruction }],\n },\n ...referenceImageMessages,\n ...conversationHistory.snapshot(config.historyImageLimit),\n ];\n }\n\n return [\n {\n role: 'user',\n content: `${systemPrompt}${userInstruction}`,\n },\n ...referenceImageMessages,\n ...conversationHistory.snapshot(config.historyImageLimit),\n ];\n}\n\nexport async function runCustomPlanning<TParsed>(\n userInstruction: PreparedUserPrompt,\n options: PlanOptions,\n config: ResolvedCustomPlanningDefinition<TParsed>,\n): Promise<PlanningAIResponse> {\n const { context } = options;\n const preparedImage = await prepareModelImage({\n imageBase64: context.screenshot.base64,\n width: context.shotSize.width,\n height: context.shotSize.height,\n policy: options.modelRuntime.adapter.imagePreprocess,\n });\n const preparedOptions: PlanOptions = {\n ...options,\n context: {\n ...context,\n screenshot: ScreenshotItem.create(\n preparedImage.imageBase64,\n context.screenshot.capturedAt,\n ),\n shotSize: preparedImage.preparedSize,\n },\n };\n const input: CustomPlanningInput = {\n userInstruction,\n options: preparedOptions,\n coordinateSystem: config.coordinateSystem,\n };\n\n const messages = buildCustomPlanningMessages(input, config.messages);\n const { content, usage, rawChoiceMessage } = await callAIWithStringResponse(\n messages,\n preparedOptions.modelRuntime,\n {\n abortSignal: preparedOptions.abortSignal,\n requiresOriginalImageDetail: preparedOptions.includeLocateInPlanning,\n },\n );\n\n let parsed: TParsed;\n let actions: PlanningAction[];\n let shouldContinuePlanning: boolean;\n\n try {\n parsed = config.parseResponse(content, input);\n actions = config.transformActions(parsed, input);\n normalizePlanningActionLocateFields(actions, {\n actionSpace: preparedOptions.actionSpace,\n includeLocateInPlanning: preparedOptions.includeLocateInPlanning,\n locateResultCodec: config.coordinateNormalizer,\n locateResultContext: {\n preparedSize: preparedImage.preparedSize,\n contentSize: preparedImage.contentSize,\n },\n acceptBbox2dAlias: preparedOptions.modelRuntime.adapter.acceptBbox2dAlias,\n });\n shouldContinuePlanning = config.shouldContinuePlanning(parsed, actions);\n } catch (parseError) {\n const errorMessage = `Parse error: ${\n parseError instanceof Error ? parseError.message : String(parseError)\n }`;\n throw new AIResponseParseError(\n errorMessage,\n JSON.stringify(content, undefined, 2),\n usage,\n rawChoiceMessage,\n );\n }\n\n const assistantContent = config.messages.buildAssistantContent?.(\n parsed,\n content,\n input,\n );\n // UI-TARS and Auto-GLM define their own assistant history format.\n if (assistantContent) {\n options.conversationHistory.append({\n role: 'assistant',\n content: assistantContent,\n });\n }\n\n return {\n actions,\n log: config.buildResponseLog(parsed, content),\n usage,\n shouldContinuePlanning,\n rawResponse: JSON.stringify(content, undefined, 2),\n rawChoiceMessage,\n };\n}\n"],"names":["appendActionContext","systemPrompt","actionContext","buildCustomPlanningMessages","input","config","options","conversationHistory","context","userInstructionText","userInstruction","referenceImageMessages","preparedReferenceImagesToChatMessages","runCustomPlanning","preparedImage","prepareModelImage","preparedOptions","ScreenshotItem","messages","content","usage","rawChoiceMessage","callAIWithStringResponse","parsed","actions","shouldContinuePlanning","normalizePlanningActionLocateFields","parseError","errorMessage","Error","String","AIResponseParseError","JSON","undefined","assistantContent"],"mappings":";;;;;AAoBA,SAASA,oBACPC,YAAoB,EACpBC,aAAsB;IAEtB,OAAOD,eAAgBC,CAAAA,gBAAgB,GAAGA,cAAc,EAAE,CAAC,GAAG,EAAC;AACjE;AAEO,SAASC,4BACdC,KAA0B,EAC1BC,MAA4C;IAE5C,MAAM,EAAEC,OAAO,EAAE,GAAGF;IACpB,MAAM,EAAEG,mBAAmB,EAAEC,OAAO,EAAEN,aAAa,EAAE,GAAGI;IACxD,MAAML,eAAeD,oBACnBK,OAAO,iBAAiB,IACxBH;IAEF,MAAMO,sBAAsBL,MAAM,eAAe,CAAC,IAA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,KAAKnB,OAAO,gBAAgB,CAACkB,QAAQJ;QACrCC;QACAK;QACA,aAAaO,KAAK,SAAS,CAACb,SAASc,QAAW;QAChDZ;IACF;AACF"}
@@ -2,7 +2,7 @@ import { findAllMidsceneLocatorField } from "../../../common.mjs";
2
2
  import { getDebug } from "@midscene/shared/logger";
3
3
  import { assert } from "@midscene/shared/utils";
4
4
  const debug = getDebug('planning');
5
- function normalizePlanningActionLocateFields(actions, { actionSpace, includeLocateInPlanning, locateResultCodec, locateResultContext, acceptBbox2dAlias = false, parseRawLocateParameter }) {
5
+ function normalizePlanningActionLocateFields(actions, { actionSpace, ...options }) {
6
6
  actions.forEach((action)=>{
7
7
  const actionInActionSpace = actionSpace.find((actionInSpace)=>actionInSpace.name === action.type);
8
8
  if (!actionInActionSpace) return void debug('skip locate normalization for action outside actionSpace', action);
@@ -10,33 +10,32 @@ function normalizePlanningActionLocateFields(actions, { actionSpace, includeLoca
10
10
  const locateFields = findAllMidsceneLocatorField(actionInActionSpace.paramSchema);
11
11
  debug('locateFields', locateFields);
12
12
  locateFields.forEach((field)=>{
13
- const rawLocateParameter = action.param?.[field];
14
- if (!rawLocateParameter) return;
15
- const locateParameter = parseRawLocateParameter(rawLocateParameter);
16
- if (!includeLocateInPlanning) {
17
- action.param[field] = {
18
- prompt: locateParameter.prompt
19
- };
20
- return;
21
- }
22
- assert(locateResultCodec, 'planning locate normalization requires a locate result codec');
23
- const resultKey = locateResultCodec.promptSpec.resultKey;
24
- const rawLocateValue = void 0 !== locateParameter[resultKey] ? locateParameter[resultKey] : acceptBbox2dAlias && 'bbox' === resultKey ? locateParameter.bbox_2d : void 0;
25
- const rawCoordinateKeys = new Set([
26
- resultKey,
27
- ...acceptBbox2dAlias && 'bbox' === resultKey ? [
28
- 'bbox_2d'
29
- ] : []
30
- ]);
31
- const locateParamWithoutRawCoordinates = Object.fromEntries(Object.entries(locateParameter).filter(([key])=>!rawCoordinateKeys.has(key)));
32
- const result = locateResultCodec.toPixelResult(rawLocateValue, locateResultContext);
33
- action.param[field] = {
34
- ...locateParamWithoutRawCoordinates,
35
- locatedPixelResult: result
36
- };
13
+ const locateParameter = action.param?.[field];
14
+ if (!locateParameter) return;
15
+ action.param[field] = normalizePlanningLocateParameter(locateParameter, options);
37
16
  });
38
17
  });
39
18
  }
40
- export { normalizePlanningActionLocateFields };
19
+ function normalizePlanningLocateParameter(locateParameter, { includeLocateInPlanning, locateResultCodec, locateResultContext, acceptBbox2dAlias = false }) {
20
+ if (!includeLocateInPlanning) return {
21
+ prompt: locateParameter.prompt
22
+ };
23
+ assert(locateResultCodec, 'planning locate normalization requires a locate result codec');
24
+ const resultKey = locateResultCodec.promptSpec.resultKey;
25
+ const rawLocateValue = void 0 !== locateParameter[resultKey] ? locateParameter[resultKey] : acceptBbox2dAlias && 'bbox' === resultKey ? locateParameter.bbox_2d : void 0;
26
+ const rawCoordinateKeys = new Set([
27
+ resultKey,
28
+ ...acceptBbox2dAlias && 'bbox' === resultKey ? [
29
+ 'bbox_2d'
30
+ ] : []
31
+ ]);
32
+ const locateParamWithoutRawCoordinates = Object.fromEntries(Object.entries(locateParameter).filter(([key])=>!rawCoordinateKeys.has(key)));
33
+ const result = locateResultCodec.toPixelResult(rawLocateValue, locateResultContext);
34
+ return {
35
+ ...locateParamWithoutRawCoordinates,
36
+ locatedPixelResult: result
37
+ };
38
+ }
39
+ export { normalizePlanningActionLocateFields, normalizePlanningLocateParameter };
41
40
 
42
41
  //# sourceMappingURL=locate-normalization.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/workflows/planning/locate-normalization.mjs","sources":["../../../../../src/ai-model/workflows/planning/locate-normalization.ts"],"sourcesContent":["import { findAllMidsceneLocatorField } from '@/common';\nimport type { DeviceAction } from '@/device';\nimport type { PlanningAction } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport type { ParsedPlanningLocateParameter } from '../../model-adapter/planning-protocol';\nimport type {\n LocateResultCodec,\n LocateResultContext,\n} from '../../shared/model-locate-result/types';\n\nconst debug = getDebug('planning');\n\nexport function normalizePlanningActionLocateFields(\n actions: PlanningAction[],\n {\n actionSpace,\n includeLocateInPlanning,\n locateResultCodec,\n locateResultContext,\n acceptBbox2dAlias = false,\n parseRawLocateParameter,\n }: {\n actionSpace: DeviceAction[];\n includeLocateInPlanning: boolean;\n locateResultCodec?: LocateResultCodec;\n locateResultContext: LocateResultContext;\n acceptBbox2dAlias?: boolean;\n parseRawLocateParameter: (value: unknown) => ParsedPlanningLocateParameter;\n },\n): void {\n actions.forEach((action) => {\n const actionInActionSpace = actionSpace.find(\n (actionInSpace) => actionInSpace.name === action.type,\n );\n if (!actionInActionSpace) {\n debug('skip locate normalization for action outside actionSpace', action);\n return;\n }\n\n debug('actionInActionSpace matched', actionInActionSpace);\n const locateFields = findAllMidsceneLocatorField(\n actionInActionSpace.paramSchema,\n );\n\n debug('locateFields', locateFields);\n\n locateFields.forEach((field) => {\n const rawLocateParameter = action.param?.[field];\n if (!rawLocateParameter) {\n return;\n }\n\n const locateParameter = parseRawLocateParameter(rawLocateParameter);\n\n if (!includeLocateInPlanning) {\n // In prompt-only planning mode, ignore any accidental coordinates from the model.\n action.param[field] = { prompt: locateParameter.prompt };\n return;\n }\n\n assert(\n locateResultCodec,\n 'planning locate normalization requires a locate result codec',\n );\n\n const resultKey = locateResultCodec.promptSpec.resultKey;\n const rawLocateValue =\n locateParameter[resultKey] !== undefined\n ? locateParameter[resultKey]\n : acceptBbox2dAlias && resultKey === 'bbox'\n ? locateParameter.bbox_2d\n : undefined;\n\n // The raw result field is replaced by locatedPixelResult, so it should not\n // remain in the normalized locate parameter.\n const rawCoordinateKeys = new Set([\n resultKey,\n ...(acceptBbox2dAlias && resultKey === 'bbox' ? ['bbox_2d'] : []),\n ]);\n\n const locateParamWithoutRawCoordinates = Object.fromEntries(\n Object.entries(locateParameter).filter(\n ([key]) => !rawCoordinateKeys.has(key),\n ),\n );\n\n const result = locateResultCodec.toPixelResult(\n rawLocateValue,\n locateResultContext,\n );\n action.param[field] = {\n ...locateParamWithoutRawCoordinates,\n locatedPixelResult: result,\n };\n });\n });\n}\n"],"names":["debug","getDebug","normalizePlanningActionLocateFields","actions","actionSpace","includeLocateInPlanning","locateResultCodec","locateResultContext","acceptBbox2dAlias","parseRawLocateParameter","action","actionInActionSpace","actionInSpace","locateFields","findAllMidsceneLocatorField","field","rawLocateParameter","locateParameter","assert","resultKey","rawLocateValue","undefined","rawCoordinateKeys","Set","locateParamWithoutRawCoordinates","Object","key","result"],"mappings":";;;AAWA,MAAMA,QAAQC,SAAS;AAEhB,SAASC,oCACdC,OAAyB,EACzB,EACEC,WAAW,EACXC,uBAAuB,EACvBC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,KAAK,EACzBC,uBAAuB,EAQxB;IAEDN,QAAQ,OAAO,CAAC,CAACO;QACf,MAAMC,sBAAsBP,YAAY,IAAI,CAC1C,CAACQ,gBAAkBA,cAAc,IAAI,KAAKF,OAAO,IAAI;QAEvD,IAAI,CAACC,qBAAqB,YACxBX,MAAM,4DAA4DU;QAIpEV,MAAM,+BAA+BW;QACrC,MAAME,eAAeC,4BACnBH,oBAAoB,WAAW;QAGjCX,MAAM,gBAAgBa;QAEtBA,aAAa,OAAO,CAAC,CAACE;YACpB,MAAMC,qBAAqBN,OAAO,KAAK,EAAE,CAACK,MAAM;YAChD,IAAI,CAACC,oBACH;YAGF,MAAMC,kBAAkBR,wBAAwBO;YAEhD,IAAI,CAACX,yBAAyB;gBAE5BK,OAAO,KAAK,CAACK,MAAM,GAAG;oBAAE,QAAQE,gBAAgB,MAAM;gBAAC;gBACvD;YACF;YAEAC,OACEZ,mBACA;YAGF,MAAMa,YAAYb,kBAAkB,UAAU,CAAC,SAAS;YACxD,MAAMc,iBACJH,AAA+BI,WAA/BJ,eAAe,CAACE,UAAU,GACtBF,eAAe,CAACE,UAAU,GAC1BX,qBAAqBW,AAAc,WAAdA,YACnBF,gBAAgB,OAAO,GACvBI;YAIR,MAAMC,oBAAoB,IAAIC,IAAI;gBAChCJ;mBACIX,qBAAqBW,AAAc,WAAdA,YAAuB;oBAAC;iBAAU,GAAG,EAAE;aACjE;YAED,MAAMK,mCAAmCC,OAAO,WAAW,CACzDA,OAAO,OAAO,CAACR,iBAAiB,MAAM,CACpC,CAAC,CAACS,IAAI,GAAK,CAACJ,kBAAkB,GAAG,CAACI;YAItC,MAAMC,SAASrB,kBAAkB,aAAa,CAC5Cc,gBACAb;YAEFG,OAAO,KAAK,CAACK,MAAM,GAAG;gBACpB,GAAGS,gCAAgC;gBACnC,oBAAoBG;YACtB;QACF;IACF;AACF"}
1
+ {"version":3,"file":"ai-model/workflows/planning/locate-normalization.mjs","sources":["../../../../../src/ai-model/workflows/planning/locate-normalization.ts"],"sourcesContent":["import { findAllMidsceneLocatorField } from '@/common';\nimport type { DeviceAction } from '@/device';\nimport type { PlanningAction } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport type { ParsedPlanningLocateParameter } from '../../model-adapter/planning-protocol';\nimport type {\n LocateResultCodec,\n LocateResultContext,\n} from '../../shared/model-locate-result/types';\n\nconst debug = getDebug('planning');\n\nexport function normalizePlanningActionLocateFields(\n actions: PlanningAction[],\n {\n actionSpace,\n ...options\n }: PlanningLocateNormalizationOptions & {\n actionSpace: DeviceAction[];\n },\n): void {\n actions.forEach((action) => {\n const actionInActionSpace = actionSpace.find(\n (actionInSpace) => actionInSpace.name === action.type,\n );\n if (!actionInActionSpace) {\n debug('skip locate normalization for action outside actionSpace', action);\n return;\n }\n\n debug('actionInActionSpace matched', actionInActionSpace);\n const locateFields = findAllMidsceneLocatorField(\n actionInActionSpace.paramSchema,\n );\n\n debug('locateFields', locateFields);\n\n locateFields.forEach((field) => {\n const locateParameter = action.param?.[field];\n if (!locateParameter) {\n return;\n }\n\n action.param[field] = normalizePlanningLocateParameter(\n locateParameter,\n options,\n );\n });\n });\n}\n\nexport type PlanningLocateNormalizationOptions = {\n includeLocateInPlanning: boolean;\n locateResultCodec?: LocateResultCodec;\n locateResultContext: LocateResultContext;\n acceptBbox2dAlias?: boolean;\n};\n\nexport function normalizePlanningLocateParameter(\n locateParameter: ParsedPlanningLocateParameter,\n {\n includeLocateInPlanning,\n locateResultCodec,\n locateResultContext,\n acceptBbox2dAlias = false,\n }: PlanningLocateNormalizationOptions,\n): Record<string, unknown> {\n if (!includeLocateInPlanning) {\n // In prompt-only planning mode, ignore any accidental coordinates from the model.\n return { prompt: locateParameter.prompt };\n }\n\n assert(\n locateResultCodec,\n 'planning locate normalization requires a locate result codec',\n );\n\n const resultKey = locateResultCodec.promptSpec.resultKey;\n const rawLocateValue =\n locateParameter[resultKey] !== undefined\n ? locateParameter[resultKey]\n : acceptBbox2dAlias && resultKey === 'bbox'\n ? locateParameter.bbox_2d\n : undefined;\n\n // The raw result field is replaced by locatedPixelResult, so it should not\n // remain in the normalized locate parameter.\n const rawCoordinateKeys = new Set([\n resultKey,\n ...(acceptBbox2dAlias && resultKey === 'bbox' ? ['bbox_2d'] : []),\n ]);\n\n const locateParamWithoutRawCoordinates = Object.fromEntries(\n Object.entries(locateParameter).filter(\n ([key]) => !rawCoordinateKeys.has(key),\n ),\n );\n\n const result = locateResultCodec.toPixelResult(\n rawLocateValue,\n locateResultContext,\n );\n return {\n ...locateParamWithoutRawCoordinates,\n locatedPixelResult: result,\n };\n}\n"],"names":["debug","getDebug","normalizePlanningActionLocateFields","actions","actionSpace","options","action","actionInActionSpace","actionInSpace","locateFields","findAllMidsceneLocatorField","field","locateParameter","normalizePlanningLocateParameter","includeLocateInPlanning","locateResultCodec","locateResultContext","acceptBbox2dAlias","assert","resultKey","rawLocateValue","undefined","rawCoordinateKeys","Set","locateParamWithoutRawCoordinates","Object","key","result"],"mappings":";;;AAWA,MAAMA,QAAQC,SAAS;AAEhB,SAASC,oCACdC,OAAyB,EACzB,EACEC,WAAW,EACX,GAAGC,SAGJ;IAEDF,QAAQ,OA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orField, parseActionParam, validateRequiredLocateFields } from "../../../common.mjs";
2
+ import { isPlainObject } from "@midscene/shared/utils";
3
+ import { z } from "zod";
4
+ import { normalizePlanningLocateParameter } from "./locate-normalization.mjs";
5
+ function parsePlanningActions(actions, { actionSpace, parseRawLocateParameter, ...normalizationOptions }) {
6
+ for (const action of actions){
7
+ const definition = findActionInActionSpaceOrThrow(action.type, actionSpace);
8
+ if (!definition.paramSchema) continue;
9
+ const locateFields = findAllMidsceneLocatorField(definition.paramSchema);
10
+ try {
11
+ for (const field of locateFields){
12
+ const rawLocate = action.param?.[field];
13
+ if (null != rawLocate) action.param[field] = parseRawLocateParameter(rawLocate);
14
+ }
15
+ validateRequiredLocateFields(action.param, definition.paramSchema);
16
+ parseActionParam(action.param, definition.paramSchema);
17
+ for (const field of locateFields){
18
+ const locate = action.param?.[field];
19
+ if (void 0 === locate) continue;
20
+ if (!isPlainObject(locate)) throw new Error(`${field}: Expected an object with a prompt field`);
21
+ const prompt = locate.prompt;
22
+ if (void 0 === prompt) throw new Error(`${field}.prompt: Required`);
23
+ const result = TUserPromptSchema.safeParse(prompt);
24
+ if (!result.success) throw new z.ZodError(result.error.issues.map((issue)=>({
25
+ ...issue,
26
+ path: [
27
+ field,
28
+ 'prompt',
29
+ ...issue.path
30
+ ]
31
+ })));
32
+ action.param[field] = normalizePlanningLocateParameter(locate, normalizationOptions);
33
+ }
34
+ } catch (error) {
35
+ const details = error instanceof z.ZodError ? error.issues.map((issue)=>`${issue.path.join('.') || 'param'}: ${issue.message}`).join('; ') : error instanceof Error ? error.message : String(error);
36
+ throw new Error(`Invalid parameters for action ${action.type}: ${details}`, {
37
+ cause: error
38
+ });
39
+ }
40
+ }
41
+ }
42
+ export { parsePlanningActions };
43
+
44
+ //# sourceMappingURL=parse-planning-actions.mjs.map