@midscene/core 1.10.1 → 1.10.2

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 (58) hide show
  1. package/dist/es/agent/utils.mjs +1 -1
  2. package/dist/es/ai-model/llm-planning.mjs +1 -1
  3. package/dist/es/ai-model/llm-planning.mjs.map +1 -1
  4. package/dist/es/ai-model/models/default.mjs +2 -1
  5. package/dist/es/ai-model/models/default.mjs.map +1 -1
  6. package/dist/es/ai-model/models/gemini.mjs +4 -15
  7. package/dist/es/ai-model/models/gemini.mjs.map +1 -1
  8. package/dist/es/ai-model/prompt/describe.mjs +31 -34
  9. package/dist/es/ai-model/prompt/describe.mjs.map +1 -1
  10. package/dist/es/ai-model/prompt/extraction.mjs +6 -6
  11. package/dist/es/ai-model/prompt/extraction.mjs.map +1 -1
  12. package/dist/es/ai-model/prompt/llm-planning.mjs +19 -19
  13. package/dist/es/ai-model/prompt/llm-planning.mjs.map +1 -1
  14. package/dist/es/ai-model/prompt/locate-grounding-rules.mjs +7 -3
  15. package/dist/es/ai-model/prompt/locate-grounding-rules.mjs.map +1 -1
  16. package/dist/es/element-describer.mjs +36 -18
  17. package/dist/es/element-describer.mjs.map +1 -1
  18. package/dist/es/index.mjs +2 -2
  19. package/dist/es/index.mjs.map +1 -1
  20. package/dist/es/service/index.mjs +98 -22
  21. package/dist/es/service/index.mjs.map +1 -1
  22. package/dist/es/service/utils.mjs +65 -1
  23. package/dist/es/service/utils.mjs.map +1 -1
  24. package/dist/es/types.mjs.map +1 -1
  25. package/dist/es/utils.mjs +2 -2
  26. package/dist/lib/agent/utils.js +1 -1
  27. package/dist/lib/ai-model/llm-planning.js +1 -1
  28. package/dist/lib/ai-model/llm-planning.js.map +1 -1
  29. package/dist/lib/ai-model/models/default.js +2 -1
  30. package/dist/lib/ai-model/models/default.js.map +1 -1
  31. package/dist/lib/ai-model/models/gemini.js +4 -15
  32. package/dist/lib/ai-model/models/gemini.js.map +1 -1
  33. package/dist/lib/ai-model/prompt/describe.js +31 -34
  34. package/dist/lib/ai-model/prompt/describe.js.map +1 -1
  35. package/dist/lib/ai-model/prompt/extraction.js +6 -6
  36. package/dist/lib/ai-model/prompt/extraction.js.map +1 -1
  37. package/dist/lib/ai-model/prompt/llm-planning.js +19 -19
  38. package/dist/lib/ai-model/prompt/llm-planning.js.map +1 -1
  39. package/dist/lib/ai-model/prompt/locate-grounding-rules.js +7 -3
  40. package/dist/lib/ai-model/prompt/locate-grounding-rules.js.map +1 -1
  41. package/dist/lib/element-describer.js +37 -22
  42. package/dist/lib/element-describer.js.map +1 -1
  43. package/dist/lib/index.js +1 -4
  44. package/dist/lib/index.js.map +1 -1
  45. package/dist/lib/service/index.js +96 -20
  46. package/dist/lib/service/index.js.map +1 -1
  47. package/dist/lib/service/utils.js +98 -1
  48. package/dist/lib/service/utils.js.map +1 -1
  49. package/dist/lib/types.js.map +1 -1
  50. package/dist/lib/utils.js +2 -2
  51. package/dist/types/ai-model/models/gemini.d.ts +1 -1
  52. package/dist/types/ai-model/models/registry.d.ts +1 -1
  53. package/dist/types/element-describer.d.ts +3 -6
  54. package/dist/types/index.d.ts +1 -1
  55. package/dist/types/service/index.d.ts +1 -1
  56. package/dist/types/service/utils.d.ts +21 -2
  57. package/dist/types/types.d.ts +1 -0
  58. package/package.json +2 -2
@@ -141,16 +141,16 @@ async function systemPromptToTaskPlanning({ actionSpace, locatePromptSpec, inclu
141
141
  const locateExample1 = locateExample('Add to cart button for Sauce Labs Backpack', 1);
142
142
  const locateNameField = locateExample('Name input field in the registration form', 2);
143
143
  const locateEmailField = locateExample('Email input field in the registration form', 3);
144
- const step1Title = shouldIncludeSubGoals ? '## Step 1: Observe and Plan (related tags: <thought>, <update-plan-content>, <mark-sub-goal-done>)' : '## Step 1: Observe (related tags: <thought>)';
144
+ const step1Title = shouldIncludeSubGoals ? '## Step 1: Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)' : '## Step 1: Observe (related tags: <planning>)';
145
145
  const step1Description = shouldIncludeSubGoals ? "First, observe the current screenshot and previous logs, 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." : 'First, observe the current screenshot and previous logs to understand the current state.';
146
146
  const explicitInstructionRule = 'CRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: "fill out the form" means only fill fields, do NOT submit; "click the button" means only click, do NOT wait for page load or verify results; "type \'hello\'" means only type, do NOT press Enter.';
147
- const thoughtTagDescription = shouldIncludeSubGoals ? `REQUIRED: You MUST always output the <thought> tag. Never skip it.
147
+ const planningTagDescription = shouldIncludeSubGoals ? `REQUIRED: You MUST always output the <planning> tag. Never skip it.
148
148
 
149
- Include your thought process in the <thought> tag. It should answer: 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? Write your thoughts naturally without numbering or section headers.
149
+ Include your planning details in the <planning> tag. It should answer: 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? Write it naturally without numbering or section headers.
150
150
 
151
- ${explicitInstructionRule}` : `REQUIRED: You MUST always output the <thought> tag. Never skip it.
151
+ ${explicitInstructionRule}` : `REQUIRED: You MUST always output the <planning> tag. Never skip it.
152
152
 
153
- Include your thought process in the <thought> tag. It should answer: What is the current state based on the screenshot? What should be the next action? Write your thoughts naturally without numbering or section headers.
153
+ Include your planning details in the <planning> tag. It should answer: What is the current state based on the screenshot? What should be the next action? Write it naturally without numbering or section headers.
154
154
 
155
155
  ${explicitInstructionRule}`;
156
156
  const subGoalTags = shouldIncludeSubGoals ? `
@@ -183,7 +183,7 @@ During execution, you can call <update-plan-content> at any time to update the p
183
183
 
184
184
  If 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:
185
185
 
186
- <thought>...</thought>
186
+ <planning>...</planning>
187
187
  <update-plan-content>
188
188
  <sub-goal index="1" status="pending">Log in to the system</sub-goal>
189
189
  <sub-goal index="2" status="pending">Complete all to-do items</sub-goal>
@@ -219,9 +219,9 @@ ${step1Title}
219
219
 
220
220
  ${step1Description}
221
221
  ${shouldIncludeSubGoals ? `\n${OBSERVE_STEP_NOTES}\n` : ''}
222
- * <thought> tag (REQUIRED)
222
+ * <planning> tag (REQUIRED)
223
223
 
224
- ${thoughtTagDescription}
224
+ ${planningTagDescription}
225
225
  ${subGoalTags}
226
226
  ${shouldIncludeSubGoals ? `
227
227
  ## Step ${memoryStepNumber}: Memory Data from Current Screenshot (related tags: <memory>)
@@ -364,7 +364,7 @@ Return in XML format following this decision flow:
364
364
 
365
365
  **Always include (REQUIRED):**
366
366
  <!-- Step 1: Observe${shouldIncludeSubGoals ? ' and Plan' : ''} -->
367
- <thought>Your thought process here. NEVER skip this tag.</thought>
367
+ <planning>Your planning details here. NEVER skip this tag.</planning>
368
368
  ${shouldIncludeSubGoals ? `
369
369
  <!-- required when no update-plan-content is provided in the previous response -->
370
370
  <update-plan-content>...</update-plan-content>
@@ -403,7 +403,7 @@ Below is an example of a multi-turn conversation for "fill out the registration
403
403
  **Screenshot:** [Shows a registration form with empty Name and Email fields]
404
404
 
405
405
  **Your response:**
406
- <thought>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I'll break this down into sub-goals and start with the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</thought>
406
+ <planning>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I'll break this down into sub-goals and start with the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</planning>
407
407
  <update-plan-content>
408
408
  <sub-goal index="1" status="pending">Fill in the Name field with 'John'</sub-goal>
409
409
  <sub-goal index="2" status="pending">Fill in the Email field with 'john@example.com'</sub-goal>
@@ -433,7 +433,7 @@ Actions performed for current sub-goal:
433
433
  **Screenshot:** [Shows the form with Name field now focused/active]
434
434
 
435
435
  **Your response:**
436
- <thought>The Name field is now focused. I need to type 'John' into this field. Current sub-goal is running, will be completed after input.</thought>
436
+ <planning>The Name field is now focused. I need to type 'John' into this field. Current sub-goal is running, will be completed after input.</planning>
437
437
  <log>Typing 'John' into the Name field</log>
438
438
  <action-type>Input</action-type>
439
439
  <action-param-json>
@@ -459,7 +459,7 @@ Actions performed for current sub-goal:
459
459
  **Screenshot:** [Shows the form with Name field containing 'John']
460
460
 
461
461
  **Your response:**
462
- <thought>The Name field now shows 'John'. Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.</thought>
462
+ <planning>The Name field now shows 'John'. Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.</planning>
463
463
  <mark-sub-goal-done>
464
464
  <sub-goal index="1" status="finished" />
465
465
  </mark-sub-goal-done>
@@ -488,7 +488,7 @@ Actions performed for current sub-goal:
488
488
  **Screenshot:** [Shows the form with Name='John' and Email field focused]
489
489
 
490
490
  **Your response:**
491
- <thought>The Email field is now focused. I'll enter 'john@example.com'. After this, sub-goal 2 will be complete and my task will be done.</thought>
491
+ <planning>The Email field is now focused. I'll enter 'john@example.com'. After this, sub-goal 2 will be complete and my task will be done.</planning>
492
492
  <log>Typing email address into the Email field</log>
493
493
  <action-type>Input</action-type>
494
494
  <action-param-json>
@@ -514,7 +514,7 @@ Actions performed for current sub-goal:
514
514
  **Screenshot:** [Shows the form with Name='John' and Email='john@example.com']
515
515
 
516
516
  **Your response:**
517
- <thought>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.</thought>
517
+ <planning>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.</planning>
518
518
  <mark-sub-goal-done>
519
519
  <sub-goal index="2" status="finished" />
520
520
  <sub-goal index="3" status="finished" />
@@ -533,7 +533,7 @@ Below is an example of a multi-turn conversation for "fill out the registration
533
533
  **Screenshot:** [Shows a registration form with empty Name and Email fields]
534
534
 
535
535
  **Your response:**
536
- <thought>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I should start by clicking on the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</thought>
536
+ <planning>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I should start by clicking on the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</planning>
537
537
  <log>Click on the Name field to start filling the form</log>
538
538
  <action-type>Tap</action-type>
539
539
  <action-param-json>
@@ -550,7 +550,7 @@ The previous action has been executed, here is the latest screenshot. Please con
550
550
  **Screenshot:** [Shows the form with Name field now focused/active]
551
551
 
552
552
  **Your response:**
553
- <thought>The Name field is now focused. I need to type 'John' into this field. After this, I'll need to fill the Email field as well.</thought>
553
+ <planning>The Name field is now focused. I need to type 'John' into this field. After this, I'll need to fill the Email field as well.</planning>
554
554
  <log>Typing 'John' into the Name field</log>
555
555
  <action-type>Input</action-type>
556
556
  <action-param-json>
@@ -567,7 +567,7 @@ The previous action has been executed, here is the latest screenshot. Please con
567
567
  **Screenshot:** [Shows the form with Name field containing 'John']
568
568
 
569
569
  **Your response:**
570
- <thought>The Name field now shows 'John'. Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.</thought>
570
+ <planning>The Name field now shows 'John'. Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.</planning>
571
571
  <log>Moving to the Email field</log>
572
572
  <action-type>Tap</action-type>
573
573
  <action-param-json>
@@ -584,7 +584,7 @@ The previous action has been executed, here is the latest screenshot. Please con
584
584
  **Screenshot:** [Shows the form with Name='John' and Email field focused]
585
585
 
586
586
  **Your response:**
587
- <thought>The Email field is now focused. I'll enter 'john@example.com'. After this, both required fields will be filled and my task will be complete.</thought>
587
+ <planning>The Email field is now focused. I'll enter 'john@example.com'. After this, both required fields will be filled and my task will be complete.</planning>
588
588
  <log>Typing email address into the Email field</log>
589
589
  <action-type>Input</action-type>
590
590
  <action-param-json>
@@ -601,7 +601,7 @@ The previous action has been executed, here is the latest screenshot. Please con
601
601
  **Screenshot:** [Shows the form with Name='John' and Email='john@example.com']
602
602
 
603
603
  **Your response:**
604
- <thought>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.</thought>
604
+ <planning>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.</planning>
605
605
  <complete success="true">john@example.com</complete>
606
606
  `}`;
607
607
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/prompt/llm-planning.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/prompt/llm-planning.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { findAllMidsceneLocatorField } from '@/common';\nimport type { DeviceAction } from '@/types';\nimport { getPreferredLanguage } from '@midscene/shared/env';\nimport {\n getZodDescription,\n getZodTypeName,\n} from '@midscene/shared/zod-schema-utils';\nimport type { z } from 'zod';\nimport { planningModelFamilyRequiredForLocateMessage } from '../errors';\nimport type { LocateResultPromptSpec } from '../shared/model-locate-result';\nimport { locateGroundingRules } from './locate-grounding-rules';\nimport { locateParamExample } from './locate-param-example';\n\nconst locateParamSchemaDescription = (promptSpec?: LocateResultPromptSpec) => {\n if (promptSpec) {\n return `{${promptSpec.resultKey}: ${promptSpec.resultValueSchema}, prompt: string } // ${promptSpec.resultValueDescription}`;\n }\n return '{ prompt: string /* description of the target element */ }';\n};\n\nconst OBSERVE_STEP_NOTES = [\n '### 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].join('\\n');\n\nconst MEMORY_STEP_NOTES = [\n 'Use `<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 '',\n 'Examples:',\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].join('\\n');\n\nconst RUN_ADB_SHELL_ACTION_GUIDANCE =\n \"- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action.\";\n\nconst buildActionStepNotes = (actionList: string) =>\n [\n '### Action Guidelines',\n '',\n ...(actionList.includes('RunAdbShell')\n ? [RUN_ADB_SHELL_ACTION_GUIDANCE]\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 ].join('\\n');\n\n/**\n * Find ZodDefault in the wrapper chain and return its default value\n */\nconst findDefaultValue = (field: unknown): any | undefined => {\n let current = field;\n const visited = new Set<unknown>();\n\n while (current && !visited.has(current)) {\n visited.add(current);\n const currentWithDef = current as {\n _def?: {\n typeName?: string;\n defaultValue?: () => any;\n innerType?: unknown;\n };\n };\n\n if (!currentWithDef._def?.typeName) break;\n\n if (currentWithDef._def.typeName === 'ZodDefault') {\n return currentWithDef._def.defaultValue?.();\n }\n\n // Continue unwrapping if it's a wrapper type\n if (\n currentWithDef._def.typeName === 'ZodOptional' ||\n currentWithDef._def.typeName === 'ZodNullable'\n ) {\n current = currentWithDef._def.innerType;\n } else {\n break;\n }\n }\n\n return undefined;\n};\n\n/**\n * Inject model locate results into locate fields of a sample object.\n * Walks the sample and for any locate field (identified by paramSchema),\n * adds a fake locate result when includeLocateInPlanning is true.\n */\nconst injectLocateResultIntoSample = (\n sample: Record<string, any>,\n locateFields: string[],\n promptSpec: LocateResultPromptSpec,\n): Record<string, any> => {\n const resultKey = promptSpec.resultKey;\n const sampleResults = promptSpec.exampleValues;\n const result = { ...sample };\n let sampleResultIndex = 0;\n for (const field of locateFields) {\n if (\n result[field] &&\n typeof result[field] === 'object' &&\n result[field].prompt\n ) {\n result[field] = {\n ...result[field],\n [resultKey]: sampleResults[sampleResultIndex % sampleResults.length],\n };\n sampleResultIndex++;\n }\n }\n return result;\n};\n\nexport const descriptionForAction = (\n action: DeviceAction<any>,\n locateParamTypeDescription: string,\n includeLocateInPlanning = false,\n locatePromptSpec?: LocateResultPromptSpec,\n) => {\n const tab = ' ';\n const fields: string[] = [];\n\n // Add the action type field\n fields.push(`- type: \"${action.name}\"`);\n\n // Handle paramSchema if it exists\n if (action.paramSchema) {\n const paramLines: string[] = [];\n\n // Check if paramSchema is a ZodObject with shape\n const schema = action.paramSchema as {\n _def?: { typeName?: string };\n shape?: Record<string, unknown>;\n };\n const isZodObject = schema._def?.typeName === 'ZodObject';\n\n if (isZodObject && schema.shape) {\n // Original logic for ZodObject schemas\n const shape = schema.shape;\n\n for (const [key, field] of Object.entries(shape)) {\n if (field && typeof field === 'object') {\n // Check if field is optional\n const isOptional =\n typeof (field as { isOptional?: () => boolean }).isOptional ===\n 'function' &&\n (field as { isOptional: () => boolean }).isOptional();\n const keyWithOptional = isOptional ? `${key}?` : key;\n\n // Get the type name using extracted helper\n const typeName = getZodTypeName(field, locateParamTypeDescription);\n\n // Get description using extracted helper\n const description = getZodDescription(field as z.ZodTypeAny);\n\n // Check if field has a default value by searching the wrapper chain\n const defaultValue = findDefaultValue(field);\n const hasDefault = defaultValue !== undefined;\n\n // Build param line for this field\n let paramLine = `${keyWithOptional}: ${typeName}`;\n const comments: string[] = [];\n if (description) {\n comments.push(description);\n }\n if (hasDefault) {\n const defaultStr =\n typeof defaultValue === 'string'\n ? `\"${defaultValue}\"`\n : JSON.stringify(defaultValue);\n comments.push(`default: ${defaultStr}`);\n }\n if (comments.length > 0) {\n paramLine += ` // ${comments.join(', ')}`;\n }\n\n paramLines.push(paramLine);\n }\n }\n\n // Add the param section to fields if there are paramLines\n if (paramLines.length > 0) {\n fields.push('- param:');\n paramLines.forEach((line) => {\n fields.push(` - ${line}`);\n });\n }\n } else {\n // Handle non-object schemas (string, number, etc.)\n const typeName = getZodTypeName(schema);\n const description = getZodDescription(schema as z.ZodTypeAny);\n\n // For simple types, indicate that param should be the direct value, not an object\n let paramDescription = `- param: ${typeName}`;\n if (description) {\n paramDescription += ` // ${description}`;\n }\n paramDescription += ' (pass the value directly, not as an object)';\n\n fields.push(paramDescription);\n }\n }\n\n // Render sample if provided, using the same XML tag format as the real output\n if (action.sample && typeof action.sample === 'object') {\n const locateFields = findAllMidsceneLocatorField(action.paramSchema);\n const sampleWithLocateResult =\n includeLocateInPlanning && locatePromptSpec\n ? injectLocateResultIntoSample(\n action.sample,\n locateFields,\n locatePromptSpec,\n )\n : action.sample;\n const sampleStr = `- sample:\\n${tab}${tab}<action-type>${action.name}</action-type>\\n${tab}${tab}<action-param-json>\\n${tab}${tab}${JSON.stringify(sampleWithLocateResult, null, 2).replace(/\\n/g, `\\n${tab}${tab}`)}\\n${tab}${tab}</action-param-json>`;\n fields.push(sampleStr);\n }\n\n return `- ${action.name}, ${action.description || 'No description provided'}\n${tab}${fields.join(`\\n${tab}`)}\n`.trim();\n};\n\nexport async function systemPromptToTaskPlanning({\n actionSpace,\n locatePromptSpec,\n includeLocateInPlanning,\n includeThought,\n includeSubGoals,\n}: {\n actionSpace: DeviceAction<any>[];\n locatePromptSpec?: LocateResultPromptSpec;\n includeLocateInPlanning: boolean;\n includeThought?: boolean;\n includeSubGoals?: boolean;\n}) {\n const preferredLanguage = getPreferredLanguage();\n\n if (includeLocateInPlanning && !locatePromptSpec) {\n throw new Error(planningModelFamilyRequiredForLocateMessage());\n }\n\n const actionDescriptionList = actionSpace.map((action) => {\n return descriptionForAction(\n action,\n locateParamSchemaDescription(\n includeLocateInPlanning ? locatePromptSpec : undefined,\n ),\n includeLocateInPlanning,\n locatePromptSpec,\n );\n });\n const actionList = actionDescriptionList.join('\\n');\n const actionStepNotes = buildActionStepNotes(actionList);\n\n const shouldIncludeThought = includeThought ?? true;\n const shouldIncludeSubGoals = includeSubGoals ?? false;\n\n const locateExample = (prompt: string, exampleValueIndex: number) =>\n locateParamExample(\n prompt,\n includeLocateInPlanning ? locatePromptSpec : undefined,\n locatePromptSpec?.exampleValues[exampleValueIndex] ??\n locatePromptSpec?.exampleValues[0],\n );\n const locateExample1 = locateExample(\n 'Add to cart button for Sauce Labs Backpack',\n 1,\n );\n const locateNameField = locateExample(\n 'Name input field in the registration form',\n 2,\n );\n const locateEmailField = locateExample(\n 'Email input field in the registration form',\n 3,\n );\n\n const thoughtTag = (content: string) =>\n shouldIncludeThought ? `<thought>${content}</thought>\\n` : '';\n\n // Sub-goals related content - only included when shouldIncludeSubGoals is true\n const step1Title = shouldIncludeSubGoals\n ? '## Step 1: Observe and Plan (related tags: <thought>, <update-plan-content>, <mark-sub-goal-done>)'\n : '## Step 1: Observe (related tags: <thought>)';\n\n const step1Description = shouldIncludeSubGoals\n ? \"First, observe the current screenshot and previous logs, 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 : 'First, observe the current screenshot and previous logs to understand the current state.';\n\n const explicitInstructionRule = `CRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: \"fill out the form\" means only fill fields, do NOT submit; \"click the button\" means only click, do NOT wait for page load or verify results; \"type 'hello'\" means only type, do NOT press Enter.`;\n\n const thoughtTagDescription = shouldIncludeSubGoals\n ? `REQUIRED: You MUST always output the <thought> tag. Never skip it.\n\nInclude your thought process in the <thought> tag. It should answer: 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? Write your thoughts naturally without numbering or section headers.\n\n${explicitInstructionRule}`\n : `REQUIRED: You MUST always output the <thought> tag. Never skip it.\n\nInclude your thought process in the <thought> tag. It should answer: What is the current state based on the screenshot? What should be the next action? Write your thoughts naturally without numbering or section headers.\n\n${explicitInstructionRule}`;\n\n const subGoalTags = shouldIncludeSubGoals\n ? `\n\n* <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<thought>...</thought>\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\n // Step numbering adjusts based on whether sub-goals are included\n // When includeSubGoals=false, memory step is skipped\n const memoryStepNumber = 2; // Only used when shouldIncludeSubGoals is true\n const checkGoalStepNumber = shouldIncludeSubGoals ? 3 : 2;\n const actionStepNumber = shouldIncludeSubGoals ? 4 : 3;\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${step1Title}\n\n${step1Description}\n${shouldIncludeSubGoals ? `\\n${OBSERVE_STEP_NOTES}\\n` : ''}\n* <thought> tag (REQUIRED)\n\n${thoughtTagDescription}\n${subGoalTags}\n${\n shouldIncludeSubGoals\n ? `\n## Step ${memoryStepNumber}: Memory Data from Current Screenshot (related tags: <memory>)\n\n${MEMORY_STEP_NOTES}\n\nDon't use this tag if no information needs to be preserved.\n`\n : ''\n}\n## Step ${checkGoalStepNumber}: ${shouldIncludeSubGoals ? 'Check if Goal is Accomplished' : 'Check if the Instruction is Fulfilled'} (related tags: <complete>)\n\n${shouldIncludeSubGoals ? 'Based on the current screenshot and the status of all sub-goals, determine' : 'Determine'} if the entire task is completed.\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 \"${shouldIncludeSubGoals ? 'goal accomplished' : 'instruction fulfilled'}\" means:**\n- The ${shouldIncludeSubGoals ? '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\" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} when all fields are filled. Do NOT submit the form.\n- \"click the login button\" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} once clicked. Do NOT wait for page load or verify login success.\n- \"type 'hello' in the search box\" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} when 'hello' is typed. Do NOT press Enter or trigger search.\n- \"select the first item\" → ${shouldIncludeSubGoals ? '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 ${shouldIncludeSubGoals ? '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 !shouldIncludeSubGoals\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}\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. ${shouldIncludeSubGoals ? '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 ${shouldIncludeSubGoals ? '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 <action-type> or <action-param-json>. The task ends here.\n\n## Step ${actionStepNumber}: Determine Next Action (related tags: <log>, <action-type>, <action-param-json>, <error>)\n\nONLY if the task is not complete: Think what the next action is according to the current screenshot${shouldIncludeSubGoals ? ' 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${actionStepNotes}\n\n${\n includeLocateInPlanning\n ? `${locateGroundingRules()}\n\n`\n : ''\n}### Supporting actions list\n\n${actionList}\n\n### 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- Use the <action-type> and <action-param-json> tags to output the action to be executed.\n- The <action-type> MUST be one of the supporting actions. 'complete' is NOT a valid action-type.\n- Parameter names are strict. Use EXACTLY the field names listed for the selected action. Do NOT invent alias fields. If an action has a \"sample\" in its description, follow that structure.\nFor example:\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateExample1}\n}\n</action-param-json>\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 <action-type> or <action-param-json> if there is no action to do.\n\n## Return Format\n\nReturn in XML format following this decision flow:\n\n**Always include (REQUIRED):**\n<!-- Step 1: Observe${shouldIncludeSubGoals ? ' and Plan' : ''} -->\n<thought>Your thought process here. NEVER skip this tag.</thought>\n${\n shouldIncludeSubGoals\n ? `\n<!-- 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 : ''\n}${\n shouldIncludeSubGoals\n ? `\n<!-- Step ${memoryStepNumber}: Memory data from current screenshot if needed -->\n<memory>...</memory>\n`\n : ''\n}\n**Then choose ONE of the following paths:**\n\n**Path A: If the ${shouldIncludeSubGoals ? 'goal is accomplished' : 'instruction is fulfilled'} or failed (Step ${checkGoalStepNumber})**\n<complete success=\"true|false\">...</complete>\n\n**Path B: If the ${shouldIncludeSubGoals ? 'goal is NOT complete' : 'instruction is NOT fulfilled'} yet (Step ${actionStepNumber})**\n<!-- Determine next action -->\n<log>...</log>\n<action-type>...</action-type>\n<action-param-json>...</action-param-json>\n\n<!-- OR if there's an error -->\n<error>...</error>\n${\n shouldIncludeSubGoals\n ? `\n## Multi-turn Conversation Example\n\nBelow is an example of a multi-turn conversation for \"fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address\":\n\n### Turn 1 - Initial instruction\n\n**User message:**\n<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>\n\n**Screenshot:** [Shows a registration form with empty Name and Email fields]\n\n**Your response:**\n<thought>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I'll break this down into sub-goals and start with the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</thought>\n<update-plan-content>\n <sub-goal index=\"1\" status=\"pending\">Fill in the Name field with 'John'</sub-goal>\n <sub-goal index=\"2\" status=\"pending\">Fill in the Email field with 'john@example.com'</sub-goal>\n <sub-goal index=\"3\" status=\"pending\">Return the filled email address</sub-goal>\n</update-plan-content>\n<log>Click on the Name field to start filling the form</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateNameField}\n}\n</action-param-json>\n\n### Turn 2 - After clicking Name field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (running)\n2. Fill in the Email field with 'john@example.com' (pending)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Name field with 'John'\nActions performed for current sub-goal:\n- Click on the Name field to start filling the form\n\n**Screenshot:** [Shows the form with Name field now focused/active]\n\n**Your response:**\n<thought>The Name field is now focused. I need to type 'John' into this field. Current sub-goal is running, will be completed after input.</thought>\n<log>Typing 'John' into the Name field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"John\"\n}\n</action-param-json>\n\n### Turn 3 - After entering name\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (running)\n2. Fill in the Email field with 'john@example.com' (pending)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Name field with 'John'\nActions performed for current sub-goal:\n- Click on the Name field to start filling the form\n- Typing 'John' into the Name field\n\n**Screenshot:** [Shows the form with Name field containing 'John']\n\n**Your response:**\n<thought>The Name field now shows 'John'. Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.</thought>\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n<memory>Name field has been filled with 'John'</memory>\n<log>Moving to the Email field</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateEmailField}\n}\n</action-param-json>\n\n### Turn 4 - After clicking Email field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (finished)\n2. Fill in the Email field with 'john@example.com' (running)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Email field with 'john@example.com'\nActions performed for current sub-goal:\n- Moving to the Email field\n\n**Screenshot:** [Shows the form with Name='John' and Email field focused]\n\n**Your response:**\n<thought>The Email field is now focused. I'll enter 'john@example.com'. After this, sub-goal 2 will be complete and my task will be done.</thought>\n<log>Typing email address into the Email field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"john@example.com\"\n}\n</action-param-json>\n\n### Turn 5 - After entering email (Goal accomplished)\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (finished)\n2. Fill in the Email field with 'john@example.com' (running)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Email field with 'john@example.com'\nActions performed for current sub-goal:\n- Moving to the Email field\n- Typing email address into the Email field\n\n**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']\n\n**Your response:**\n<thought>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.</thought>\n<mark-sub-goal-done>\n <sub-goal index=\"2\" status=\"finished\" />\n <sub-goal index=\"3\" status=\"finished\" />\n</mark-sub-goal-done>\n<complete success=\"true\">john@example.com</complete>\n`\n : `\n## Multi-turn Conversation Example\n\nBelow is an example of a multi-turn conversation for \"fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address\":\n\n### Turn 1 - Initial instruction\n\n**User message:**\n<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>\n\n**Screenshot:** [Shows a registration form with empty Name and Email fields]\n\n**Your response:**\n<thought>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I should start by clicking on the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</thought>\n<log>Click on the Name field to start filling the form</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateNameField}\n}\n</action-param-json>\n\n### Turn 2 - After clicking Name field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name field now focused/active]\n\n**Your response:**\n<thought>The Name field is now focused. I need to type 'John' into this field. After this, I'll need to fill the Email field as well.</thought>\n<log>Typing 'John' into the Name field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"John\"\n}\n</action-param-json>\n\n### Turn 3 - After entering name\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name field containing 'John']\n\n**Your response:**\n<thought>The Name field now shows 'John'. Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.</thought>\n<log>Moving to the Email field</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateEmailField}\n}\n</action-param-json>\n\n### Turn 4 - After clicking Email field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name='John' and Email field focused]\n\n**Your response:**\n<thought>The Email field is now focused. I'll enter 'john@example.com'. After this, both required fields will be filled and my task will be complete.</thought>\n<log>Typing email address into the Email field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"john@example.com\"\n}\n</action-param-json>\n\n### Turn 5 - After entering email (Instruction fulfilled)\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']\n\n**Your response:**\n<thought>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.</thought>\n<complete success=\"true\">john@example.com</complete>\n`\n}`;\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","locateParamSchemaDescription","promptSpec","OBSERVE_STEP_NOTES","MEMORY_STEP_NOTES","RUN_ADB_SHELL_ACTION_GUIDANCE","buildActionStepNotes","actionList","findDefaultValue","field","current","visited","Set","currentWithDef","injectLocateResultIntoSample","sample","locateFields","resultKey","sampleResults","result","sampleResultIndex","descriptionForAction","action","locateParamTypeDescription","includeLocateInPlanning","locatePromptSpec","tab","fields","paramLines","schema","isZodObject","shape","isOptional","keyWithOptional","typeName","getZodTypeName","description","getZodDescription","defaultValue","hasDefault","undefined","paramLine","comments","defaultStr","JSON","line","paramDescription","findAllMidsceneLocatorField","sampleWithLocateResult","sampleStr","systemPromptToTaskPlanning","actionSpace","includeThought","includeSubGoals","preferredLanguage","getPreferredLanguage","Error","planningModelFamilyRequiredForLocateMessage","actionDescriptionList","actionStepNotes","shouldIncludeSubGoals","locateExample","prompt","exampleValueIndex","locateParamExample","locateExample1","locateNameField","locateEmailField","step1Title","step1Description","explicitInstructionRule","thoughtTagDescription","subGoalTags","memoryStepNumber","checkGoalStepNumber","actionStepNumber","locateGroundingRules"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;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,WAAW;;;;;;QAML,EAAE+C,kBAAkB;;;;;;;;;;;;;;;;;;;;YAoBhB,EAAEW,eAAe;;;;;;;;;;;;;;;;;;;;oBAoBT,EAAEL,wBAAwB,cAAc,GAAG;;AAE/D,EACEA,wBACI,CAAC;;;;;;;;AAQP,CAAC,GACK,KAEJA,wBACI,CAAC;UACG,EAAEa,iBAAiB;;AAE7B,CAAC,GACK,GACL;;;iBAGgB,EAAEb,wBAAwB,yBAAyB,2BAA2B,iBAAiB,EAAEc,oBAAoB;;;iBAGrH,EAAEd,wBAAwB,yBAAyB,+BAA+B,WAAW,EAAEe,iBAAiB;;;;;;;;AAQjI,EACEf,wBACI,CAAC;;;;;;;;;;;;;;;;;;;;;;;YAuBK,EAAEM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAuDlB,EAAEC,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoD/B,CAAC,GACK,CAAC;;;;;;;;;;;;;;;;;;YAkBK,EAAED,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAkClB,EAAEC,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B/B,CAAC,EACC;AACF"}
1
+ {"version":3,"file":"ai-model/prompt/llm-planning.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/prompt/llm-planning.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { findAllMidsceneLocatorField } from '@/common';\nimport type { DeviceAction } from '@/types';\nimport { getPreferredLanguage } from '@midscene/shared/env';\nimport {\n getZodDescription,\n getZodTypeName,\n} from '@midscene/shared/zod-schema-utils';\nimport type { z } from 'zod';\nimport { planningModelFamilyRequiredForLocateMessage } from '../errors';\nimport type { LocateResultPromptSpec } from '../shared/model-locate-result';\nimport { locateGroundingRules } from './locate-grounding-rules';\nimport { locateParamExample } from './locate-param-example';\n\nconst locateParamSchemaDescription = (promptSpec?: LocateResultPromptSpec) => {\n if (promptSpec) {\n return `{${promptSpec.resultKey}: ${promptSpec.resultValueSchema}, prompt: string } // ${promptSpec.resultValueDescription}`;\n }\n return '{ prompt: string /* description of the target element */ }';\n};\n\nconst OBSERVE_STEP_NOTES = [\n '### 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].join('\\n');\n\nconst MEMORY_STEP_NOTES = [\n 'Use `<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 '',\n 'Examples:',\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].join('\\n');\n\nconst RUN_ADB_SHELL_ACTION_GUIDANCE =\n \"- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action.\";\n\nconst buildActionStepNotes = (actionList: string) =>\n [\n '### Action Guidelines',\n '',\n ...(actionList.includes('RunAdbShell')\n ? [RUN_ADB_SHELL_ACTION_GUIDANCE]\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 ].join('\\n');\n\n/**\n * Find ZodDefault in the wrapper chain and return its default value\n */\nconst findDefaultValue = (field: unknown): any | undefined => {\n let current = field;\n const visited = new Set<unknown>();\n\n while (current && !visited.has(current)) {\n visited.add(current);\n const currentWithDef = current as {\n _def?: {\n typeName?: string;\n defaultValue?: () => any;\n innerType?: unknown;\n };\n };\n\n if (!currentWithDef._def?.typeName) break;\n\n if (currentWithDef._def.typeName === 'ZodDefault') {\n return currentWithDef._def.defaultValue?.();\n }\n\n // Continue unwrapping if it's a wrapper type\n if (\n currentWithDef._def.typeName === 'ZodOptional' ||\n currentWithDef._def.typeName === 'ZodNullable'\n ) {\n current = currentWithDef._def.innerType;\n } else {\n break;\n }\n }\n\n return undefined;\n};\n\n/**\n * Inject model locate results into locate fields of a sample object.\n * Walks the sample and for any locate field (identified by paramSchema),\n * adds a fake locate result when includeLocateInPlanning is true.\n */\nconst injectLocateResultIntoSample = (\n sample: Record<string, any>,\n locateFields: string[],\n promptSpec: LocateResultPromptSpec,\n): Record<string, any> => {\n const resultKey = promptSpec.resultKey;\n const sampleResults = promptSpec.exampleValues;\n const result = { ...sample };\n let sampleResultIndex = 0;\n for (const field of locateFields) {\n if (\n result[field] &&\n typeof result[field] === 'object' &&\n result[field].prompt\n ) {\n result[field] = {\n ...result[field],\n [resultKey]: sampleResults[sampleResultIndex % sampleResults.length],\n };\n sampleResultIndex++;\n }\n }\n return result;\n};\n\nexport const descriptionForAction = (\n action: DeviceAction<any>,\n locateParamTypeDescription: string,\n includeLocateInPlanning = false,\n locatePromptSpec?: LocateResultPromptSpec,\n) => {\n const tab = ' ';\n const fields: string[] = [];\n\n // Add the action type field\n fields.push(`- type: \"${action.name}\"`);\n\n // Handle paramSchema if it exists\n if (action.paramSchema) {\n const paramLines: string[] = [];\n\n // Check if paramSchema is a ZodObject with shape\n const schema = action.paramSchema as {\n _def?: { typeName?: string };\n shape?: Record<string, unknown>;\n };\n const isZodObject = schema._def?.typeName === 'ZodObject';\n\n if (isZodObject && schema.shape) {\n // Original logic for ZodObject schemas\n const shape = schema.shape;\n\n for (const [key, field] of Object.entries(shape)) {\n if (field && typeof field === 'object') {\n // Check if field is optional\n const isOptional =\n typeof (field as { isOptional?: () => boolean }).isOptional ===\n 'function' &&\n (field as { isOptional: () => boolean }).isOptional();\n const keyWithOptional = isOptional ? `${key}?` : key;\n\n // Get the type name using extracted helper\n const typeName = getZodTypeName(field, locateParamTypeDescription);\n\n // Get description using extracted helper\n const description = getZodDescription(field as z.ZodTypeAny);\n\n // Check if field has a default value by searching the wrapper chain\n const defaultValue = findDefaultValue(field);\n const hasDefault = defaultValue !== undefined;\n\n // Build param line for this field\n let paramLine = `${keyWithOptional}: ${typeName}`;\n const comments: string[] = [];\n if (description) {\n comments.push(description);\n }\n if (hasDefault) {\n const defaultStr =\n typeof defaultValue === 'string'\n ? `\"${defaultValue}\"`\n : JSON.stringify(defaultValue);\n comments.push(`default: ${defaultStr}`);\n }\n if (comments.length > 0) {\n paramLine += ` // ${comments.join(', ')}`;\n }\n\n paramLines.push(paramLine);\n }\n }\n\n // Add the param section to fields if there are paramLines\n if (paramLines.length > 0) {\n fields.push('- param:');\n paramLines.forEach((line) => {\n fields.push(` - ${line}`);\n });\n }\n } else {\n // Handle non-object schemas (string, number, etc.)\n const typeName = getZodTypeName(schema);\n const description = getZodDescription(schema as z.ZodTypeAny);\n\n // For simple types, indicate that param should be the direct value, not an object\n let paramDescription = `- param: ${typeName}`;\n if (description) {\n paramDescription += ` // ${description}`;\n }\n paramDescription += ' (pass the value directly, not as an object)';\n\n fields.push(paramDescription);\n }\n }\n\n // Render sample if provided, using the same XML tag format as the real output\n if (action.sample && typeof action.sample === 'object') {\n const locateFields = findAllMidsceneLocatorField(action.paramSchema);\n const sampleWithLocateResult =\n includeLocateInPlanning && locatePromptSpec\n ? injectLocateResultIntoSample(\n action.sample,\n locateFields,\n locatePromptSpec,\n )\n : action.sample;\n const sampleStr = `- sample:\\n${tab}${tab}<action-type>${action.name}</action-type>\\n${tab}${tab}<action-param-json>\\n${tab}${tab}${JSON.stringify(sampleWithLocateResult, null, 2).replace(/\\n/g, `\\n${tab}${tab}`)}\\n${tab}${tab}</action-param-json>`;\n fields.push(sampleStr);\n }\n\n return `- ${action.name}, ${action.description || 'No description provided'}\n${tab}${fields.join(`\\n${tab}`)}\n`.trim();\n};\n\nexport async function systemPromptToTaskPlanning({\n actionSpace,\n locatePromptSpec,\n includeLocateInPlanning,\n includeThought,\n includeSubGoals,\n}: {\n actionSpace: DeviceAction<any>[];\n locatePromptSpec?: LocateResultPromptSpec;\n includeLocateInPlanning: boolean;\n includeThought?: boolean;\n includeSubGoals?: boolean;\n}) {\n const preferredLanguage = getPreferredLanguage();\n\n if (includeLocateInPlanning && !locatePromptSpec) {\n throw new Error(planningModelFamilyRequiredForLocateMessage());\n }\n\n const actionDescriptionList = actionSpace.map((action) => {\n return descriptionForAction(\n action,\n locateParamSchemaDescription(\n includeLocateInPlanning ? locatePromptSpec : undefined,\n ),\n includeLocateInPlanning,\n locatePromptSpec,\n );\n });\n const actionList = actionDescriptionList.join('\\n');\n const actionStepNotes = buildActionStepNotes(actionList);\n\n const shouldIncludeThought = includeThought ?? true;\n const shouldIncludeSubGoals = includeSubGoals ?? false;\n\n const locateExample = (prompt: string, exampleValueIndex: number) =>\n locateParamExample(\n prompt,\n includeLocateInPlanning ? locatePromptSpec : undefined,\n locatePromptSpec?.exampleValues[exampleValueIndex] ??\n locatePromptSpec?.exampleValues[0],\n );\n const locateExample1 = locateExample(\n 'Add to cart button for Sauce Labs Backpack',\n 1,\n );\n const locateNameField = locateExample(\n 'Name input field in the registration form',\n 2,\n );\n const locateEmailField = locateExample(\n 'Email input field in the registration form',\n 3,\n );\n\n const planningTag = (content: string) =>\n shouldIncludeThought ? `<planning>${content}</planning>\\n` : '';\n\n // Sub-goals related content - only included when shouldIncludeSubGoals is true\n const step1Title = shouldIncludeSubGoals\n ? '## Step 1: Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)'\n : '## Step 1: Observe (related tags: <planning>)';\n\n const step1Description = shouldIncludeSubGoals\n ? \"First, observe the current screenshot and previous logs, 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 : 'First, observe the current screenshot and previous logs to understand the current state.';\n\n const explicitInstructionRule = `CRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: \"fill out the form\" means only fill fields, do NOT submit; \"click the button\" means only click, do NOT wait for page load or verify results; \"type 'hello'\" means only type, do NOT press Enter.`;\n\n const planningTagDescription = shouldIncludeSubGoals\n ? `REQUIRED: You MUST always output the <planning> tag. Never skip it.\n\nInclude your planning details in the <planning> tag. It should answer: 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? Write it naturally without numbering or section headers.\n\n${explicitInstructionRule}`\n : `REQUIRED: You MUST always output the <planning> tag. Never skip it.\n\nInclude your planning details in the <planning> tag. It should answer: What is the current state based on the screenshot? What should be the next action? Write it naturally without numbering or section headers.\n\n${explicitInstructionRule}`;\n\n const subGoalTags = shouldIncludeSubGoals\n ? `\n\n* <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\n // Step numbering adjusts based on whether sub-goals are included\n // When includeSubGoals=false, memory step is skipped\n const memoryStepNumber = 2; // Only used when shouldIncludeSubGoals is true\n const checkGoalStepNumber = shouldIncludeSubGoals ? 3 : 2;\n const actionStepNumber = shouldIncludeSubGoals ? 4 : 3;\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${step1Title}\n\n${step1Description}\n${shouldIncludeSubGoals ? `\\n${OBSERVE_STEP_NOTES}\\n` : ''}\n* <planning> tag (REQUIRED)\n\n${planningTagDescription}\n${subGoalTags}\n${\n shouldIncludeSubGoals\n ? `\n## Step ${memoryStepNumber}: Memory Data from Current Screenshot (related tags: <memory>)\n\n${MEMORY_STEP_NOTES}\n\nDon't use this tag if no information needs to be preserved.\n`\n : ''\n}\n## Step ${checkGoalStepNumber}: ${shouldIncludeSubGoals ? 'Check if Goal is Accomplished' : 'Check if the Instruction is Fulfilled'} (related tags: <complete>)\n\n${shouldIncludeSubGoals ? 'Based on the current screenshot and the status of all sub-goals, determine' : 'Determine'} if the entire task is completed.\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 \"${shouldIncludeSubGoals ? 'goal accomplished' : 'instruction fulfilled'}\" means:**\n- The ${shouldIncludeSubGoals ? '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\" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} when all fields are filled. Do NOT submit the form.\n- \"click the login button\" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} once clicked. Do NOT wait for page load or verify login success.\n- \"type 'hello' in the search box\" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} when 'hello' is typed. Do NOT press Enter or trigger search.\n- \"select the first item\" → ${shouldIncludeSubGoals ? '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 ${shouldIncludeSubGoals ? '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 !shouldIncludeSubGoals\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}\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. ${shouldIncludeSubGoals ? '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 ${shouldIncludeSubGoals ? '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 <action-type> or <action-param-json>. The task ends here.\n\n## Step ${actionStepNumber}: Determine Next Action (related tags: <log>, <action-type>, <action-param-json>, <error>)\n\nONLY if the task is not complete: Think what the next action is according to the current screenshot${shouldIncludeSubGoals ? ' 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${actionStepNotes}\n\n${\n includeLocateInPlanning\n ? `${locateGroundingRules()}\n\n`\n : ''\n}### Supporting actions list\n\n${actionList}\n\n### 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- Use the <action-type> and <action-param-json> tags to output the action to be executed.\n- The <action-type> MUST be one of the supporting actions. 'complete' is NOT a valid action-type.\n- Parameter names are strict. Use EXACTLY the field names listed for the selected action. Do NOT invent alias fields. If an action has a \"sample\" in its description, follow that structure.\nFor example:\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateExample1}\n}\n</action-param-json>\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 <action-type> or <action-param-json> if there is no action to do.\n\n## Return Format\n\nReturn in XML format following this decision flow:\n\n**Always include (REQUIRED):**\n<!-- Step 1: Observe${shouldIncludeSubGoals ? ' and Plan' : ''} -->\n<planning>Your planning details here. NEVER skip this tag.</planning>\n${\n shouldIncludeSubGoals\n ? `\n<!-- 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 : ''\n}${\n shouldIncludeSubGoals\n ? `\n<!-- Step ${memoryStepNumber}: Memory data from current screenshot if needed -->\n<memory>...</memory>\n`\n : ''\n}\n**Then choose ONE of the following paths:**\n\n**Path A: If the ${shouldIncludeSubGoals ? 'goal is accomplished' : 'instruction is fulfilled'} or failed (Step ${checkGoalStepNumber})**\n<complete success=\"true|false\">...</complete>\n\n**Path B: If the ${shouldIncludeSubGoals ? 'goal is NOT complete' : 'instruction is NOT fulfilled'} yet (Step ${actionStepNumber})**\n<!-- Determine next action -->\n<log>...</log>\n<action-type>...</action-type>\n<action-param-json>...</action-param-json>\n\n<!-- OR if there's an error -->\n<error>...</error>\n${\n shouldIncludeSubGoals\n ? `\n## Multi-turn Conversation Example\n\nBelow is an example of a multi-turn conversation for \"fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address\":\n\n### Turn 1 - Initial instruction\n\n**User message:**\n<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>\n\n**Screenshot:** [Shows a registration form with empty Name and Email fields]\n\n**Your response:**\n<planning>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I'll break this down into sub-goals and start with the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</planning>\n<update-plan-content>\n <sub-goal index=\"1\" status=\"pending\">Fill in the Name field with 'John'</sub-goal>\n <sub-goal index=\"2\" status=\"pending\">Fill in the Email field with 'john@example.com'</sub-goal>\n <sub-goal index=\"3\" status=\"pending\">Return the filled email address</sub-goal>\n</update-plan-content>\n<log>Click on the Name field to start filling the form</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateNameField}\n}\n</action-param-json>\n\n### Turn 2 - After clicking Name field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (running)\n2. Fill in the Email field with 'john@example.com' (pending)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Name field with 'John'\nActions performed for current sub-goal:\n- Click on the Name field to start filling the form\n\n**Screenshot:** [Shows the form with Name field now focused/active]\n\n**Your response:**\n<planning>The Name field is now focused. I need to type 'John' into this field. Current sub-goal is running, will be completed after input.</planning>\n<log>Typing 'John' into the Name field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"John\"\n}\n</action-param-json>\n\n### Turn 3 - After entering name\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (running)\n2. Fill in the Email field with 'john@example.com' (pending)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Name field with 'John'\nActions performed for current sub-goal:\n- Click on the Name field to start filling the form\n- Typing 'John' into the Name field\n\n**Screenshot:** [Shows the form with Name field containing 'John']\n\n**Your response:**\n<planning>The Name field now shows 'John'. Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.</planning>\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n<memory>Name field has been filled with 'John'</memory>\n<log>Moving to the Email field</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateEmailField}\n}\n</action-param-json>\n\n### Turn 4 - After clicking Email field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (finished)\n2. Fill in the Email field with 'john@example.com' (running)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Email field with 'john@example.com'\nActions performed for current sub-goal:\n- Moving to the Email field\n\n**Screenshot:** [Shows the form with Name='John' and Email field focused]\n\n**Your response:**\n<planning>The Email field is now focused. I'll enter 'john@example.com'. After this, sub-goal 2 will be complete and my task will be done.</planning>\n<log>Typing email address into the Email field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"john@example.com\"\n}\n</action-param-json>\n\n### Turn 5 - After entering email (Goal accomplished)\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\nSub-goals:\n1. Fill in the Name field with 'John' (finished)\n2. Fill in the Email field with 'john@example.com' (running)\n3. Return the filled email address (pending)\nCurrent sub-goal is: Fill in the Email field with 'john@example.com'\nActions performed for current sub-goal:\n- Moving to the Email field\n- Typing email address into the Email field\n\n**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']\n\n**Your response:**\n<planning>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.</planning>\n<mark-sub-goal-done>\n <sub-goal index=\"2\" status=\"finished\" />\n <sub-goal index=\"3\" status=\"finished\" />\n</mark-sub-goal-done>\n<complete success=\"true\">john@example.com</complete>\n`\n : `\n## Multi-turn Conversation Example\n\nBelow is an example of a multi-turn conversation for \"fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address\":\n\n### Turn 1 - Initial instruction\n\n**User message:**\n<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>\n\n**Screenshot:** [Shows a registration form with empty Name and Email fields]\n\n**Your response:**\n<planning>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I should start by clicking on the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</planning>\n<log>Click on the Name field to start filling the form</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateNameField}\n}\n</action-param-json>\n\n### Turn 2 - After clicking Name field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name field now focused/active]\n\n**Your response:**\n<planning>The Name field is now focused. I need to type 'John' into this field. After this, I'll need to fill the Email field as well.</planning>\n<log>Typing 'John' into the Name field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"John\"\n}\n</action-param-json>\n\n### Turn 3 - After entering name\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name field containing 'John']\n\n**Your response:**\n<planning>The Name field now shows 'John'. Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.</planning>\n<log>Moving to the Email field</log>\n<action-type>Tap</action-type>\n<action-param-json>\n{\n \"locate\": ${locateEmailField}\n}\n</action-param-json>\n\n### Turn 4 - After clicking Email field\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name='John' and Email field focused]\n\n**Your response:**\n<planning>The Email field is now focused. I'll enter 'john@example.com'. After this, both required fields will be filled and my task will be complete.</planning>\n<log>Typing email address into the Email field</log>\n<action-type>Input</action-type>\n<action-param-json>\n{\n \"value\": \"john@example.com\"\n}\n</action-param-json>\n\n### Turn 5 - After entering email (Instruction fulfilled)\n\n**User message:**\nThe previous action has been executed, here is the latest screenshot. Please continue according to the instruction.\n\n**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']\n\n**Your response:**\n<planning>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.</planning>\n<complete success=\"true\">john@example.com</complete>\n`\n}`;\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","locateParamSchemaDescription","promptSpec","OBSERVE_STEP_NOTES","MEMORY_STEP_NOTES","RUN_ADB_SHELL_ACTION_GUIDANCE","buildActionStepNotes","actionList","findDefaultValue","field","current","visited","Set","currentWithDef","injectLocateResultIntoSample","sample","locateFields","resultKey","sampleResults","result","sampleResultIndex","descriptionForAction","action","locateParamTypeDescription","includeLocateInPlanning","locatePromptSpec","tab","fields","paramLines","schema","isZodObject","shape","isOptional","keyWithOptional","typeName","getZodTypeName","description","getZodDescription","defaultValue","hasDefault","undefined","paramLine","comments","defaultStr","JSON","line","paramDescription","findAllMidsceneLocatorField","sampleWithLocateResult","sampleStr","systemPromptToTaskPlanning","actionSpace","includeThought","includeSubGoals","preferredLanguage","getPreferredLanguage","Error","planningModelFamilyRequiredForLocateMessage","actionDescriptionList","actionStepNotes","shouldIncludeSubGoals","locateExample","prompt","exampleValueIndex","locateParamExample","locateExample1","locateNameField","locateEmailField","step1Title","step1Description","explicitInstructionRule","planningTagDescription","subGoalTags","memoryStepNumber","checkGoalStepNumber","actionStepNumber","locateGroundingRules"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU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  function locateGroundingRules() {
30
30
  return `## Important Notes for Locating Elements:
31
- - When the user describes an element that contains text (such as buttons, input fields, dropdown options, radio buttons, etc.), you should locate ONLY the text region of that element, not the entire element boundary.
32
- - For example: If an input field is large (both wide and tall) with a placeholder text "Please enter your comment", you should locate only the area where the placeholder text appears, not the entire input field.
33
- - This principle applies to all text-containing elements: focus on the visible text region rather than the full element container.`;
31
+ - First identify the target primitive from the user's description, then locate that primitive only. Treat labels, owners, rows, columns, and surrounding text as context unless the description says they are the target.
32
+ - If the target itself is visible text, link text, status text, table cell text, or header text, return only the tight visible text region, not the entire control, row, sentence, or container.
33
+ - If a text or link target wraps across multiple lines, do not return one large box covering the whole wrapped text. Return a tight box around a distinctive visible segment of the target text; for CJK link labels, the first 2-4 visible characters are enough when unique.
34
+ - If the target is an input/select/filter field body, current value area, or blank field region, return that field/control body or value region. Do not retarget to a trailing search icon, dropdown arrow, clear button, or nearby table header.
35
+ - If the target is an icon, arrow, checkbox, radio, or accessory control, return only that glyph/control region. Do not return adjacent owner text.
36
+ - If the target is a tiny icon/control among adjacent similar icons, use the described local order or relative position within that group and return only that glyph/control.
37
+ - If the same text appears in multiple regions, obey the described owner region first, such as filter bar vs table header.`;
34
38
  }
35
39
  exports.locateGroundingRules = __webpack_exports__.locateGroundingRules;
36
40
  for(var __rspack_i in __webpack_exports__)if (-1 === [
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/prompt/locate-grounding-rules.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/prompt/locate-grounding-rules.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export function locateGroundingRules() {\n return `## Important Notes for Locating Elements:\n- When the user describes an element that contains text (such as buttons, input fields, dropdown options, radio buttons, etc.), you should locate ONLY the text region of that element, not the entire element boundary.\n- For example: If an input field is large (both wide and tall) with a placeholder text \"Please enter your comment\", you should locate only the area where the placeholder text appears, not the entire input field.\n- This principle applies to all text-containing elements: focus on the visible text region rather than the full element container.`;\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","locateGroundingRules"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;ACNO,SAASI;IACd,OAAO,CAAC;;;kIAGwH,CAAC;AACnI"}
1
+ {"version":3,"file":"ai-model/prompt/locate-grounding-rules.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/prompt/locate-grounding-rules.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export function locateGroundingRules() {\n return `## Important Notes for Locating Elements:\n- First identify the target primitive from the user's description, then locate that primitive only. Treat labels, owners, rows, columns, and surrounding text as context unless the description says they are the target.\n- If the target itself is visible text, link text, status text, table cell text, or header text, return only the tight visible text region, not the entire control, row, sentence, or container.\n- If a text or link target wraps across multiple lines, do not return one large box covering the whole wrapped text. Return a tight box around a distinctive visible segment of the target text; for CJK link labels, the first 2-4 visible characters are enough when unique.\n- If the target is an input/select/filter field body, current value area, or blank field region, return that field/control body or value region. Do not retarget to a trailing search icon, dropdown arrow, clear button, or nearby table header.\n- If the target is an icon, arrow, checkbox, radio, or accessory control, return only that glyph/control region. Do not return adjacent owner text.\n- If the target is a tiny icon/control among adjacent similar icons, use the described local order or relative position within that group and return only that glyph/control.\n- If the same text appears in multiple regions, obey the described owner region first, such as filter bar vs table header.`;\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","locateGroundingRules"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;ACNO,SAASI;IACd,OAAO,CAAC;;;;;;;0HAOgH,CAAC;AAC3H"}
@@ -24,10 +24,9 @@ var __webpack_require__ = {};
24
24
  var __webpack_exports__ = {};
25
25
  __webpack_require__.r(__webpack_exports__);
26
26
  __webpack_require__.d(__webpack_exports__, {
27
- verifyElementByServiceLocate: ()=>verifyElementByServiceLocate,
28
- verifyLocator: ()=>verifyLocator,
29
27
  describeElementAtPoint: ()=>describeElementAtPoint,
30
- verifyElementDescriptionAtPoint: ()=>verifyElementDescriptionAtPoint
28
+ verifyElementDescriptionAtPoint: ()=>verifyElementDescriptionAtPoint,
29
+ verifyLocator: ()=>verifyLocator
31
30
  });
32
31
  const utils_namespaceObject = require("@midscene/shared/utils");
33
32
  const utils_js_namespaceObject = require("./agent/utils.js");
@@ -80,6 +79,7 @@ const createScreenshotBoundLocatorContext = async (center, opt)=>{
80
79
  async function verifyLocator(runtime, prompt, locateOpt, expectCenter, verifyLocateOption) {
81
80
  return locateAndVerify(runtime, prompt, expectCenter, {
82
81
  centerDistanceThreshold: verifyLocateOption?.centerDistanceThreshold,
82
+ deepLocate: verifyLocateOption?.deepLocate,
83
83
  uiContext: locateOpt?.uiContext
84
84
  });
85
85
  }
@@ -101,25 +101,37 @@ async function describeElementAtPoint(runtime, center, opt) {
101
101
  let success = false;
102
102
  let retryCount = 0;
103
103
  let resultPrompt = '';
104
+ const autoRetryDeepDescribe = opt?.deepDescribe === void 0;
105
+ const autoRetryDeepLocate = opt?.deepLocate === void 0;
106
+ let deepDescribe = opt?.deepDescribe || false;
104
107
  let deepLocate = opt?.deepLocate || false;
105
108
  let verifyResult;
106
109
  let lastError;
107
110
  let failureStage;
108
111
  while(!success && retryCount < retryLimit){
109
- if (retryCount >= 2) deepLocate = true;
112
+ if (retryCount >= 1 && autoRetryDeepDescribe) deepDescribe = true;
113
+ if (retryCount >= 1 && autoRetryDeepLocate) deepLocate = true;
114
+ const describeModelRuntime = runtime.describeModelRuntime;
115
+ const locateModelRuntime = runtime.locateModelRuntime;
116
+ const retryRuntime = {
117
+ ...runtime,
118
+ describeModelRuntime,
119
+ locateModelRuntime
120
+ };
110
121
  const describeOpt = screenshotContext ? {
111
- deepLocate,
122
+ deepDescribe,
112
123
  context: screenshotContext
113
124
  } : {
114
- deepLocate
125
+ deepDescribe
115
126
  };
116
127
  let text;
117
128
  try {
118
- text = await runtime.service.describe(targetCenter, runtime.describeModelRuntime, describeOpt);
129
+ text = await retryRuntime.service.describe(targetCenter, retryRuntime.describeModelRuntime, describeOpt);
119
130
  } catch (error) {
120
131
  return {
121
132
  prompt: resultPrompt,
122
133
  deepLocate,
134
+ deepDescribe,
123
135
  verifyResult,
124
136
  success: false,
125
137
  error: errorMessage(error),
@@ -129,6 +141,7 @@ async function describeElementAtPoint(runtime, center, opt) {
129
141
  if (!text.description) return {
130
142
  prompt: resultPrompt,
131
143
  deepLocate,
144
+ deepDescribe,
132
145
  verifyResult,
133
146
  success: false,
134
147
  error: `failed to describe element at [${targetCenter}]`,
@@ -138,44 +151,50 @@ async function describeElementAtPoint(runtime, center, opt) {
138
151
  if (!verifyPrompt) {
139
152
  opt?.onProgress?.({
140
153
  prompt: resultPrompt,
154
+ deepDescribe,
141
155
  deepLocate
142
156
  });
143
157
  success = true;
144
158
  break;
145
159
  }
146
160
  try {
147
- verifyResult = await verifyLocator(runtime, resultPrompt, locateOpt, targetCenter, opt);
161
+ const candidateVerifyResult = await verifyLocator(retryRuntime, resultPrompt, locateOpt, targetCenter, {
162
+ ...opt,
163
+ deepLocate
164
+ });
148
165
  verifyResult = applyLocatorVerifyFn(opt?.locatorVerifyFn, {
149
166
  prompt: resultPrompt,
150
167
  expectCenter: targetCenter,
151
- deepLocate,
152
168
  retryCount,
153
- verifyResult
169
+ verifyResult: candidateVerifyResult
154
170
  });
155
171
  opt?.onProgress?.({
156
172
  prompt: resultPrompt,
173
+ deepDescribe,
157
174
  deepLocate,
158
175
  verifyResult
159
176
  });
160
- if (verifyResult.pass) success = true;
161
- else {
162
- lastError = void 0;
163
- failureStage = 'verify';
164
- retryCount++;
177
+ if (verifyResult.pass) {
178
+ success = true;
179
+ break;
165
180
  }
181
+ lastError = void 0;
182
+ failureStage = 'verify';
166
183
  } catch (error) {
167
184
  lastError = errorMessage(error);
168
185
  failureStage = 'verify';
169
186
  opt?.onProgress?.({
170
187
  prompt: resultPrompt,
188
+ deepDescribe,
171
189
  deepLocate
172
190
  });
173
- retryCount++;
174
191
  }
192
+ retryCount++;
175
193
  }
176
194
  return {
177
195
  prompt: resultPrompt,
178
196
  deepLocate,
197
+ deepDescribe,
179
198
  verifyResult,
180
199
  success,
181
200
  error: success || !verifyPrompt ? void 0 : lastError || 'describeElementAtPoint verify failed',
@@ -187,9 +206,6 @@ async function verifyElementDescriptionAtPoint(runtime, description, center, opt
187
206
  const { locateOpt, targetCenter } = await createScreenshotBoundLocatorContext(center, opt);
188
207
  return verifyLocator(runtime, description, locateOpt, targetCenter, opt);
189
208
  }
190
- async function verifyElementByServiceLocate(runtime, description, center, opt) {
191
- return locateAndVerify(runtime, description, center, opt);
192
- }
193
209
  async function locateAndVerify(runtime, description, center, opt) {
194
210
  (0, utils_namespaceObject.assert)(description?.trim(), "description must not be empty");
195
211
  const { screenshotContext, targetCenter } = await createScreenshotBoundLocatorContext(center, opt);
@@ -204,15 +220,14 @@ async function locateAndVerify(runtime, description, center, opt) {
204
220
  context
205
221
  } : {}, runtime.locateModelRuntime, opt?.abortSignal);
206
222
  (0, utils_namespaceObject.assert)(locateResult.element, `Element not found: ${description}`);
207
- return buildLocateValidatorResult(targetCenter, locateResult.element, opt);
223
+ const verifyResult = buildLocateValidatorResult(targetCenter, locateResult.element, opt);
224
+ return verifyResult;
208
225
  }
209
226
  exports.describeElementAtPoint = __webpack_exports__.describeElementAtPoint;
210
- exports.verifyElementByServiceLocate = __webpack_exports__.verifyElementByServiceLocate;
211
227
  exports.verifyElementDescriptionAtPoint = __webpack_exports__.verifyElementDescriptionAtPoint;
212
228
  exports.verifyLocator = __webpack_exports__.verifyLocator;
213
229
  for(var __rspack_i in __webpack_exports__)if (-1 === [
214
230
  "describeElementAtPoint",
215
- "verifyElementByServiceLocate",
216
231
  "verifyElementDescriptionAtPoint",
217
232
  "verifyLocator"
218
233
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];