@midscene/core 1.12.8-beta-20260916024015.0 → 1.12.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -153,7 +153,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
153
153
  return;
154
154
  }
155
155
  }
156
- const getMidsceneVersion = ()=>"1.12.8-beta-20260916024015.0";
156
+ const getMidsceneVersion = ()=>"1.12.8";
157
157
  const parsePrompt = (prompt)=>{
158
158
  if ('string' == typeof prompt) return {
159
159
  textPrompt: prompt,
@@ -199,10 +199,28 @@ ONLY if the task is not complete: Think what the next action is according to the
199
199
  ### Action Guidelines
200
200
 
201
201
  ${hasRunAdbShell ? "- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action." : ''}
202
- - For touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.
202
+ - If Swipe is available in the current Action Space, for touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.
203
203
  - When editing existing text in a UI field, preserve all existing text by moving the cursor and typing/deleting the minimal necessary characters.
204
204
  - For insert/prepend/append edits, use CursorMove when the caret must be adjusted precisely, then use Input with mode "typeOnly" for inserted characters and KeyboardPress for newlines or deletion. If the caret lands in the wrong position, recover with CursorMove, KeyboardPress, or undo and retry cursor placement; do not switch to replace as a fallback for cursor placement failures.
205
205
 
206
+ ### Interpreting Scroll and Swipe Directions
207
+
208
+ Scroll and swipe directions can be ambiguous: they may refer to off-screen content to reveal, visible content movement, or the physical movement of a finger, pointer, or scroll wheel. Infer the intended result from the user's goal, the interaction target, the current UI, and common usage in the user's language, rather than mechanically copying the user's direction word.
209
+
210
+ In the current Action Space, \`direction\` has the following meanings:
211
+
212
+ - Scroll follows the traditional mouse-wheel convention (with natural scrolling disabled). Its direction refers to the off-screen content to reveal; under this convention, it matches the wheel movement direction and is opposite to the content movement direction.
213
+ - Swipe follows the finger-movement convention. Its direction refers to finger movement; for controls where content follows the finger, it matches the content movement direction and is opposite to the direction from which off-screen content is revealed.
214
+
215
+ Use the following priority order:
216
+
217
+ 1. Prioritize the user's goal or expected result, even when it conflicts with a direction word. For example, for "swipe the date picker down to increase the date", if dates increase from top to bottom, use Swipe up to move a larger date from below into the selected position.
218
+ 2. Otherwise, if the user specifies a moving object or movement path, follow that object's physical movement. For example, "swipe the finger to the left" means Swipe left; "move the page content from top to bottom" means moving content downward, corresponding to Swipe down on a page where content follows the finger.
219
+ 3. Otherwise, consider the interaction target and common usage in the user's language. For content browsing, such as pages and lists, scroll directions usually refer to the off-screen content the user wants to see. For directly manipulated controls, such as sliders and wheel pickers, swipe directions usually refer to the intended movement of the control's movable part. For example, the Chinese "往下滑一下页面" and English "scroll down the page" usually mean revealing content below, corresponding to Scroll down; the Chinese "向右滑动滑块" and English "slide the slider to the right" usually mean moving the slider right, corresponding to Swipe right if using Swipe.
220
+ 4. If the intent remains ambiguous, use the Scroll and Swipe direction definitions above.
221
+
222
+ After interpreting the intent, choose an appropriate Action from the current Action Space and use its supported parameters to achieve the intended result. Some actions support start and end points instead of \`direction\`. When using \`direction\`, ensure its value achieves the intended result according to the selected Action's definition.
223
+
206
224
  ${includeLocateInPlanning ? locateGroundingRules() : ''}
207
225
 
208
226
  ### ${planningProtocol.actionSpaceProtocol.title}
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/prompt/planning/system-prompt.mjs","sources":["../../../../../src/ai-model/prompt/planning/system-prompt.ts"],"sourcesContent":["import type { DeviceAction } from '@/types';\nimport { getPreferredLanguage } from '@midscene/shared/env';\nimport type { StandardPlanningProtocol } from '../../model-adapter/planning-protocol';\nimport type { LocateResultPromptSpec } from '../../shared/model-locate-result';\nimport { planningModelFamilyRequiredForLocateMessage } from '../../shared/model-locate-result/errors';\nimport { locateGroundingRules } from '../locate';\nimport {\n buildActionOutputExample,\n createSampleTapAction,\n} from './action-output-example';\nimport { buildPlanningActionSpaceDescription } from './action-space-description';\nimport { buildPlanningMultiTurnExample } from './multi-turn-example';\n\ntype BuildStandardPlanningSystemPromptInput = {\n actionSpace: DeviceAction<any>[];\n includeSubGoals?: boolean;\n includeThought?: boolean;\n includeLog?: boolean;\n planningProtocol: StandardPlanningProtocol;\n} & (\n | {\n includeLocateInPlanning: true;\n locatePromptSpec: LocateResultPromptSpec;\n }\n | {\n includeLocateInPlanning: false;\n locatePromptSpec?: never;\n }\n);\n\nexport async function buildStandardPlanningSystemPrompt(\n input: BuildStandardPlanningSystemPromptInput,\n) {\n const {\n actionSpace,\n includeLocateInPlanning,\n locatePromptSpec,\n includeSubGoals,\n includeThought = true,\n includeLog = true,\n planningProtocol,\n } = input;\n const actionOutputProtocol = planningProtocol.actionOutputProtocol;\n const preferredLanguage = getPreferredLanguage();\n\n if (includeLocateInPlanning && !locatePromptSpec) {\n throw new Error(planningModelFamilyRequiredForLocateMessage());\n }\n\n const actionSpaceDescription = buildPlanningActionSpaceDescription({\n actionSpace,\n locatePromptSpec,\n planningProtocol,\n });\n const hasRunAdbShell = actionSpace.some(\n (action) => action.name === 'RunAdbShell',\n );\n const actionOutputTagsText = actionOutputProtocol.actionOutputTagNames\n .map((tagName) => `<${tagName}>`)\n .join(', ');\n\n const shouldIncludeSubGoals = includeSubGoals ?? false;\n const renderSubGoalsContent = (content: string, fallbackContent = '') =>\n shouldIncludeSubGoals ? content : fallbackContent;\n const renderThoughtContent = (content: string, fallbackContent = '') =>\n includeThought ? content : fallbackContent;\n const renderLogContent = (content: string, fallbackContent = '') =>\n includeLog ? content : fallbackContent;\n\n // Step numbering adjusts based on whether sub-goals are included\n // When includeSubGoals=false, memory step is skipped\n const completionCheckStepNumber = shouldIncludeSubGoals ? 3 : 2;\n const actionStepNumber = completionCheckStepNumber + 1;\n\n return `\nTarget: You are an expert to manipulate the UI to accomplish the user's instruction. User will give you an instruction, some screenshots, background knowledge and previous logs indicating what have been done. Your task is to accomplish the instruction by thinking through the path to complete the task and give the next action to execute.\n\n## Step 1: ${renderSubGoalsContent(\n 'Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)',\n renderThoughtContent('Observe (related tags: <planning>)', 'Observe'),\n )}\n\nFirst, observe the current screenshot and previous logs${renderSubGoalsContent(\n \", then break down the user's instruction into multiple high-level sub-goals. Update the status of sub-goals based on what you see in the current screenshot.\",\n ' to understand the current state.',\n )}\n\n${renderSubGoalsContent(`### Observation Guidelines\n\n- Treat visible summaries, thumbnails, cropped content, and partially visible lists as potentially incomplete when the task depends on precise details.\n- If the current view does not provide enough information to decide safely, use available UI affordances such as opening details, expanding content, previewing, enlarging, zooming, or scrolling before acting.`)}\n\n${renderThoughtContent(`### <planning> tag (REQUIRED)\n\nREQUIRED: You MUST always output the <planning> tag. Never skip it.\n\nWrite the content of the <planning> tag in ${preferredLanguage}.\n\nInclude your planning details in the <planning> tag. It should answer: ${renderSubGoalsContent(\n \"What is the user's requirement? What is the current state based on the screenshot? Are all sub-goals completed? If not, what should be the next action?\",\n 'What is the current state based on the screenshot? What should be the next action?',\n)} Write it naturally without numbering or section headers.\n\nCRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: \"fill out the form\" means only fill fields, do NOT submit; \"click the button\" means only click, do NOT wait for page load or verify results; \"type 'hello'\" means only type, do NOT press Enter.`)}\n\n${renderSubGoalsContent(`### <update-plan-content> tag\n\nUse this structure to give or update your plan:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished|pending\">sub goal description</sub-goal>\n <sub-goal index=\"2\" status=\"finished|pending\">sub goal description</sub-goal>\n ...\n</update-plan-content>\n\n### <mark-sub-goal-done> tag\n\nUse this structure to mark a sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nIMPORTANT: You MUST only mark a sub-goal as \"finished\" AFTER you have confirmed the task is actually completed by observing the result in the screenshot. Do NOT mark a sub-goal as done just because you expect the next action will complete it. Wait until you see visual confirmation in the screenshot that the sub-goal has been achieved.\n\n### Note\n\nDuring execution, you can call <update-plan-content> at any time to update the plan based on the latest screenshot and completed sub-goals.\n\n### Example\n\nIf the user wants to \"log in to a system using username and password, complete all to-do items, and submit a registration form\", you can break it down into the following sub-goals:\n\n<planning>...</planning>\n<update-plan-content>\n <sub-goal index=\"1\" status=\"pending\">Log in to the system</sub-goal>\n <sub-goal index=\"2\" status=\"pending\">Complete all to-do items</sub-goal>\n <sub-goal index=\"3\" status=\"pending\">Submit the registration form</sub-goal>\n</update-plan-content>\n\nAfter logging in and seeing the to-do items, you can mark the sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nAt this point, the status of all sub-goals is:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished\" />\n <sub-goal index=\"2\" status=\"pending\" />\n <sub-goal index=\"3\" status=\"pending\" />\n</update-plan-content>\n\nAfter some time, when the last sub-goal is also completed, you can mark it as done as well:\n\n<mark-sub-goal-done>\n <sub-goal index=\"3\" status=\"finished\" />\n</mark-sub-goal-done>`)}\n\n${renderSubGoalsContent(`## Step 2: Memory Data from Current Screenshot (related tags: <memory>)\n\nUse <memory> to record clear, task-relevant information from the current screenshot that may be needed in later steps. The current screenshot will not be available later, so memory should preserve enough detail for future reasoning, verification, or action.\n\n- Record information completely and exactly as shown. Do not summarize, translate, normalize, or merge values that may matter later.\n- When recording an item, include the item itself, its exact task-relevant details, and the visible cue or UI context that identifies where it came from when relevant.\n- Keep similar or repeated items as separate memory entries unless their task-relevant details are confirmed to be the same.\n- After navigation, scrolling, editing, deletion, saving, or other screen changes, treat remembered positions, order, indexes, and UI bindings as references only. Re-check the current screen before acting on them.\n\nExamples:\n- If you need to find an item and later assert its details, record the item name and the exact details needed for the assertion, such as status, price, date, owner, description, or other visible fields.\n- If you need to compare multiple similar results, record each candidate separately with its exact distinguishing details and visible context.\n- If you need to copy information from one place to another, record the exact source value and the target field or UI cue it should be mapped to.\n\nDon't use this tag if no information needs to be preserved.`)}\n\n## Step ${completionCheckStepNumber}: ${renderSubGoalsContent(\n 'Check if Goal is Accomplished',\n 'Check if the Instruction is Fulfilled',\n )} (related tags: <complete>)\n\nDetermine if the entire task is completed${renderSubGoalsContent(' based on the current screenshot and the status of all sub-goals')}.\n\n### CRITICAL: The User's Instruction is the Supreme Authority\n\nThe user's instruction defines the EXACT scope of what you must accomplish. You MUST follow it precisely - nothing more, nothing less. Violating this rule may cause severe consequences such as data loss, unintended operations, or system failures.\n\n**Explicit instructions vs. High-level goals:**\n- If the user gives you **explicit operation steps** (e.g., \"click X\", \"type Y\", \"fill out the form\"), treat them as exact commands. Execute ONLY those steps, nothing more.\n- If the user gives you a **high-level goal** (e.g., \"log in to the system\", \"complete the purchase\"), you may determine the necessary steps to achieve it.\n\n**What \"${renderSubGoalsContent('goal accomplished', 'instruction fulfilled')}\" means:**\n- The ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} when you have done EXACTLY what the user asked - no extra steps, no assumptions.\n- Do NOT perform any action beyond the explicit instruction, even if it seems logical or helpful.\n\n**Examples - Explicit instructions (execute exactly, no extra steps):**\n- \"fill out the form\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when all fields are filled. Do NOT submit the form.\n- \"click the login button\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} once clicked. Do NOT wait for page load or verify login success.\n- \"type 'hello' in the search box\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when 'hello' is typed. Do NOT press Enter or trigger search.\n- \"select the first item\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when selected. Do NOT proceed to checkout.\n\n**Change completion:**\n- If the requested outcome is a durable change, such as create, edit, update, delete, save, send, submit, apply, or publish, do not stop at an unsaved draft, open editor, temporary input, transient selection, or staged value. Continue through the app/page's normal completion control such as Save, Done, Confirm, OK, Submit, Apply, Send, or Publish before completing, so the result remains after leaving the screen.\n- If the user only asks for an intermediate UI state, such as typing text, selecting an option, filling fields, or opening a screen without saving/submitting/applying, stop once that exact state is reached.\n\n**Special case - Scrollable option lists and dropdowns:**\n- When choosing an item from a scrollable select, dropdown, listbox, menu, or similar option list, first open the control if it is closed. Once the list is open, interact with the list itself, not the page.\n- If the target option is visible in the open list, Tap that exact option immediately.\n- If the list is open but the target option is not visible, try to find it by scrolling the open list/dropdown before giving up or interacting with other elements.\n- For an open dropdown/list, prefer small incremental Scroll actions with an explicit distance (typically 50-120 pixels) and a locate target describing the open list/dropdown. Do NOT omit distance while searching within a list, because the default scroll distance can skip over relevant options and cause oscillation.\n- While searching within an open dropdown/list, use short scrolls so intermediate options are not skipped.\n- After selecting the target, if the trigger text or result text shows the requested option, treat the current selection step as fulfilled and continue evaluating the remaining user instruction.\n\n**Special case - Text hidden by a narrow input field:**\n- CRITICAL PRIORITY OVERRIDE - Input verification after an input action:\n- This rule overrides the general requirement to verify the exact target text from the screenshot.\n- If the previous step already executed an input action, and the current input field is not empty, you MUST directly treat that input as successful.\n- In this situation, do NOT use the visible text in the screenshot to decide that the input is incomplete, incorrect, missing characters, out of order, or needs correction.\n- Do NOT perform ClearInput, another Input, KeyboardPress, or any other action intended to \"fix the input content\" just because the visible text looks different from the target text, has abnormal character order, missing characters, abnormal spacing, suspicious visual recognition results, or appears to have selected/highlighted text.\n- The general rule \"do EXACTLY what the user asked\" still applies to the intended input value you execute, but it MUST NOT be enforced by re-validating the visible text in the screenshot after the input action.\n- Differences in visible text must be assumed to be caused by clipping, horizontal scrolling, narrow input fields, text selection, caret position, or visual recognition errors rather than input failure.\n- Retry input only when the input field is clearly still empty, or when the page shows an explicit error message.\n\n**Special case - Assertion instructions:**\n- If the user's instruction includes an assertion (e.g., \"verify that...\", \"check that...\", \"assert...\"), and you observe from the screenshot that the assertion condition is NOT satisfied and cannot be satisfied, mark ${renderSubGoalsContent('the goal', 'it')} as failed (success=\"false\").\n- If the page is still loading (e.g., you see a loading spinner, skeleton screen, or progress bar), do NOT assert yet. Wait for the page to finish loading before evaluating the assertion.\n\n### Completion Criteria for Process-required Instructions\n\nIf the user's instruction includes explicit operation steps, ordering requirements, or action requirements, it is a process-required instruction.\n\nFor process-required instructions, do NOT treat the task as complete only because the current screenshot already shows the final expected state. Do NOT infer that earlier steps were executed from the final UI state.\n\nYou may output <complete success=\"true\"> only when the current execution history, previous logs, or the screenshot after the most recent action proves that every explicit step required by the user has been completed, and the final check condition is also satisfied.\n\nIf any explicit step lacks completion evidence in the current execution history, continue with the next missing step instead of outputting <complete>, even if the current screenshot appears to satisfy the final condition.\n\n${renderSubGoalsContent(\n '',\n `**Page navigation restriction:**\n- Unless the user's instruction explicitly asks you to click a link, jump to another page, or navigate to a URL, you MUST complete the task on the current page only.\n- Do NOT navigate away from the current page on your own initiative (e.g., do not click links that lead to other pages, do not use browser back/forward, do not open new URLs).\n- If the task cannot be accomplished on the current page and the user has not instructed you to navigate, report it as a failure (success=\"false\") instead of attempting to navigate to other pages.`,\n)}\n\n### Output Rules\n\n- If the task is NOT complete, skip this section and continue to Step ${actionStepNumber}.\n- Use the <complete success=\"true|false\">message</complete> tag to output the result if the goal is accomplished or failed.\n - the 'success' attribute is required. ${renderSubGoalsContent('It means whether the expected goal is accomplished based on what you observe in the current screenshot and the current execution history. ')}No matter what errors occurred during execution, set success=\"true\" only when the current execution history shows that all steps required by the user have been completed and the final state satisfies the requirement. If the user asks for explicit operation steps or an ordered workflow, do not treat those steps as completed only because the current screenshot already shows the final expected state. If the ${renderSubGoalsContent('expected goal is not accomplished and cannot be accomplished', 'instruction is not fulfilled and cannot be fulfilled')}, set success=\"false\".\n - the 'message' is the information that will be provided to the user. If the user asks for a specific format, strictly follow that.\n- If you output <complete>, do NOT output ${actionOutputTagsText}. The task ends here.\n\n## Step ${actionStepNumber}: Determine Next Action (related tags: ${renderLogContent('<log>, ')}${actionOutputTagsText}, <error>)\n\nONLY if the task is not complete: Think what the next action is according to the current screenshot${renderSubGoalsContent(' and the plan')}.\n\n- Don't give extra actions or plans beyond the instruction or the plan. For example, don't try to submit the form if the instruction is only to fill something.\n- Consider the current screenshot and give the action that is most likely to accomplish the instruction. For example, if the next step is to click a button but it's not visible in the screenshot, you should try to find it first instead of give a click action.\n- Make sure the previous actions are completed successfully. Otherwise, retry or do something else to recover.\n- Give just the next ONE action you should do (if any)\n- If there are some error messages reported by the previous actions, don't give up, try parse a new action to recover. If the error persists for more than 3 times, you should think this is an error and set the \"error\" field to the error message.\n\n### Action Guidelines\n\n${\n hasRunAdbShell\n ? \"- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action.\"\n : ''\n}\n- For touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.\n- When editing existing text in a UI field, preserve all existing text by moving the cursor and typing/deleting the minimal necessary characters.\n- For insert/prepend/append edits, use CursorMove when the caret must be adjusted precisely, then use Input with mode \"typeOnly\" for inserted characters and KeyboardPress for newlines or deletion. If the caret lands in the wrong position, recover with CursorMove, KeyboardPress, or undo and retry cursor placement; do not switch to replace as a fallback for cursor placement failures.\n\n${includeLocateInPlanning ? locateGroundingRules() : ''}\n\n### ${planningProtocol.actionSpaceProtocol.title}\n\n${actionSpaceDescription}\n\n${renderLogContent(`### Log to give user feedback (preamble message)\n\nThe <log> tag is a brief preamble message to the user explaining what you're about to do. It should follow these principles and examples:\n\n- **Use ${preferredLanguage}**\n- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words or Chinese characters for quick updates).\n- **Build on prior context**: if this is not the first action to be done, use the preamble message to connect the dots with what's been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n\n**Examples:**\n- <log>Click the login button</log>\n- <log>Scroll to find the 'Yes' button in popup</log>\n- <log>Previous actions failed to find the 'Yes' button, i will try again</log>\n- <log>Go back to find the login button</log>`)}\n\n### If there is some action to do ...\n\n${actionOutputProtocol.actionOutputRules}\n\nFor example:\n${buildActionOutputExample(\n createSampleTapAction('Add to cart button for Sauce Labs Backpack'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 1,\n buildActionOutput: actionOutputProtocol.buildActionOutput,\n },\n)}\n\n### If you think there is an error ...\n\n- Use the <error> tag to output the error message.\n\nFor example:\n<error>Unable to find the required element on the page</error>\n\n### If there is no action to do ...\n\n- Don't output ${actionOutputTagsText} if there is no action to do.\n\n## Return Format\n\nReturn in XML format following this decision flow:\n\n${planningProtocol.responsePrefix ?? ''}\n\n${renderThoughtContent(`**Always include (REQUIRED):**\n<!-- Step 1: Observe and Plan -->\n<planning>Your planning details here. NEVER skip this tag.</planning>`)}\n${renderSubGoalsContent(`<!-- required when no update-plan-content is provided in the previous response -->\n<update-plan-content>...</update-plan-content>\n\n<!-- required when any sub-goal is completed -->\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\n<!-- Step 2: Memory data from current screenshot if needed -->\n<memory>...</memory>`)}\n\n**Then choose ONE of the following paths:**\n\n**Path A: If the ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} or failed (Step ${completionCheckStepNumber})**\n<complete success=\"true|false\">...</complete>\n\n**Path B: If the ${renderSubGoalsContent('goal is NOT complete', 'instruction is NOT fulfilled')} yet (Step ${actionStepNumber})**\n<!-- Determine next action -->\n${renderLogContent('<log>...</log>')}\n${actionOutputProtocol.actionOutputPlaceholder}\n\n<!-- OR if there's an error -->\n<error>...</error>\n\n${buildPlanningMultiTurnExample({\n includeSubGoals: shouldIncludeSubGoals,\n includeThought,\n includeLog,\n locatePromptSpec,\n actionOutputProtocol,\n prefix: planningProtocol.responsePrefix,\n})}`;\n}\n"],"names":["buildStandardPlanningSystemPrompt","input","actionSpace","includeLocateInPlanning","locatePromptSpec","includeSubGoals","includeThought","includeLog","planningProtocol","actionOutputProtocol","preferredLanguage","getPreferredLanguage","Error","planningModelFamilyRequiredForLocateMessage","actionSpaceDescription","buildPlanningActionSpaceDescription","hasRunAdbShell","action","actionOutputTagsText","tagName","shouldIncludeSubGoals","renderSubGoalsContent","content","fallbackContent","renderThoughtContent","renderLogContent","completionCheckStepNumber","actionStepNumber","locateGroundingRules","buildActionOutputExample","createSampleTapAction","buildPlanningMultiTurnExample"],"mappings":";;;;;;AA8BO,eAAeA,kCACpBC,KAA6C;IAE7C,MAAM,EACJC,WAAW,EACXC,uBAAuB,EACvBC,gBAAgB,EAChBC,eAAe,EACfC,iBAAiB,IAAI,EACrBC,aAAa,IAAI,EACjBC,gBAAgB,EACjB,GAAGP;IACJ,MAAMQ,uBAAuBD,iBAAiB,oBAAoB;IAClE,MAAME,oBAAoBC;IAE1B,IAAIR,2BAA2B,CAACC,kBAC9B,MAAM,IAAIQ,MAAMC;IAGlB,MAAMC,yBAAyBC,oCAAoC;QACjEb;QACAE;QACAI;IACF;IACA,MAAMQ,iBAAiBd,YAAY,IAAI,CACrC,CAACe,SAAWA,AAAgB,kBAAhBA,OAAO,IAAI;IAEzB,MAAMC,uBAAuBT,qBAAqB,oBAAoB,CACnE,GAAG,CAAC,CAACU,UAAY,CAAC,CAAC,EAAEA,QAAQ,CAAC,CAAC,EAC/B,IAAI,CAAC;IAER,MAAMC,wBAAwBf,mBAAmB;IACjD,MAAMgB,wBAAwB,CAACC,SAAiBC,kBAAkB,EAAE,GAClEH,wBAAwBE,UAAUC;IACpC,MAAMC,uBAAuB,CAACF,SAAiBC,kBAAkB,EAAE,GACjEjB,iBAAiBgB,UAAUC;IAC7B,MAAME,mBAAmB,CAACH,SAAiBC,kBAAkB,EAAE,GAC7DhB,aAAae,UAAUC;IAIzB,MAAMG,4BAA4BN,wBAAwB,IAAI;IAC9D,MAAMO,mBAAmBD,4BAA4B;IAErD,OAAO,CAAC;;;WAGC,EAAEL,sBACT,4FACAG,qBAAqB,sCAAsC,YAC3D;;uDAEmD,EAAEH,sBACrD,gK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AEW,iBAAiB,CAAC;;;;QAIZ,EAAEf,kBAAkB;;;;;;;;;6CASiB,CAAC,EAAE;;;;AAIhD,EAAED,qBAAqB,iBAAiB,CAAC;;;AAGzC,EAAEoB,yBACAC,sBAAsB,+CACtB;QACE1B;QACA,0BAA0B;QAC1B,mBAAmBK,qBAAqB,iBAAiB;IAC3D,GACA;;;;;;;;;;;eAWa,EAAES,qBAAqB;;;;;;AAMtC,EAAEV,iBAAiB,cAAc,IAAI,GAAG;;AAExC,EAAEgB,qBAAqB,CAAC;;qEAE6C,CAAC,EAAE;AACxE,EAAEH,sBAAsB,CAAC;;;;;;;;;oBASL,CAAC,EAAE;;;;iBAIN,EAAEA,sBAAsB,wBAAwB,4BAA4B,iBAAiB,EAAEK,0BAA0B;;;iBAGzH,EAAEL,sBAAsB,wBAAwB,gCAAgC,WAAW,EAAEM,iBAAiB;;AAE/H,EAAEF,iBAAiB,kBAAkB;AACrC,EAAEhB,qBAAqB,uBAAuB,CAAC;;;;;AAK/C,EAAEsB,8BAA8B;QAC9B,iBAAiBX;QACjBd;QACAC;QACAH;QACAK;QACA,QAAQD,iBAAiB,cAAc;IACzC,IAAI;AACJ"}
1
+ {"version":3,"file":"ai-model/prompt/planning/system-prompt.mjs","sources":["../../../../../src/ai-model/prompt/planning/system-prompt.ts"],"sourcesContent":["import type { DeviceAction } from '@/types';\nimport { getPreferredLanguage } from '@midscene/shared/env';\nimport type { StandardPlanningProtocol } from '../../model-adapter/planning-protocol';\nimport type { LocateResultPromptSpec } from '../../shared/model-locate-result';\nimport { planningModelFamilyRequiredForLocateMessage } from '../../shared/model-locate-result/errors';\nimport { locateGroundingRules } from '../locate';\nimport {\n buildActionOutputExample,\n createSampleTapAction,\n} from './action-output-example';\nimport { buildPlanningActionSpaceDescription } from './action-space-description';\nimport { buildPlanningMultiTurnExample } from './multi-turn-example';\n\ntype BuildStandardPlanningSystemPromptInput = {\n actionSpace: DeviceAction<any>[];\n includeSubGoals?: boolean;\n includeThought?: boolean;\n includeLog?: boolean;\n planningProtocol: StandardPlanningProtocol;\n} & (\n | {\n includeLocateInPlanning: true;\n locatePromptSpec: LocateResultPromptSpec;\n }\n | {\n includeLocateInPlanning: false;\n locatePromptSpec?: never;\n }\n);\n\nexport async function buildStandardPlanningSystemPrompt(\n input: BuildStandardPlanningSystemPromptInput,\n) {\n const {\n actionSpace,\n includeLocateInPlanning,\n locatePromptSpec,\n includeSubGoals,\n includeThought = true,\n includeLog = true,\n planningProtocol,\n } = input;\n const actionOutputProtocol = planningProtocol.actionOutputProtocol;\n const preferredLanguage = getPreferredLanguage();\n\n if (includeLocateInPlanning && !locatePromptSpec) {\n throw new Error(planningModelFamilyRequiredForLocateMessage());\n }\n\n const actionSpaceDescription = buildPlanningActionSpaceDescription({\n actionSpace,\n locatePromptSpec,\n planningProtocol,\n });\n const hasRunAdbShell = actionSpace.some(\n (action) => action.name === 'RunAdbShell',\n );\n const actionOutputTagsText = actionOutputProtocol.actionOutputTagNames\n .map((tagName) => `<${tagName}>`)\n .join(', ');\n\n const shouldIncludeSubGoals = includeSubGoals ?? false;\n const renderSubGoalsContent = (content: string, fallbackContent = '') =>\n shouldIncludeSubGoals ? content : fallbackContent;\n const renderThoughtContent = (content: string, fallbackContent = '') =>\n includeThought ? content : fallbackContent;\n const renderLogContent = (content: string, fallbackContent = '') =>\n includeLog ? content : fallbackContent;\n\n // Step numbering adjusts based on whether sub-goals are included\n // When includeSubGoals=false, memory step is skipped\n const completionCheckStepNumber = shouldIncludeSubGoals ? 3 : 2;\n const actionStepNumber = completionCheckStepNumber + 1;\n\n return `\nTarget: You are an expert to manipulate the UI to accomplish the user's instruction. User will give you an instruction, some screenshots, background knowledge and previous logs indicating what have been done. Your task is to accomplish the instruction by thinking through the path to complete the task and give the next action to execute.\n\n## Step 1: ${renderSubGoalsContent(\n 'Observe and Plan (related tags: <planning>, <update-plan-content>, <mark-sub-goal-done>)',\n renderThoughtContent('Observe (related tags: <planning>)', 'Observe'),\n )}\n\nFirst, observe the current screenshot and previous logs${renderSubGoalsContent(\n \", then break down the user's instruction into multiple high-level sub-goals. Update the status of sub-goals based on what you see in the current screenshot.\",\n ' to understand the current state.',\n )}\n\n${renderSubGoalsContent(`### Observation Guidelines\n\n- Treat visible summaries, thumbnails, cropped content, and partially visible lists as potentially incomplete when the task depends on precise details.\n- If the current view does not provide enough information to decide safely, use available UI affordances such as opening details, expanding content, previewing, enlarging, zooming, or scrolling before acting.`)}\n\n${renderThoughtContent(`### <planning> tag (REQUIRED)\n\nREQUIRED: You MUST always output the <planning> tag. Never skip it.\n\nWrite the content of the <planning> tag in ${preferredLanguage}.\n\nInclude your planning details in the <planning> tag. It should answer: ${renderSubGoalsContent(\n \"What is the user's requirement? What is the current state based on the screenshot? Are all sub-goals completed? If not, what should be the next action?\",\n 'What is the current state based on the screenshot? What should be the next action?',\n)} Write it naturally without numbering or section headers.\n\nCRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: \"fill out the form\" means only fill fields, do NOT submit; \"click the button\" means only click, do NOT wait for page load or verify results; \"type 'hello'\" means only type, do NOT press Enter.`)}\n\n${renderSubGoalsContent(`### <update-plan-content> tag\n\nUse this structure to give or update your plan:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished|pending\">sub goal description</sub-goal>\n <sub-goal index=\"2\" status=\"finished|pending\">sub goal description</sub-goal>\n ...\n</update-plan-content>\n\n### <mark-sub-goal-done> tag\n\nUse this structure to mark a sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nIMPORTANT: You MUST only mark a sub-goal as \"finished\" AFTER you have confirmed the task is actually completed by observing the result in the screenshot. Do NOT mark a sub-goal as done just because you expect the next action will complete it. Wait until you see visual confirmation in the screenshot that the sub-goal has been achieved.\n\n### Note\n\nDuring execution, you can call <update-plan-content> at any time to update the plan based on the latest screenshot and completed sub-goals.\n\n### Example\n\nIf the user wants to \"log in to a system using username and password, complete all to-do items, and submit a registration form\", you can break it down into the following sub-goals:\n\n<planning>...</planning>\n<update-plan-content>\n <sub-goal index=\"1\" status=\"pending\">Log in to the system</sub-goal>\n <sub-goal index=\"2\" status=\"pending\">Complete all to-do items</sub-goal>\n <sub-goal index=\"3\" status=\"pending\">Submit the registration form</sub-goal>\n</update-plan-content>\n\nAfter logging in and seeing the to-do items, you can mark the sub-goal as done:\n\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\nAt this point, the status of all sub-goals is:\n\n<update-plan-content>\n <sub-goal index=\"1\" status=\"finished\" />\n <sub-goal index=\"2\" status=\"pending\" />\n <sub-goal index=\"3\" status=\"pending\" />\n</update-plan-content>\n\nAfter some time, when the last sub-goal is also completed, you can mark it as done as well:\n\n<mark-sub-goal-done>\n <sub-goal index=\"3\" status=\"finished\" />\n</mark-sub-goal-done>`)}\n\n${renderSubGoalsContent(`## Step 2: Memory Data from Current Screenshot (related tags: <memory>)\n\nUse <memory> to record clear, task-relevant information from the current screenshot that may be needed in later steps. The current screenshot will not be available later, so memory should preserve enough detail for future reasoning, verification, or action.\n\n- Record information completely and exactly as shown. Do not summarize, translate, normalize, or merge values that may matter later.\n- When recording an item, include the item itself, its exact task-relevant details, and the visible cue or UI context that identifies where it came from when relevant.\n- Keep similar or repeated items as separate memory entries unless their task-relevant details are confirmed to be the same.\n- After navigation, scrolling, editing, deletion, saving, or other screen changes, treat remembered positions, order, indexes, and UI bindings as references only. Re-check the current screen before acting on them.\n\nExamples:\n- If you need to find an item and later assert its details, record the item name and the exact details needed for the assertion, such as status, price, date, owner, description, or other visible fields.\n- If you need to compare multiple similar results, record each candidate separately with its exact distinguishing details and visible context.\n- If you need to copy information from one place to another, record the exact source value and the target field or UI cue it should be mapped to.\n\nDon't use this tag if no information needs to be preserved.`)}\n\n## Step ${completionCheckStepNumber}: ${renderSubGoalsContent(\n 'Check if Goal is Accomplished',\n 'Check if the Instruction is Fulfilled',\n )} (related tags: <complete>)\n\nDetermine if the entire task is completed${renderSubGoalsContent(' based on the current screenshot and the status of all sub-goals')}.\n\n### CRITICAL: The User's Instruction is the Supreme Authority\n\nThe user's instruction defines the EXACT scope of what you must accomplish. You MUST follow it precisely - nothing more, nothing less. Violating this rule may cause severe consequences such as data loss, unintended operations, or system failures.\n\n**Explicit instructions vs. High-level goals:**\n- If the user gives you **explicit operation steps** (e.g., \"click X\", \"type Y\", \"fill out the form\"), treat them as exact commands. Execute ONLY those steps, nothing more.\n- If the user gives you a **high-level goal** (e.g., \"log in to the system\", \"complete the purchase\"), you may determine the necessary steps to achieve it.\n\n**What \"${renderSubGoalsContent('goal accomplished', 'instruction fulfilled')}\" means:**\n- The ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} when you have done EXACTLY what the user asked - no extra steps, no assumptions.\n- Do NOT perform any action beyond the explicit instruction, even if it seems logical or helpful.\n\n**Examples - Explicit instructions (execute exactly, no extra steps):**\n- \"fill out the form\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when all fields are filled. Do NOT submit the form.\n- \"click the login button\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} once clicked. Do NOT wait for page load or verify login success.\n- \"type 'hello' in the search box\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when 'hello' is typed. Do NOT press Enter or trigger search.\n- \"select the first item\" → ${renderSubGoalsContent('Goal accomplished', 'Instruction fulfilled')} when selected. Do NOT proceed to checkout.\n\n**Change completion:**\n- If the requested outcome is a durable change, such as create, edit, update, delete, save, send, submit, apply, or publish, do not stop at an unsaved draft, open editor, temporary input, transient selection, or staged value. Continue through the app/page's normal completion control such as Save, Done, Confirm, OK, Submit, Apply, Send, or Publish before completing, so the result remains after leaving the screen.\n- If the user only asks for an intermediate UI state, such as typing text, selecting an option, filling fields, or opening a screen without saving/submitting/applying, stop once that exact state is reached.\n\n**Special case - Scrollable option lists and dropdowns:**\n- When choosing an item from a scrollable select, dropdown, listbox, menu, or similar option list, first open the control if it is closed. Once the list is open, interact with the list itself, not the page.\n- If the target option is visible in the open list, Tap that exact option immediately.\n- If the list is open but the target option is not visible, try to find it by scrolling the open list/dropdown before giving up or interacting with other elements.\n- For an open dropdown/list, prefer small incremental Scroll actions with an explicit distance (typically 50-120 pixels) and a locate target describing the open list/dropdown. Do NOT omit distance while searching within a list, because the default scroll distance can skip over relevant options and cause oscillation.\n- While searching within an open dropdown/list, use short scrolls so intermediate options are not skipped.\n- After selecting the target, if the trigger text or result text shows the requested option, treat the current selection step as fulfilled and continue evaluating the remaining user instruction.\n\n**Special case - Text hidden by a narrow input field:**\n- CRITICAL PRIORITY OVERRIDE - Input verification after an input action:\n- This rule overrides the general requirement to verify the exact target text from the screenshot.\n- If the previous step already executed an input action, and the current input field is not empty, you MUST directly treat that input as successful.\n- In this situation, do NOT use the visible text in the screenshot to decide that the input is incomplete, incorrect, missing characters, out of order, or needs correction.\n- Do NOT perform ClearInput, another Input, KeyboardPress, or any other action intended to \"fix the input content\" just because the visible text looks different from the target text, has abnormal character order, missing characters, abnormal spacing, suspicious visual recognition results, or appears to have selected/highlighted text.\n- The general rule \"do EXACTLY what the user asked\" still applies to the intended input value you execute, but it MUST NOT be enforced by re-validating the visible text in the screenshot after the input action.\n- Differences in visible text must be assumed to be caused by clipping, horizontal scrolling, narrow input fields, text selection, caret position, or visual recognition errors rather than input failure.\n- Retry input only when the input field is clearly still empty, or when the page shows an explicit error message.\n\n**Special case - Assertion instructions:**\n- If the user's instruction includes an assertion (e.g., \"verify that...\", \"check that...\", \"assert...\"), and you observe from the screenshot that the assertion condition is NOT satisfied and cannot be satisfied, mark ${renderSubGoalsContent('the goal', 'it')} as failed (success=\"false\").\n- If the page is still loading (e.g., you see a loading spinner, skeleton screen, or progress bar), do NOT assert yet. Wait for the page to finish loading before evaluating the assertion.\n\n### Completion Criteria for Process-required Instructions\n\nIf the user's instruction includes explicit operation steps, ordering requirements, or action requirements, it is a process-required instruction.\n\nFor process-required instructions, do NOT treat the task as complete only because the current screenshot already shows the final expected state. Do NOT infer that earlier steps were executed from the final UI state.\n\nYou may output <complete success=\"true\"> only when the current execution history, previous logs, or the screenshot after the most recent action proves that every explicit step required by the user has been completed, and the final check condition is also satisfied.\n\nIf any explicit step lacks completion evidence in the current execution history, continue with the next missing step instead of outputting <complete>, even if the current screenshot appears to satisfy the final condition.\n\n${renderSubGoalsContent(\n '',\n `**Page navigation restriction:**\n- Unless the user's instruction explicitly asks you to click a link, jump to another page, or navigate to a URL, you MUST complete the task on the current page only.\n- Do NOT navigate away from the current page on your own initiative (e.g., do not click links that lead to other pages, do not use browser back/forward, do not open new URLs).\n- If the task cannot be accomplished on the current page and the user has not instructed you to navigate, report it as a failure (success=\"false\") instead of attempting to navigate to other pages.`,\n)}\n\n### Output Rules\n\n- If the task is NOT complete, skip this section and continue to Step ${actionStepNumber}.\n- Use the <complete success=\"true|false\">message</complete> tag to output the result if the goal is accomplished or failed.\n - the 'success' attribute is required. ${renderSubGoalsContent('It means whether the expected goal is accomplished based on what you observe in the current screenshot and the current execution history. ')}No matter what errors occurred during execution, set success=\"true\" only when the current execution history shows that all steps required by the user have been completed and the final state satisfies the requirement. If the user asks for explicit operation steps or an ordered workflow, do not treat those steps as completed only because the current screenshot already shows the final expected state. If the ${renderSubGoalsContent('expected goal is not accomplished and cannot be accomplished', 'instruction is not fulfilled and cannot be fulfilled')}, set success=\"false\".\n - the 'message' is the information that will be provided to the user. If the user asks for a specific format, strictly follow that.\n- If you output <complete>, do NOT output ${actionOutputTagsText}. The task ends here.\n\n## Step ${actionStepNumber}: Determine Next Action (related tags: ${renderLogContent('<log>, ')}${actionOutputTagsText}, <error>)\n\nONLY if the task is not complete: Think what the next action is according to the current screenshot${renderSubGoalsContent(' and the plan')}.\n\n- Don't give extra actions or plans beyond the instruction or the plan. For example, don't try to submit the form if the instruction is only to fill something.\n- Consider the current screenshot and give the action that is most likely to accomplish the instruction. For example, if the next step is to click a button but it's not visible in the screenshot, you should try to find it first instead of give a click action.\n- Make sure the previous actions are completed successfully. Otherwise, retry or do something else to recover.\n- Give just the next ONE action you should do (if any)\n- If there are some error messages reported by the previous actions, don't give up, try parse a new action to recover. If the error persists for more than 3 times, you should think this is an error and set the \"error\" field to the error message.\n\n### Action Guidelines\n\n${\n hasRunAdbShell\n ? \"- If the user's task can be completed with the RunAdbShell action, prefer using the RunAdbShell action.\"\n : ''\n}\n- If Swipe is available in the current Action Space, for touch continuous controls that set a value along a track, such as a slider, prefer Swipe from the current handle or filled position to the requested track endpoint instead of tapping the endpoint.\n- When editing existing text in a UI field, preserve all existing text by moving the cursor and typing/deleting the minimal necessary characters.\n- For insert/prepend/append edits, use CursorMove when the caret must be adjusted precisely, then use Input with mode \"typeOnly\" for inserted characters and KeyboardPress for newlines or deletion. If the caret lands in the wrong position, recover with CursorMove, KeyboardPress, or undo and retry cursor placement; do not switch to replace as a fallback for cursor placement failures.\n\n### Interpreting Scroll and Swipe Directions\n\nScroll and swipe directions can be ambiguous: they may refer to off-screen content to reveal, visible content movement, or the physical movement of a finger, pointer, or scroll wheel. Infer the intended result from the user's goal, the interaction target, the current UI, and common usage in the user's language, rather than mechanically copying the user's direction word.\n\nIn the current Action Space, \\`direction\\` has the following meanings:\n\n- Scroll follows the traditional mouse-wheel convention (with natural scrolling disabled). Its direction refers to the off-screen content to reveal; under this convention, it matches the wheel movement direction and is opposite to the content movement direction.\n- Swipe follows the finger-movement convention. Its direction refers to finger movement; for controls where content follows the finger, it matches the content movement direction and is opposite to the direction from which off-screen content is revealed.\n\nUse the following priority order:\n\n1. Prioritize the user's goal or expected result, even when it conflicts with a direction word. For example, for \"swipe the date picker down to increase the date\", if dates increase from top to bottom, use Swipe up to move a larger date from below into the selected position.\n2. Otherwise, if the user specifies a moving object or movement path, follow that object's physical movement. For example, \"swipe the finger to the left\" means Swipe left; \"move the page content from top to bottom\" means moving content downward, corresponding to Swipe down on a page where content follows the finger.\n3. Otherwise, consider the interaction target and common usage in the user's language. For content browsing, such as pages and lists, scroll directions usually refer to the off-screen content the user wants to see. For directly manipulated controls, such as sliders and wheel pickers, swipe directions usually refer to the intended movement of the control's movable part. For example, the Chinese \"往下滑一下页面\" and English \"scroll down the page\" usually mean revealing content below, corresponding to Scroll down; the Chinese \"向右滑动滑块\" and English \"slide the slider to the right\" usually mean moving the slider right, corresponding to Swipe right if using Swipe.\n4. If the intent remains ambiguous, use the Scroll and Swipe direction definitions above.\n\nAfter interpreting the intent, choose an appropriate Action from the current Action Space and use its supported parameters to achieve the intended result. Some actions support start and end points instead of \\`direction\\`. When using \\`direction\\`, ensure its value achieves the intended result according to the selected Action's definition.\n\n${includeLocateInPlanning ? locateGroundingRules() : ''}\n\n### ${planningProtocol.actionSpaceProtocol.title}\n\n${actionSpaceDescription}\n\n${renderLogContent(`### Log to give user feedback (preamble message)\n\nThe <log> tag is a brief preamble message to the user explaining what you're about to do. It should follow these principles and examples:\n\n- **Use ${preferredLanguage}**\n- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words or Chinese characters for quick updates).\n- **Build on prior context**: if this is not the first action to be done, use the preamble message to connect the dots with what's been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n\n**Examples:**\n- <log>Click the login button</log>\n- <log>Scroll to find the 'Yes' button in popup</log>\n- <log>Previous actions failed to find the 'Yes' button, i will try again</log>\n- <log>Go back to find the login button</log>`)}\n\n### If there is some action to do ...\n\n${actionOutputProtocol.actionOutputRules}\n\nFor example:\n${buildActionOutputExample(\n createSampleTapAction('Add to cart button for Sauce Labs Backpack'),\n {\n locatePromptSpec,\n locateResultExampleIndex: 1,\n buildActionOutput: actionOutputProtocol.buildActionOutput,\n },\n)}\n\n### If you think there is an error ...\n\n- Use the <error> tag to output the error message.\n\nFor example:\n<error>Unable to find the required element on the page</error>\n\n### If there is no action to do ...\n\n- Don't output ${actionOutputTagsText} if there is no action to do.\n\n## Return Format\n\nReturn in XML format following this decision flow:\n\n${planningProtocol.responsePrefix ?? ''}\n\n${renderThoughtContent(`**Always include (REQUIRED):**\n<!-- Step 1: Observe and Plan -->\n<planning>Your planning details here. NEVER skip this tag.</planning>`)}\n${renderSubGoalsContent(`<!-- required when no update-plan-content is provided in the previous response -->\n<update-plan-content>...</update-plan-content>\n\n<!-- required when any sub-goal is completed -->\n<mark-sub-goal-done>\n <sub-goal index=\"1\" status=\"finished\" />\n</mark-sub-goal-done>\n\n<!-- Step 2: Memory data from current screenshot if needed -->\n<memory>...</memory>`)}\n\n**Then choose ONE of the following paths:**\n\n**Path A: If the ${renderSubGoalsContent('goal is accomplished', 'instruction is fulfilled')} or failed (Step ${completionCheckStepNumber})**\n<complete success=\"true|false\">...</complete>\n\n**Path B: If the ${renderSubGoalsContent('goal is NOT complete', 'instruction is NOT fulfilled')} yet (Step ${actionStepNumber})**\n<!-- Determine next action -->\n${renderLogContent('<log>...</log>')}\n${actionOutputProtocol.actionOutputPlaceholder}\n\n<!-- OR if there's an error -->\n<error>...</error>\n\n${buildPlanningMultiTurnExample({\n includeSubGoals: shouldIncludeSubGoals,\n includeThought,\n includeLog,\n locatePromptSpec,\n actionOutputProtocol,\n prefix: planningProtocol.responsePrefix,\n})}`;\n}\n"],"names":["buildStandardPlanningSystemPrompt","input","actionSpace","includeLocateInPlanning","locatePromptSpec","includeSubGoals","includeThought","includeLog","planningProtocol","actionOutputProtocol","preferredLanguage","getPreferredLanguage","Error","planningModelFamilyRequiredForLocateMessage","actionSpaceDescription","buildPlanningActionSpaceDescription","hasRunAdbShell","action","actionOutputTagsText","tagName","shouldIncludeSubGoals","renderSubGoalsContent","content","fallbackContent","renderThoughtContent","renderLogContent","completionCheckStepNumber","actionStepNumber","locateGroundingRules","buildActionOutputExample","createSampleTapAction","buildPlanningMultiTurnExample"],"mappings":";;;;;;AA8BO,eAAeA,kCACpBC,KAA6C;IAE7C,MAA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AAEV,iBAAiB,cAAc,IAAI,GAAG;;AAExC,EAAEgB,qBAAqB,CAAC;;qEAE6C,CAAC,EAAE;AACxE,EAAEH,sBAAsB,CAAC;;;;;;;;;oBASL,CAAC,EAAE;;;;iBAIN,EAAEA,sBAAsB,wBAAwB,4BAA4B,iBAAiB,EAAEK,0BAA0B;;;iBAGzH,EAAEL,sBAAsB,wBAAwB,gCAAgC,WAAW,EAAEM,iBAAiB;;AAE/H,EAAEF,iBAAiB,kBAAkB;AACrC,EAAEhB,qBAAqB,uBAAuB,CAAC;;;;;AAK/C,EAAEsB,8BAA8B;QAC9B,iBAAiBX;QACjBd;QACAC;QACAH;QACAK;QACA,QAAQD,iBAAiB,cAAc;IACzC,IAAI;AACJ"}
@@ -207,7 +207,7 @@ const actionScrollParamSchema = z.object({
207
207
  });
208
208
  const defineActionScroll = (scroll)=>defineAction({
209
209
  name: 'Scroll',
210
- description: 'Scroll a page or scrollable region to reveal off-screen content. Use Scroll when the goal is to browse content outside the current viewport. For direct gesture interactions, such as adjusting a slider or wheel picker, switching between paged cards or images, following an on-screen swipe gesture to continue or dismiss, or swiping an item to delete it, use Swipe instead. Supports scrollToBottom/scrollToTop for boundary navigation. Default: direction `down`, scrollType `singleAction`, distance `null`.',
210
+ description: 'Scroll a page or scrollable region to reveal off-screen content. Use Scroll when the goal is to browse content outside the current viewport. For direct gesture interactions, such as adjusting a slider or wheel picker, switching between paged cards or images, following an on-screen swipe gesture to continue or dismiss, or swiping an item to delete it, use Swipe instead if available in the current Action Space. Supports scrollToBottom/scrollToTop for boundary navigation. Default: direction `down`, scrollType `singleAction`, distance `null`.',
211
211
  interfaceAlias: 'aiScroll',
212
212
  paramSchema: actionScrollParamSchema,
213
213
  sample: {
@@ -1 +1 @@
1
- {"version":3,"file":"device/index.mjs","sources":["../../../src/device/index.ts"],"sourcesContent":["import type { ModelRuntime } from '@/ai-model/models';\nimport { getMidsceneLocationSchema } from '@/common';\nimport type {\n ActionScrollParam,\n DeviceAction,\n ExecutorContext,\n LocateResultElement,\n} from '@/types';\nimport type { ElementNode } from '@midscene/shared/extractor';\nimport { getDebug } from '@midscene/shared/logger';\nimport { _keyDefinitions } from '@midscene/shared/us-keyboard-layout';\nimport { z } from 'zod';\nimport type {\n ElementCacheFeature,\n Rect,\n Size,\n UIContext,\n UITreeSnapshot,\n} from '../types';\nimport { type InputStrategy, inputStrategies } from './input-strategy';\n\nexport interface FileChooserHandler {\n accept(files: string[]): Promise<void>;\n}\n\nexport interface FileChooserRegistration {\n dispose: () => void;\n getError: () => Error | undefined | Promise<Error | undefined>;\n}\n\nexport interface MjpegStreamFrame {\n /** Raw base64-encoded image bytes WITHOUT a `data:image/...;base64,` prefix. */\n data: string;\n contentType?: string;\n}\n\nexport interface MjpegStreamHandle {\n stop(): void | Promise<void>;\n}\n\nexport interface MjpegStreamOptions {\n signal?: AbortSignal;\n onFrame(frame: MjpegStreamFrame): void;\n onError?(error: unknown): void;\n}\n\n/**\n * A cheap, not-yet-decoded handle to one screen frame from a\n * {@link DeviceFrameSource}. `ref` is platform-specific (a raw H.264 keyframe\n * buffer on Android, an already-encoded JPEG data URL on iOS/web) and must not\n * be interpreted by callers — pass it back to `decode()` to materialize.\n */\nexport interface DeviceFrameRef {\n ref: unknown;\n capturedAt: number;\n}\n\n/**\n * A continuous screen-frame source opened via\n * {@link AbstractInterface.openFrameSource}. Designed for deferred decoding:\n * grabbing `latest()` is near-zero cost, so observers can sample at a steady\n * cadence and pay any decode cost only once, for the frames they keep.\n */\nexport interface DeviceFrameSource {\n /** Latest frame handle, near-zero cost. Null until the first frame arrives. */\n latest(): DeviceFrameRef | null;\n /**\n * Materialize frame handles into `data:image/...;base64,` URLs, preserving\n * order. Possibly expensive (e.g. one ffmpeg run per unique frame on\n * Android) — call once with the sampled handles, never per tick.\n */\n decode(refs: DeviceFrameRef[]): Promise<string[]>;\n /** Release the source (stop streams/subscriptions it started). */\n stop(): Promise<void> | void;\n}\n\n/** A point in device-pixel coordinates on the screen. */\nexport interface PointerPoint {\n x: number;\n y: number;\n}\n\nexport interface PointerInputPrimitives {\n tap(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n doubleClick?(p: PointerPoint): Promise<void>;\n rightClick?(p: PointerPoint): Promise<void>;\n hover?(p: PointerPoint): Promise<void>;\n longPress?(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n dragAndDrop?(from: PointerPoint, to: PointerPoint): Promise<void>;\n}\n\nexport interface TouchInputPrimitives {\n swipe(\n start: PointerPoint,\n end: PointerPoint,\n opts?: { duration?: number; repeat?: number },\n ): Promise<void>;\n pinch?(\n center: PointerPoint,\n opts: { startDistance: number; endDistance: number; duration: number },\n ): Promise<void>;\n}\n\nexport interface KeyboardInputPrimitives {\n keyboardPress(keyName: string, opts?: { target?: unknown }): Promise<void>;\n cursorMove?(direction: 'left' | 'right', times?: number): Promise<void>;\n typeText(\n value: string,\n opts?: {\n autoDismissKeyboard?: boolean;\n keyboardDismissStrategy?: 'esc-first' | 'back-first';\n keyboardTypeDelay?: number;\n inputStrategy?: InputStrategy;\n target?: unknown;\n replace?: boolean;\n focusOnly?: boolean;\n },\n ): Promise<void>;\n clearInput(target?: unknown): Promise<void>;\n}\n\nexport interface ScrollInputPrimitives {\n scroll(param: ActionScrollParam): Promise<void>;\n}\n\nexport interface SystemInputPrimitives {\n backButton?(): Promise<void>;\n homeButton?(): Promise<void>;\n recentAppsButton?(): Promise<void>;\n}\n\nexport interface InputPrimitives {\n pointer?: PointerInputPrimitives;\n keyboard?: KeyboardInputPrimitives;\n touch?: TouchInputPrimitives;\n scroll?: ScrollInputPrimitives;\n system?: SystemInputPrimitives;\n}\n\nexport interface MobileInputPrimitives extends InputPrimitives {\n pointer: PointerInputPrimitives & {\n doubleClick(p: PointerPoint): Promise<void>;\n longPress(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n dragAndDrop(from: PointerPoint, to: PointerPoint): Promise<void>;\n };\n keyboard: KeyboardInputPrimitives;\n touch: TouchInputPrimitives;\n}\n\nexport interface BrowserInputPrimitives extends InputPrimitives {\n pointer: PointerInputPrimitives & {\n doubleClick(p: PointerPoint): Promise<void>;\n rightClick(p: PointerPoint): Promise<void>;\n hover(p: PointerPoint): Promise<void>;\n dragAndDrop(from: PointerPoint, to: PointerPoint): Promise<void>;\n longPress(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n };\n keyboard: KeyboardInputPrimitives;\n scroll: ScrollInputPrimitives;\n touch: TouchInputPrimitives;\n}\n\nexport interface ComputerInputPrimitives extends InputPrimitives {\n pointer: PointerInputPrimitives & {\n doubleClick(p: PointerPoint): Promise<void>;\n rightClick(p: PointerPoint): Promise<void>;\n hover(p: PointerPoint): Promise<void>;\n dragAndDrop(from: PointerPoint, to: PointerPoint): Promise<void>;\n };\n keyboard: KeyboardInputPrimitives;\n scroll: ScrollInputPrimitives;\n}\n\nexport abstract class AbstractInterface {\n abstract interfaceType: string;\n\n abstract screenshotBase64(): Promise<string>;\n abstract size(): Promise<Size>;\n abstract actionSpace(): DeviceAction[];\n\n abstract cacheFeatureForPoint?(\n center: [number, number],\n options?: {\n targetDescription?: string;\n modelRuntime?: ModelRuntime;\n },\n ): Promise<ElementCacheFeature>;\n abstract rectMatchesCacheFeature?(\n feature: ElementCacheFeature,\n ): Promise<Rect>;\n\n abstract getUITree?(): Promise<UITreeSnapshot>;\n\n abstract destroy?(): Promise<void>;\n\n abstract describe?(): string;\n abstract beforeInvokeAction?(actionName: string, param: any): Promise<void>;\n abstract afterInvokeAction?(actionName: string, param: any): Promise<void>;\n\n // for web only\n registerFileChooserListener?(\n handler: (chooser: FileChooserHandler) => Promise<void>,\n ): Promise<FileChooserRegistration>;\n\n // @deprecated do NOT extend this method\n abstract getElementsNodeTree?: () => Promise<ElementNode>;\n\n // @deprecated do NOT extend this method\n abstract url?: () => string | Promise<string>;\n\n // @deprecated do NOT extend this method\n abstract evaluateJavaScript?<T = any>(script: string): Promise<T>;\n\n /**\n * Get the current device-local time as a formatted string.\n * Prefer this for user-visible time because timestamps alone do not preserve\n * the target device's timezone when formatted on the host machine.\n */\n getDeviceLocalTimeString?(format?: string): Promise<string>;\n\n /** URL of native MJPEG stream for real-time screen preview (e.g. WDA MJPEG server) */\n mjpegStreamUrl?: string;\n\n /**\n * Optional continuous frame source for UI observation (`startObserving`).\n * Devices that maintain a continuous frame stream — scrcpy on Android, WDA\n * MJPEG on iOS, CDP screencast on web — implement this so an observer can\n * sample the screen far faster than repeated `screenshotBase64()` calls,\n * catching short-lived UI (toasts, carousels, transitions).\n *\n * The contract enables DEFERRED decoding: `latest()` returns a cheap opaque\n * handle (e.g. a raw H.264 keyframe on Android) with no per-frame decode\n * cost, and `decode()` materializes only the handles that were actually\n * sampled — once, at the end of the observation window.\n */\n openFrameSource?(): Promise<DeviceFrameSource | undefined>;\n\n /**\n * Optional in-process MJPEG frame producer. Implementations can push raw\n * base64 frames here when there is no standalone native MJPEG URL, e.g.\n * Chromium CDP Page.startScreencast for web previews.\n */\n startMjpegStream?(\n options: MjpegStreamOptions,\n ): MjpegStreamHandle | undefined | Promise<MjpegStreamHandle | undefined>;\n\n /**\n * Optional hook used after a UI action to push a fresh frame on the active\n * MJPEG stream. Set `force` after navigation to replace a transient loading\n * frame even when the screencast has already emitted one. Implementations\n * should be a no-op when no stream is active.\n */\n flushPendingVisualUpdate?(force?: boolean): Promise<void>;\n\n /**\n * Optional non-blocking variant of `flushPendingVisualUpdate`. Keyboard-\n * heavy preview interactions can schedule a coalesced refresh here without\n * stalling the input hot path; `force` preserves a requested navigation\n * refresh while work is already queued.\n */\n schedulePendingVisualUpdate?(force?: boolean): void;\n\n /**\n * Optional navigation state probe for browser-like interfaces, used to drive\n * loading indicators in playground UIs. Returning `undefined` means the\n * interface does not expose this concept.\n */\n navigationState?(): Promise<{ isLoading: boolean }>;\n\n /**\n * Low-level device input surface. Platform implementations expose transport\n * primitives here; higher-level AI actions and manual pointer dispatch should\n * adapt to this instead of duplicating platform gesture logic.\n */\n inputPrimitives?: InputPrimitives;\n}\n\n// Generic function to define actions with proper type inference\n// TRuntime allows specifying a different type for the runtime parameter (after location resolution)\n// TReturn allows specifying the return type of the action\nexport const defineAction = <\n TSchema extends z.ZodType | undefined = undefined,\n TRuntime = TSchema extends z.ZodType ? z.infer<TSchema> : undefined,\n TReturn = any,\n>(\n config: {\n name: string;\n description: string;\n interfaceAlias?: string;\n paramSchema?: TSchema;\n call: (\n param: TRuntime,\n context?: ExecutorContext,\n ) => Promise<TReturn> | TReturn;\n } & Partial<\n Omit<\n DeviceAction<TRuntime, TReturn>,\n 'name' | 'description' | 'interfaceAlias' | 'paramSchema' | 'call'\n >\n >,\n): DeviceAction<TRuntime, TReturn> => {\n return config as any; // Type assertion needed because schema validation type differs from runtime type\n};\n\nfunction pointFromLocate(\n locate: LocateResultElement | undefined,\n missingMessage: string,\n): PointerPoint {\n if (!locate) {\n throw new Error(missingMessage);\n }\n return { x: locate.center[0], y: locate.center[1] };\n}\n\nfunction defineLocatedPointAction<\n TSchema extends z.ZodType,\n TParam extends { locate: LocateResultElement },\n>(config: {\n name: string;\n description: string;\n interfaceAlias?: string;\n paramSchema: TSchema;\n sample: DeviceAction<TParam>['sample'];\n missingLocateMessage: string;\n call: (point: PointerPoint, param: TParam) => Promise<void>;\n}): DeviceAction<TParam> {\n return defineAction<TSchema, TParam>({\n name: config.name,\n description: config.description,\n interfaceAlias: config.interfaceAlias,\n paramSchema: config.paramSchema,\n sample: config.sample,\n call: async (param) => {\n await config.call(\n pointFromLocate(param.locate, config.missingLocateMessage),\n param,\n );\n },\n });\n}\n\n// Tap\nexport const actionTapParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe('The element to be tapped'),\n});\nexport type ActionTapParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionTap = (\n tap: PointerInputPrimitives['tap'],\n): DeviceAction<ActionTapParam> => {\n return defineLocatedPointAction<typeof actionTapParamSchema, ActionTapParam>({\n name: 'Tap',\n description: 'Tap the element',\n interfaceAlias: 'aiTap',\n paramSchema: actionTapParamSchema,\n sample: {\n locate: { prompt: 'the \"Submit\" button' },\n },\n missingLocateMessage: 'Element not found, cannot tap',\n call: async (point) => {\n await tap(point);\n },\n });\n};\n\nexport const registerFileChooserAcceptParamSchema = z.object({\n files: z\n .union([z.string(), z.array(z.string())])\n .describe(\n \"File path(s) within the current aiAct call's fileChooserAllowedDir to use whenever a later action triggers a file chooser. fileChooserAllowedDir must be provided for this action. This setting replaces any previously registered file path(s).\",\n ),\n});\nexport type RegisterFileChooserAcceptParam = {\n files: string | string[];\n};\n\nexport const defineActionRegisterFileChooserAccept = (\n register: (files: string | string[]) => Promise<void>,\n): DeviceAction<RegisterFileChooserAcceptParam> => {\n return defineAction<\n typeof registerFileChooserAcceptParamSchema,\n RegisterFileChooserAcceptParam\n >({\n name: 'RegisterFileChooserAccept',\n description:\n 'Configure files for file chooser dialogs triggered by later actions in this aiAct',\n interfaceAlias: 'registerFileChooserAccept',\n paramSchema: registerFileChooserAcceptParamSchema,\n sample: {\n files: ['fixtures/document.pdf'],\n },\n call: async (param) => {\n await register(param.files);\n },\n });\n};\n\n// RightClick\nexport const actionRightClickParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe(\n 'The element to be right clicked',\n ),\n});\nexport type ActionRightClickParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionRightClick = (\n rightClick: NonNullable<PointerInputPrimitives['rightClick']>,\n): DeviceAction<ActionRightClickParam> => {\n return defineLocatedPointAction<\n typeof actionRightClickParamSchema,\n ActionRightClickParam\n >({\n name: 'RightClick',\n description: 'Right click the element',\n interfaceAlias: 'aiRightClick',\n paramSchema: actionRightClickParamSchema,\n sample: {\n locate: { prompt: 'the file icon on the desktop' },\n },\n missingLocateMessage: 'Element not found, cannot right click',\n call: async (point) => {\n await rightClick(point);\n },\n });\n};\n\n// DoubleClick\nexport const actionDoubleClickParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe(\n 'The element to be double clicked',\n ),\n});\nexport type ActionDoubleClickParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionDoubleClick = (\n doubleClick: NonNullable<PointerInputPrimitives['doubleClick']>,\n): DeviceAction<ActionDoubleClickParam> => {\n return defineLocatedPointAction<\n typeof actionDoubleClickParamSchema,\n ActionDoubleClickParam\n >({\n name: 'DoubleClick',\n description: 'Double click the element',\n interfaceAlias: 'aiDoubleClick',\n paramSchema: actionDoubleClickParamSchema,\n sample: {\n locate: { prompt: 'the folder icon' },\n },\n missingLocateMessage: 'Element not found, cannot double click',\n call: async (point) => {\n await doubleClick(point);\n },\n });\n};\n\n// Hover\nexport const actionHoverParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe('The element to be hovered'),\n});\nexport type ActionHoverParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionHover = (\n hover: NonNullable<PointerInputPrimitives['hover']>,\n): DeviceAction<ActionHoverParam> => {\n return defineLocatedPointAction<\n typeof actionHoverParamSchema,\n ActionHoverParam\n >({\n name: 'Hover',\n description: 'Move the mouse to the element',\n interfaceAlias: 'aiHover',\n paramSchema: actionHoverParamSchema,\n sample: {\n locate: { prompt: 'the navigation menu item \"Products\"' },\n },\n missingLocateMessage: 'Element not found, cannot hover',\n call: async (point) => {\n await hover(point);\n },\n });\n};\n\n// Input\nconst inputLocateDescription =\n 'the position of the placeholder or text content in the target input field. If there is no content, locate the center of the input field.';\nexport const actionInputParamSchema = z.object({\n value: z\n .union([z.string(), z.number()])\n .transform((val) => String(val))\n .describe(\n 'The text to input. Provide the final content for replace mode, only the inserted characters for typeOnly mode, or an empty string when using clear mode to remove existing text.',\n ),\n locate: getMidsceneLocationSchema()\n .describe(inputLocateDescription)\n .optional(),\n mode: z\n .enum(['replace', 'clear', 'typeOnly'])\n .default('replace')\n .describe(\n 'Input mode: \"replace\" (default) - clear the field and input the value; \"typeOnly\" - type the value directly without clearing the field first, and should be set explicitly for incremental edits after moving the cursor; \"clear\" - clear the field without inputting new text.',\n ),\n autoDismissKeyboard: z\n .boolean()\n .optional()\n .describe(\n 'If true, the keyboard will be dismissed after the input is completed. Do not set it unless the user asks you to do so.',\n ),\n keyboardTypeDelay: z\n .number()\n .finite()\n .nonnegative()\n .optional()\n .describe(\n 'Delay in milliseconds between keystrokes when typing. Passed through from device/user configuration. Do not set it unless the user asks you to do so.',\n ),\n inputStrategy: z\n .enum(inputStrategies)\n .optional()\n .describe(\n 'Text input strategy: \"legacy\" (default) preserves the current platform behavior; \"sequential\" enters one Unicode code point at a time; \"bulk\" sends the complete text through one platform input operation when supported and requires keyboardTypeDelay to be omitted or set to 0. Do not set it unless the user asks you to do so.',\n ),\n});\nexport type ActionInputParam = {\n value: string;\n locate?: LocateResultElement;\n mode?: 'replace' | 'clear' | 'typeOnly' | 'append';\n autoDismissKeyboard?: boolean;\n keyboardTypeDelay?: number;\n inputStrategy?: InputStrategy;\n};\n\nexport const defineActionInput = (\n keyboard: KeyboardInputPrimitives,\n): DeviceAction<ActionInputParam> => {\n return defineAction<typeof actionInputParamSchema, ActionInputParam>({\n name: 'Input',\n description: 'Input the value into the element',\n interfaceAlias: 'aiInput',\n paramSchema: actionInputParamSchema,\n sample: {\n value: 'test@example.com',\n locate: { prompt: 'the email input field' },\n },\n call: async (param) => {\n // backward compat: convert deprecated 'append' to 'typeOnly'\n if ((param.mode as string) === 'append') {\n param.mode = 'typeOnly';\n }\n\n if (param.mode === 'clear') {\n await keyboard.clearInput(param.locate);\n return;\n }\n\n if (!param || !param.value) {\n return;\n }\n\n await keyboard.typeText(param.value, {\n target: param.locate,\n replace: param.mode !== 'typeOnly',\n autoDismissKeyboard: param.autoDismissKeyboard,\n keyboardTypeDelay: param.keyboardTypeDelay,\n inputStrategy: param.inputStrategy,\n });\n },\n });\n};\n\n// KeyboardPress\nexport const actionKeyboardPressParamSchema = z.object({\n locate: getMidsceneLocationSchema()\n .describe(\n 'The optional element to click before pressing the key. Omit this when the key should operate on the currently focused element, especially when copying or cutting an existing text selection.',\n )\n .optional(),\n keyName: z\n .string()\n .describe(\n \"The key to be pressed. Use '+' for key combinations, e.g., 'Control+A', 'Shift+Enter'\",\n ),\n});\nexport type ActionKeyboardPressParam = {\n locate?: LocateResultElement;\n keyName: string;\n};\n\nexport const defineActionKeyboardPress = (\n keyboardPress: KeyboardInputPrimitives['keyboardPress'],\n): DeviceAction<ActionKeyboardPressParam> => {\n return defineAction<\n typeof actionKeyboardPressParamSchema,\n ActionKeyboardPressParam\n >({\n name: 'KeyboardPress',\n description:\n 'Press a key or key combination, like \"Enter\", \"Tab\", \"Escape\", or \"Control+A\", \"Shift+Enter\". Do not use this to type text. Omit locate to operate on the current focus without clicking again, especially for Copy or Cut after text has been selected.',\n interfaceAlias: 'aiKeyboardPress',\n paramSchema: actionKeyboardPressParamSchema,\n sample: {\n keyName: 'Enter',\n },\n call: async (param) => {\n await keyboardPress(param.keyName, {\n target: param.locate,\n });\n },\n });\n};\n\n// Scroll\nexport const actionScrollParamSchema = z.object({\n scrollType: z\n .enum([\n 'singleAction',\n 'scrollToBottom',\n 'scrollToTop',\n 'scrollToRight',\n 'scrollToLeft',\n ])\n .default('singleAction')\n .describe(\n 'The scroll behavior: \"singleAction\" for a single scroll action, \"scrollToBottom\" for scrolling all the way to the bottom by rapidly scrolling 5-10 times (skipping intermediate content until reaching the bottom), \"scrollToTop\" for scrolling all the way to the top by rapidly scrolling 5-10 times (skipping intermediate content until reaching the top), \"scrollToRight\" for scrolling all the way to the right by rapidly scrolling multiple times, \"scrollToLeft\" for scrolling all the way to the left by rapidly scrolling multiple times',\n ),\n direction: z\n .enum(['down', 'up', 'right', 'left'])\n .default('down')\n .describe(\n 'The direction toward the off-screen content to reveal. \"down\" reveals content below the current viewport, \"up\" reveals content above, \"right\" reveals content to the right, and \"left\" reveals content to the left. This does not describe the movement direction of the content currently visible on the screen. Only effective when scrollType is \"singleAction\".',\n ),\n distance: z\n .number()\n .positive()\n .nullable()\n .optional()\n .describe(\n 'Positive requested scroll amount in screen-coordinate units. On touch platforms, it controls the length of the swipe gesture used to scroll; on web and desktop platforms, it controls or approximates the wheel scroll delta. Only effective when scrollType is \"singleAction\".',\n ),\n locate: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'Describe the target element to be scrolled on, like \"the table\" or \"the list\" or \"the content area\" or \"the scrollable area\". Do NOT provide a general intent like \"scroll to find some element\"',\n ),\n});\n\nexport const defineActionScroll = (\n scroll: ScrollInputPrimitives['scroll'],\n): DeviceAction<ActionScrollParam> => {\n return defineAction<typeof actionScrollParamSchema, ActionScrollParam>({\n name: 'Scroll',\n description:\n 'Scroll a page or scrollable region to reveal off-screen content. Use Scroll when the goal is to browse content outside the current viewport. For direct gesture interactions, such as adjusting a slider or wheel picker, switching between paged cards or images, following an on-screen swipe gesture to continue or dismiss, or swiping an item to delete it, use Swipe instead. Supports scrollToBottom/scrollToTop for boundary navigation. Default: direction `down`, scrollType `singleAction`, distance `null`.',\n interfaceAlias: 'aiScroll',\n paramSchema: actionScrollParamSchema,\n sample: {\n direction: 'down',\n scrollType: 'singleAction',\n locate: { prompt: 'the center of the product list area' },\n },\n call: async (param) => {\n await scroll(param);\n },\n });\n};\n\n// DragAndDrop\nexport const actionDragAndDropParamSchema = z.object({\n from: getMidsceneLocationSchema().describe('The position to be dragged'),\n to: getMidsceneLocationSchema().describe('The position to be dropped'),\n});\nexport type ActionDragAndDropParam = {\n from: LocateResultElement;\n to: LocateResultElement;\n};\n\nexport const defineActionDragAndDrop = (\n dragAndDrop: NonNullable<PointerInputPrimitives['dragAndDrop']>,\n): DeviceAction<ActionDragAndDropParam> => {\n return defineAction<\n typeof actionDragAndDropParamSchema,\n ActionDragAndDropParam\n >({\n name: 'DragAndDrop',\n description:\n 'Pick up a specific UI element and move it to a new position (e.g., reorder a card, move a file into a folder, sort list items). The element itself moves with your finger/mouse.',\n interfaceAlias: 'aiDragAndDrop',\n paramSchema: actionDragAndDropParamSchema,\n sample: {\n from: { prompt: 'the \"report.pdf\" file icon' },\n to: { prompt: 'the upload drop zone' },\n },\n call: async (param) => {\n const from = param.from;\n const to = param.to;\n if (!from) {\n throw new Error('missing \"from\" param for drag and drop');\n }\n if (!to) {\n throw new Error('missing \"to\" param for drag and drop');\n }\n await dragAndDrop(\n { x: from.center[0], y: from.center[1] },\n { x: to.center[0], y: to.center[1] },\n );\n },\n });\n};\n\nexport const ActionLongPressParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe(\n 'The element to be long pressed',\n ),\n duration: z\n .number()\n .optional()\n .describe('Long press duration in milliseconds'),\n});\n\nexport type ActionLongPressParam = {\n locate: LocateResultElement;\n duration?: number;\n};\nexport const defineActionLongPress = (\n longPress: NonNullable<PointerInputPrimitives['longPress']>,\n): DeviceAction<ActionLongPressParam> => {\n return defineLocatedPointAction<\n typeof ActionLongPressParamSchema,\n ActionLongPressParam\n >({\n name: 'LongPress',\n description: 'Long press the element',\n interfaceAlias: 'aiLongPress',\n paramSchema: ActionLongPressParamSchema,\n sample: {\n locate: { prompt: 'the message bubble' },\n },\n missingLocateMessage: 'LongPress requires an element to be located',\n call: async (point, param) => {\n await longPress(point, { duration: param.duration });\n },\n });\n};\n\nexport const ActionSwipeParamSchema = z.object({\n start: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'Optional starting point of the finger movement. Available in both relative and endpoint forms. If omitted, the center of the page is used.',\n ),\n direction: z\n .enum(['up', 'down', 'left', 'right'])\n .optional()\n .describe(\n 'Finger movement direction. Required together with a positive distance for a relative swipe. Omit when using end.',\n ),\n distance: z\n .number()\n .positive()\n .optional()\n .describe(\n 'Positive length of the finger movement in pixels. Required together with direction for a relative swipe. Omit when using end.',\n ),\n end: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'Endpoint of the finger movement. Use for an endpoint swipe, optionally with start. Do not provide direction or distance when using end.',\n ),\n duration: z\n .number()\n .default(300)\n .describe('Duration of the swipe gesture in milliseconds'),\n repeat: z\n .number()\n .optional()\n .describe(\n 'The number of times to repeat the swipe gesture. 1 for default, 0 for infinite (e.g. endless swipe until the end of the page)',\n ),\n});\n\nexport type ActionSwipeParam = {\n start?: LocateResultElement;\n direction?: 'up' | 'down' | 'left' | 'right';\n distance?: number;\n end?: LocateResultElement;\n duration?: number;\n repeat?: number;\n};\n\nexport function normalizeMobileSwipeParam(\n param: ActionSwipeParam,\n screenSize: { width: number; height: number },\n): {\n startPoint: { x: number; y: number };\n endPoint: { x: number; y: number };\n duration: number;\n repeatCount: number;\n} {\n const { width, height } = screenSize;\n const { start, end } = param;\n\n const startPoint = start\n ? { x: start.center[0], y: start.center[1] }\n : { x: width / 2, y: height / 2 };\n\n const endPoint = (() => {\n if (end) {\n if (param.direction !== undefined || param.distance !== undefined) {\n throw new Error(\n 'Invalid Swipe parameters: \"end\" cannot be combined with \"direction\" or \"distance\". Use \"end\", optionally with \"start\", for an endpoint swipe.',\n );\n }\n\n return { x: end.center[0], y: end.center[1] };\n }\n\n if (param.direction === undefined || param.distance === undefined) {\n throw new Error(\n 'Invalid Swipe parameters: a relative swipe requires both \"direction\" and a positive \"distance\".',\n );\n }\n\n if (param.distance <= 0) {\n throw new Error(\n 'Invalid Swipe parameters: \"distance\" must be a positive number.',\n );\n }\n\n return {\n x:\n startPoint.x +\n (param.direction === 'right'\n ? param.distance\n : param.direction === 'left'\n ? -param.distance\n : 0),\n y:\n startPoint.y +\n (param.direction === 'down'\n ? param.distance\n : param.direction === 'up'\n ? -param.distance\n : 0),\n };\n })();\n\n endPoint.x = Math.max(0, Math.min(endPoint.x, width));\n endPoint.y = Math.max(0, Math.min(endPoint.y, height));\n\n const duration = param.duration ?? 300;\n\n let repeatCount = typeof param.repeat === 'number' ? param.repeat : 1;\n if (repeatCount === 0) {\n repeatCount = 10;\n }\n\n return { startPoint, endPoint, duration, repeatCount };\n}\n\nexport const defineActionSwipe = (config: {\n swipe: TouchInputPrimitives['swipe'];\n size(): Promise<Size>;\n}): DeviceAction<ActionSwipeParam> => {\n return defineAction<typeof ActionSwipeParamSchema, ActionSwipeParam>({\n name: 'Swipe',\n description:\n 'Perform a touch gesture that directly manipulates the UI (e.g., adjust a continuous control such as a slider or wheel picker, switch between paged cards or images, follow an on-screen swipe gesture to continue or dismiss, or swipe an item to delete it). For browsing off-screen content in a page or scrollable region, use Scroll instead. Choose exactly one movement form: (1) relative swipe — provide \"direction\" and a positive \"distance\"; or (2) endpoint swipe — provide \"end\". \"start\" is optional for both forms and defaults to the center of the page. Do not combine \"end\" with \"direction\" or \"distance\".',\n paramSchema: ActionSwipeParamSchema,\n sample: {\n start: { prompt: 'center of the notification' },\n end: { prompt: 'upper edge of the screen' },\n },\n call: async (param) => {\n const { startPoint, endPoint, duration, repeatCount } =\n normalizeMobileSwipeParam(param, await config.size());\n for (let i = 0; i < repeatCount; i++) {\n await config.swipe(startPoint, endPoint, { duration });\n }\n },\n });\n};\n\n// ClearInput\nexport const actionClearInputParamSchema = z.object({\n locate: getMidsceneLocationSchema()\n .describe('The input field to be cleared')\n .optional(),\n});\nexport type ActionClearInputParam = {\n locate?: LocateResultElement;\n};\n\nexport const defineActionClearInput = (\n clearInput: KeyboardInputPrimitives['clearInput'],\n): DeviceAction<ActionClearInputParam> => {\n return defineAction<\n typeof actionClearInputParamSchema,\n ActionClearInputParam\n >({\n name: 'ClearInput',\n description: inputLocateDescription,\n interfaceAlias: 'aiClearInput',\n paramSchema: actionClearInputParamSchema,\n sample: {\n locate: { prompt: 'the search input field' },\n },\n call: async (param) => {\n await clearInput(param.locate);\n },\n });\n};\n\n// CursorMove\nexport const actionCursorMoveParamSchema = z.object({\n direction: z\n .enum(['left', 'right'])\n .describe('The direction to move the cursor'),\n times: z\n .number()\n .int()\n .min(1)\n .default(1)\n .describe(\n 'The number of times to move the cursor in the specified direction',\n ),\n});\nexport type ActionCursorMoveParam = {\n direction: 'left' | 'right';\n times?: number;\n};\n\nexport const defineActionCursorMove = (config: {\n keyboard: Pick<KeyboardInputPrimitives, 'keyboardPress' | 'cursorMove'>;\n sleep?(timeMs: number): Promise<void>;\n}): DeviceAction<ActionCursorMoveParam> => {\n return defineAction<\n typeof actionCursorMoveParamSchema,\n ActionCursorMoveParam\n >({\n name: 'CursorMove',\n description:\n 'Move the text cursor (caret) left or right within an input field or text area. Use this to reposition the cursor without selecting text.',\n paramSchema: actionCursorMoveParamSchema,\n sample: {\n direction: 'left',\n times: 3,\n },\n call: async (param) => {\n const times = param.times ?? 1;\n if (config.keyboard.cursorMove) {\n await config.keyboard.cursorMove(param.direction, times);\n return;\n }\n\n const wait =\n config.sleep ??\n ((timeMs: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, timeMs)));\n const arrowKey = param.direction === 'left' ? 'ArrowLeft' : 'ArrowRight';\n for (let i = 0; i < times; i++) {\n await config.keyboard.keyboardPress(arrowKey);\n await wait(100);\n }\n },\n });\n};\n\n// Pinch\nexport const ActionPinchParamSchema = z.object({\n locate: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'The element to pinch on. If not specified, the center of the screen will be used',\n ),\n direction: z\n .enum(['in', 'out'])\n .describe(\n 'Pinch direction. \"in\" = pinch fingers together (zoom out / shrink), \"out\" = spread fingers apart (zoom in / enlarge).',\n ),\n distance: z\n .number()\n .positive()\n .optional()\n .describe(\n 'How far each finger moves in pixels. Defaults to a quarter of the shorter screen dimension.',\n ),\n duration: z\n .number()\n .default(500)\n .optional()\n .describe('Duration of the pinch gesture in milliseconds'),\n});\n\nexport type ActionPinchParam = {\n locate?: LocateResultElement;\n direction: 'in' | 'out';\n distance?: number;\n duration?: number;\n};\n\nexport const defineActionPinch = (config: {\n pinch: TouchInputPrimitives['pinch'];\n size(): Promise<Size>;\n}): DeviceAction<ActionPinchParam> | undefined => {\n if (!config.pinch) {\n return undefined;\n }\n\n return defineAction<typeof ActionPinchParamSchema, ActionPinchParam>({\n name: 'Pinch',\n description:\n 'Perform a two-finger pinch gesture. Use direction \"in\" to pinch fingers together (zoom out), or \"out\" to spread fingers apart (zoom in). Optionally specify distance for how far each finger moves.',\n interfaceAlias: 'aiPinch',\n paramSchema: ActionPinchParamSchema,\n sample: {\n locate: { prompt: 'the map area' },\n direction: 'out',\n distance: 200,\n },\n call: async (param) => {\n const { centerX, centerY, startDistance, endDistance, duration } =\n normalizePinchParam(param, await config.size());\n await config.pinch?.(\n { x: centerX, y: centerY },\n { startDistance, endDistance, duration },\n );\n },\n });\n};\n\nexport function normalizePinchParam(\n param: ActionPinchParam,\n screenSize: { width: number; height: number },\n): {\n centerX: number;\n centerY: number;\n startDistance: number;\n endDistance: number;\n duration: number;\n} {\n const { width, height } = screenSize;\n const element = param.locate;\n const centerX = element\n ? Math.round(element.center[0])\n : Math.round(width / 2);\n const centerY = element\n ? Math.round(element.center[1])\n : Math.round(height / 2);\n const duration = param.duration ?? 500;\n\n const baseDistance = Math.round(Math.min(width, height) / 4);\n const fingerDistance = param.distance ?? baseDistance;\n\n const startDistance = baseDistance;\n const endDistance =\n param.direction === 'out'\n ? baseDistance + fingerDistance\n : Math.max(10, baseDistance - fingerDistance);\n\n return { centerX, centerY, startDistance, endDistance, duration };\n}\n\nexport interface MobileInputActionContext {\n input: MobileInputPrimitives;\n size(): Promise<Size>;\n sleep?(timeMs: number): Promise<void>;\n getDefaultAutoDismissKeyboard?(): boolean | undefined;\n systemActions?: SystemInputActionOptions;\n}\n\nexport interface SystemInputActionConfig {\n name: string;\n description: string;\n interfaceAlias?: string;\n delayBeforeRunner?: number;\n delayAfterRunner?: number;\n}\n\nexport interface SystemInputActionOptions {\n backButton?: SystemInputActionConfig;\n homeButton?: SystemInputActionConfig;\n recentAppsButton?: SystemInputActionConfig;\n}\n\nexport interface InputPrimitiveActionOptions {\n size?: () => Promise<Size>;\n sleep?: (timeMs: number) => Promise<void>;\n includeSwipe?: boolean;\n includePinch?: boolean;\n systemActions?: SystemInputActionOptions;\n}\n\nfunction defineSystemInputAction(\n config: SystemInputActionConfig,\n call: () => Promise<void>,\n): DeviceAction<undefined, void> {\n return defineAction<undefined, undefined, void>({\n name: config.name,\n description: config.description,\n interfaceAlias: config.interfaceAlias,\n delayBeforeRunner: config.delayBeforeRunner,\n delayAfterRunner: config.delayAfterRunner,\n call,\n });\n}\n\nexport function defineActionsFromInputPrimitives(\n input: InputPrimitives,\n options: InputPrimitiveActionOptions = {},\n): DeviceAction<any>[] {\n const actions: Array<DeviceAction<any> | undefined> = [];\n const { pointer, keyboard, scroll, touch, system } = input;\n\n if (pointer) {\n actions.push(defineActionTap(pointer.tap));\n if (pointer.doubleClick) {\n actions.push(defineActionDoubleClick(pointer.doubleClick));\n }\n if (pointer.rightClick) {\n actions.push(defineActionRightClick(pointer.rightClick));\n }\n if (pointer.hover) {\n actions.push(defineActionHover(pointer.hover));\n }\n if (pointer.dragAndDrop) {\n actions.push(defineActionDragAndDrop(pointer.dragAndDrop));\n }\n if (pointer.longPress) {\n actions.push(defineActionLongPress(pointer.longPress));\n }\n }\n\n if (keyboard) {\n actions.push(\n defineActionInput(keyboard),\n defineActionClearInput(keyboard.clearInput),\n defineActionKeyboardPress(keyboard.keyboardPress),\n defineActionCursorMove({ keyboard, sleep: options.sleep }),\n );\n }\n\n if (scroll) {\n actions.push(defineActionScroll(scroll.scroll));\n }\n\n if (touch?.swipe && options.size && options.includeSwipe !== false) {\n actions.push(defineActionSwipe({ swipe: touch.swipe, size: options.size }));\n }\n\n if (touch?.pinch && options.size && options.includePinch !== false) {\n actions.push(defineActionPinch({ pinch: touch.pinch, size: options.size }));\n }\n\n if (system && options.systemActions) {\n const { systemActions } = options;\n if (system.backButton && systemActions.backButton) {\n actions.push(\n defineSystemInputAction(systemActions.backButton, system.backButton),\n );\n }\n if (system.homeButton && systemActions.homeButton) {\n actions.push(\n defineSystemInputAction(systemActions.homeButton, system.homeButton),\n );\n }\n if (system.recentAppsButton && systemActions.recentAppsButton) {\n actions.push(\n defineSystemInputAction(\n systemActions.recentAppsButton,\n system.recentAppsButton,\n ),\n );\n }\n }\n\n return actions.filter((action): action is DeviceAction<any> =>\n Boolean(action),\n );\n}\n\nexport function createDefaultMobileActions(\n context: MobileInputActionContext,\n): DeviceAction<any>[] {\n return defineActionsFromInputPrimitives(context.input, {\n size: context.size,\n sleep: context.sleep,\n systemActions: context.systemActions,\n });\n}\n\n// Sleep\nexport const ActionSleepParamSchema = z.object({\n timeMs: z\n .number()\n .default(1000)\n .optional()\n .describe('Sleep duration in milliseconds, defaults to 1000ms (1 second)'),\n});\n\nexport type ActionSleepParam = {\n timeMs?: number;\n};\n\nexport const defineActionSleep = (): DeviceAction<ActionSleepParam> => {\n return defineAction<typeof ActionSleepParamSchema, ActionSleepParam>({\n name: 'Sleep',\n description:\n 'Wait for a specified duration before continuing. Defaults to 1 second (1000ms) if not specified.',\n paramSchema: ActionSleepParamSchema,\n sample: {\n timeMs: 2000,\n },\n call: async (param) => {\n const duration = param?.timeMs ?? 1000;\n getDebug('device:common-action')(`Sleeping for ${duration}ms`);\n await new Promise((resolve) => setTimeout(resolve, duration));\n },\n });\n};\n\nexport type { DeviceAction } from '../types';\nexport {\n inputStrategies,\n type InputStrategy,\n type ResolvedTextInputOptions,\n type SequentialTextInputHandlers,\n type TextInputOptions,\n resolveInputStrategy,\n resolveTextInputOptions,\n sendTextSequentially,\n shouldInputSequentially,\n} from './input-strategy';\nexport type {\n AndroidDeviceOpt,\n AndroidDeviceInputOpt,\n IOSDeviceOpt,\n IOSDeviceInputOpt,\n HarmonyDeviceOpt,\n HarmonyDeviceInputOpt,\n} from './device-options';\n"],"names":["AbstractInterface","defineAction","config","pointFromLocate","locate","missingMessage","Error","defineLocatedPointAction","param","actionTapParamSchema","z","getMidsceneLocationSchema","defineActionTap","tap","point","registerFileChooserAcceptParamSchema","defineActionRegisterFileChooserAccept","register","actionRightClickParamSchema","defineActionRightClick","rightClick","actionDoubleClickParamSchema","defineActionDoubleClick","doubleClick","actionHoverParamSchema","defineActionHover","hover","inputLocateDescription","actionInputParamSchema","val","String","inputStrategies","defineActionInput","keyboard","actionKeyboardPressParamSchema","defineActionKeyboardPress","keyboardPress","actionScrollParamSchema","defineActionScroll","scroll","actionDragAndDropParamSchema","defineActionDragAndDrop","dragAndDrop","from","to","ActionLongPressParamSchema","defineActionLongPress","longPress","ActionSwipeParamSchema","normalizeMobileSwipeParam","screenSize","width","height","start","end","startPoint","endPoint","undefined","Math","duration","repeatCount","defineActionSwipe","i","actionClearInputParamSchema","defineActionClearInput","clearInput","actionCursorMoveParamSchema","defineActionCursorMove","times","wait","timeMs","Promise","resolve","setTimeout","arrowKey","ActionPinchParamSchema","defineActionPinch","centerX","centerY","startDistance","endDistance","normalizePinchParam","element","baseDistance","fingerDistance","defineSystemInputAction","call","defineActionsFromInputPrimitives","input","options","actions","pointer","touch","system","systemActions","action","Boolean","createDefaultMobileActions","context","ActionSleepParamSchema","defineActionSleep","getDebug"],"mappings":";;;;;;;;;;;;;;AA6KO,MAAeA;;QAgDpB;QAqDA;;AACF;AAKO,MAAMC,eAAe,CAK1BC,SAgBOA;AAGT,SAASC,gBACPC,MAAuC,EACvCC,cAAsB;IAEtB,IAAI,CAACD,QACH,MAAM,IAAIE,MAAMD;IAElB,OAAO;QAAE,GAAGD,OAAO,MAAM,CAAC,EAAE;QAAE,GAAGA,OAAO,MAAM,CAAC,EAAE;IAAC;AACpD;AAEA,SAASG,yBAGPL,MAQD;IACC,OAAOD,aAA8B;QACnC,MAAMC,OAAO,IAAI;QACjB,aAAaA,OAAO,WAAW;QAC/B,gBAAgBA,OAAO,cAAc;QACrC,aAAaA,OAAO,WAAW;QAC/B,QAAQA,OAAO,MAAM;QACrB,MAAM,OAAOM;YACX,MAAMN,OAAO,IAAI,CACfC,gBAAgBK,MAAM,MAAM,EAAEN,OAAO,oBAAoB,GACzDM;QAEJ;IACF;AACF;AAGO,MAAMC,uBAAuBC,EAAE,MAAM,CAAC;IAC3C,QAAQC,4BAA4B,QAAQ,CAAC;AAC/C;AAKO,MAAMC,kBAAkB,CAC7BC,MAEON,yBAAsE;QAC3E,MAAM;QACN,aAAa;QACb,gBAAgB;QAChB,aAAaE;QACb,QAAQ;YACN,QAAQ;gBAAE,QAAQ;YAAsB;QAC1C;QACA,sBAAsB;QACtB,MAAM,OA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BS,cAAc,UAAU,EAAED,OAAO,UAAU;QAGvE,IAAIA,OAAO,gBAAgB,IAAIC,cAAc,gBAAgB,EAC3DJ,QAAQ,IAAI,CACVL,wBACES,cAAc,gBAAgB,EAC9BD,OAAO,gBAAgB;IAI/B;IAEA,OAAOH,QAAQ,MAAM,CAAC,CAACK,SACrBC,QAAQD;AAEZ;AAEO,SAASE,2BACdC,OAAiC;IAEjC,OAAOX,iCAAiCW,QAAQ,KAAK,EAAE;QACrD,MAAMA,QAAQ,IAAI;QAClB,OAAOA,QAAQ,KAAK;QACpB,eAAeA,QAAQ,aAAa;IACtC;AACF;AAGO,MAAMC,yBAAyBzF,EAAE,MAAM,CAAC;IAC7C,QAAQA,EAAAA,MACC,GACN,OAAO,CAAC,MACR,QAAQ,GACR,QAAQ,CAAC;AACd;AAMO,MAAM0F,oBAAoB,IACxBnG,aAA8D;QACnE,MAAM;QACN,aACE;QACF,aAAakG;QACb,QAAQ;YACN,QAAQ;QACV;QACA,MAAM,OAAO3F;YACX,MAAMmD,WAAWnD,OAAO,UAAU;YAClC6F,SAAS,wBAAwB,CAAC,aAAa,EAAE1C,SAAS,EAAE,CAAC;YAC7D,MAAM,IAAIY,QAAQ,CAACC,UAAYC,WAAWD,SAASb;QACrD;IACF"}
1
+ {"version":3,"file":"device/index.mjs","sources":["../../../src/device/index.ts"],"sourcesContent":["import type { ModelRuntime } from '@/ai-model/models';\nimport { getMidsceneLocationSchema } from '@/common';\nimport type {\n ActionScrollParam,\n DeviceAction,\n ExecutorContext,\n LocateResultElement,\n} from '@/types';\nimport type { ElementNode } from '@midscene/shared/extractor';\nimport { getDebug } from '@midscene/shared/logger';\nimport { _keyDefinitions } from '@midscene/shared/us-keyboard-layout';\nimport { z } from 'zod';\nimport type {\n ElementCacheFeature,\n Rect,\n Size,\n UIContext,\n UITreeSnapshot,\n} from '../types';\nimport { type InputStrategy, inputStrategies } from './input-strategy';\n\nexport interface FileChooserHandler {\n accept(files: string[]): Promise<void>;\n}\n\nexport interface FileChooserRegistration {\n dispose: () => void;\n getError: () => Error | undefined | Promise<Error | undefined>;\n}\n\nexport interface MjpegStreamFrame {\n /** Raw base64-encoded image bytes WITHOUT a `data:image/...;base64,` prefix. */\n data: string;\n contentType?: string;\n}\n\nexport interface MjpegStreamHandle {\n stop(): void | Promise<void>;\n}\n\nexport interface MjpegStreamOptions {\n signal?: AbortSignal;\n onFrame(frame: MjpegStreamFrame): void;\n onError?(error: unknown): void;\n}\n\n/**\n * A cheap, not-yet-decoded handle to one screen frame from a\n * {@link DeviceFrameSource}. `ref` is platform-specific (a raw H.264 keyframe\n * buffer on Android, an already-encoded JPEG data URL on iOS/web) and must not\n * be interpreted by callers — pass it back to `decode()` to materialize.\n */\nexport interface DeviceFrameRef {\n ref: unknown;\n capturedAt: number;\n}\n\n/**\n * A continuous screen-frame source opened via\n * {@link AbstractInterface.openFrameSource}. Designed for deferred decoding:\n * grabbing `latest()` is near-zero cost, so observers can sample at a steady\n * cadence and pay any decode cost only once, for the frames they keep.\n */\nexport interface DeviceFrameSource {\n /** Latest frame handle, near-zero cost. Null until the first frame arrives. */\n latest(): DeviceFrameRef | null;\n /**\n * Materialize frame handles into `data:image/...;base64,` URLs, preserving\n * order. Possibly expensive (e.g. one ffmpeg run per unique frame on\n * Android) — call once with the sampled handles, never per tick.\n */\n decode(refs: DeviceFrameRef[]): Promise<string[]>;\n /** Release the source (stop streams/subscriptions it started). */\n stop(): Promise<void> | void;\n}\n\n/** A point in device-pixel coordinates on the screen. */\nexport interface PointerPoint {\n x: number;\n y: number;\n}\n\nexport interface PointerInputPrimitives {\n tap(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n doubleClick?(p: PointerPoint): Promise<void>;\n rightClick?(p: PointerPoint): Promise<void>;\n hover?(p: PointerPoint): Promise<void>;\n longPress?(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n dragAndDrop?(from: PointerPoint, to: PointerPoint): Promise<void>;\n}\n\nexport interface TouchInputPrimitives {\n swipe(\n start: PointerPoint,\n end: PointerPoint,\n opts?: { duration?: number; repeat?: number },\n ): Promise<void>;\n pinch?(\n center: PointerPoint,\n opts: { startDistance: number; endDistance: number; duration: number },\n ): Promise<void>;\n}\n\nexport interface KeyboardInputPrimitives {\n keyboardPress(keyName: string, opts?: { target?: unknown }): Promise<void>;\n cursorMove?(direction: 'left' | 'right', times?: number): Promise<void>;\n typeText(\n value: string,\n opts?: {\n autoDismissKeyboard?: boolean;\n keyboardDismissStrategy?: 'esc-first' | 'back-first';\n keyboardTypeDelay?: number;\n inputStrategy?: InputStrategy;\n target?: unknown;\n replace?: boolean;\n focusOnly?: boolean;\n },\n ): Promise<void>;\n clearInput(target?: unknown): Promise<void>;\n}\n\nexport interface ScrollInputPrimitives {\n scroll(param: ActionScrollParam): Promise<void>;\n}\n\nexport interface SystemInputPrimitives {\n backButton?(): Promise<void>;\n homeButton?(): Promise<void>;\n recentAppsButton?(): Promise<void>;\n}\n\nexport interface InputPrimitives {\n pointer?: PointerInputPrimitives;\n keyboard?: KeyboardInputPrimitives;\n touch?: TouchInputPrimitives;\n scroll?: ScrollInputPrimitives;\n system?: SystemInputPrimitives;\n}\n\nexport interface MobileInputPrimitives extends InputPrimitives {\n pointer: PointerInputPrimitives & {\n doubleClick(p: PointerPoint): Promise<void>;\n longPress(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n dragAndDrop(from: PointerPoint, to: PointerPoint): Promise<void>;\n };\n keyboard: KeyboardInputPrimitives;\n touch: TouchInputPrimitives;\n}\n\nexport interface BrowserInputPrimitives extends InputPrimitives {\n pointer: PointerInputPrimitives & {\n doubleClick(p: PointerPoint): Promise<void>;\n rightClick(p: PointerPoint): Promise<void>;\n hover(p: PointerPoint): Promise<void>;\n dragAndDrop(from: PointerPoint, to: PointerPoint): Promise<void>;\n longPress(p: PointerPoint, opts?: { duration?: number }): Promise<void>;\n };\n keyboard: KeyboardInputPrimitives;\n scroll: ScrollInputPrimitives;\n touch: TouchInputPrimitives;\n}\n\nexport interface ComputerInputPrimitives extends InputPrimitives {\n pointer: PointerInputPrimitives & {\n doubleClick(p: PointerPoint): Promise<void>;\n rightClick(p: PointerPoint): Promise<void>;\n hover(p: PointerPoint): Promise<void>;\n dragAndDrop(from: PointerPoint, to: PointerPoint): Promise<void>;\n };\n keyboard: KeyboardInputPrimitives;\n scroll: ScrollInputPrimitives;\n}\n\nexport abstract class AbstractInterface {\n abstract interfaceType: string;\n\n abstract screenshotBase64(): Promise<string>;\n abstract size(): Promise<Size>;\n abstract actionSpace(): DeviceAction[];\n\n abstract cacheFeatureForPoint?(\n center: [number, number],\n options?: {\n targetDescription?: string;\n modelRuntime?: ModelRuntime;\n },\n ): Promise<ElementCacheFeature>;\n abstract rectMatchesCacheFeature?(\n feature: ElementCacheFeature,\n ): Promise<Rect>;\n\n abstract getUITree?(): Promise<UITreeSnapshot>;\n\n abstract destroy?(): Promise<void>;\n\n abstract describe?(): string;\n abstract beforeInvokeAction?(actionName: string, param: any): Promise<void>;\n abstract afterInvokeAction?(actionName: string, param: any): Promise<void>;\n\n // for web only\n registerFileChooserListener?(\n handler: (chooser: FileChooserHandler) => Promise<void>,\n ): Promise<FileChooserRegistration>;\n\n // @deprecated do NOT extend this method\n abstract getElementsNodeTree?: () => Promise<ElementNode>;\n\n // @deprecated do NOT extend this method\n abstract url?: () => string | Promise<string>;\n\n // @deprecated do NOT extend this method\n abstract evaluateJavaScript?<T = any>(script: string): Promise<T>;\n\n /**\n * Get the current device-local time as a formatted string.\n * Prefer this for user-visible time because timestamps alone do not preserve\n * the target device's timezone when formatted on the host machine.\n */\n getDeviceLocalTimeString?(format?: string): Promise<string>;\n\n /** URL of native MJPEG stream for real-time screen preview (e.g. WDA MJPEG server) */\n mjpegStreamUrl?: string;\n\n /**\n * Optional continuous frame source for UI observation (`startObserving`).\n * Devices that maintain a continuous frame stream — scrcpy on Android, WDA\n * MJPEG on iOS, CDP screencast on web — implement this so an observer can\n * sample the screen far faster than repeated `screenshotBase64()` calls,\n * catching short-lived UI (toasts, carousels, transitions).\n *\n * The contract enables DEFERRED decoding: `latest()` returns a cheap opaque\n * handle (e.g. a raw H.264 keyframe on Android) with no per-frame decode\n * cost, and `decode()` materializes only the handles that were actually\n * sampled — once, at the end of the observation window.\n */\n openFrameSource?(): Promise<DeviceFrameSource | undefined>;\n\n /**\n * Optional in-process MJPEG frame producer. Implementations can push raw\n * base64 frames here when there is no standalone native MJPEG URL, e.g.\n * Chromium CDP Page.startScreencast for web previews.\n */\n startMjpegStream?(\n options: MjpegStreamOptions,\n ): MjpegStreamHandle | undefined | Promise<MjpegStreamHandle | undefined>;\n\n /**\n * Optional hook used after a UI action to push a fresh frame on the active\n * MJPEG stream. Set `force` after navigation to replace a transient loading\n * frame even when the screencast has already emitted one. Implementations\n * should be a no-op when no stream is active.\n */\n flushPendingVisualUpdate?(force?: boolean): Promise<void>;\n\n /**\n * Optional non-blocking variant of `flushPendingVisualUpdate`. Keyboard-\n * heavy preview interactions can schedule a coalesced refresh here without\n * stalling the input hot path; `force` preserves a requested navigation\n * refresh while work is already queued.\n */\n schedulePendingVisualUpdate?(force?: boolean): void;\n\n /**\n * Optional navigation state probe for browser-like interfaces, used to drive\n * loading indicators in playground UIs. Returning `undefined` means the\n * interface does not expose this concept.\n */\n navigationState?(): Promise<{ isLoading: boolean }>;\n\n /**\n * Low-level device input surface. Platform implementations expose transport\n * primitives here; higher-level AI actions and manual pointer dispatch should\n * adapt to this instead of duplicating platform gesture logic.\n */\n inputPrimitives?: InputPrimitives;\n}\n\n// Generic function to define actions with proper type inference\n// TRuntime allows specifying a different type for the runtime parameter (after location resolution)\n// TReturn allows specifying the return type of the action\nexport const defineAction = <\n TSchema extends z.ZodType | undefined = undefined,\n TRuntime = TSchema extends z.ZodType ? z.infer<TSchema> : undefined,\n TReturn = any,\n>(\n config: {\n name: string;\n description: string;\n interfaceAlias?: string;\n paramSchema?: TSchema;\n call: (\n param: TRuntime,\n context?: ExecutorContext,\n ) => Promise<TReturn> | TReturn;\n } & Partial<\n Omit<\n DeviceAction<TRuntime, TReturn>,\n 'name' | 'description' | 'interfaceAlias' | 'paramSchema' | 'call'\n >\n >,\n): DeviceAction<TRuntime, TReturn> => {\n return config as any; // Type assertion needed because schema validation type differs from runtime type\n};\n\nfunction pointFromLocate(\n locate: LocateResultElement | undefined,\n missingMessage: string,\n): PointerPoint {\n if (!locate) {\n throw new Error(missingMessage);\n }\n return { x: locate.center[0], y: locate.center[1] };\n}\n\nfunction defineLocatedPointAction<\n TSchema extends z.ZodType,\n TParam extends { locate: LocateResultElement },\n>(config: {\n name: string;\n description: string;\n interfaceAlias?: string;\n paramSchema: TSchema;\n sample: DeviceAction<TParam>['sample'];\n missingLocateMessage: string;\n call: (point: PointerPoint, param: TParam) => Promise<void>;\n}): DeviceAction<TParam> {\n return defineAction<TSchema, TParam>({\n name: config.name,\n description: config.description,\n interfaceAlias: config.interfaceAlias,\n paramSchema: config.paramSchema,\n sample: config.sample,\n call: async (param) => {\n await config.call(\n pointFromLocate(param.locate, config.missingLocateMessage),\n param,\n );\n },\n });\n}\n\n// Tap\nexport const actionTapParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe('The element to be tapped'),\n});\nexport type ActionTapParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionTap = (\n tap: PointerInputPrimitives['tap'],\n): DeviceAction<ActionTapParam> => {\n return defineLocatedPointAction<typeof actionTapParamSchema, ActionTapParam>({\n name: 'Tap',\n description: 'Tap the element',\n interfaceAlias: 'aiTap',\n paramSchema: actionTapParamSchema,\n sample: {\n locate: { prompt: 'the \"Submit\" button' },\n },\n missingLocateMessage: 'Element not found, cannot tap',\n call: async (point) => {\n await tap(point);\n },\n });\n};\n\nexport const registerFileChooserAcceptParamSchema = z.object({\n files: z\n .union([z.string(), z.array(z.string())])\n .describe(\n \"File path(s) within the current aiAct call's fileChooserAllowedDir to use whenever a later action triggers a file chooser. fileChooserAllowedDir must be provided for this action. This setting replaces any previously registered file path(s).\",\n ),\n});\nexport type RegisterFileChooserAcceptParam = {\n files: string | string[];\n};\n\nexport const defineActionRegisterFileChooserAccept = (\n register: (files: string | string[]) => Promise<void>,\n): DeviceAction<RegisterFileChooserAcceptParam> => {\n return defineAction<\n typeof registerFileChooserAcceptParamSchema,\n RegisterFileChooserAcceptParam\n >({\n name: 'RegisterFileChooserAccept',\n description:\n 'Configure files for file chooser dialogs triggered by later actions in this aiAct',\n interfaceAlias: 'registerFileChooserAccept',\n paramSchema: registerFileChooserAcceptParamSchema,\n sample: {\n files: ['fixtures/document.pdf'],\n },\n call: async (param) => {\n await register(param.files);\n },\n });\n};\n\n// RightClick\nexport const actionRightClickParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe(\n 'The element to be right clicked',\n ),\n});\nexport type ActionRightClickParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionRightClick = (\n rightClick: NonNullable<PointerInputPrimitives['rightClick']>,\n): DeviceAction<ActionRightClickParam> => {\n return defineLocatedPointAction<\n typeof actionRightClickParamSchema,\n ActionRightClickParam\n >({\n name: 'RightClick',\n description: 'Right click the element',\n interfaceAlias: 'aiRightClick',\n paramSchema: actionRightClickParamSchema,\n sample: {\n locate: { prompt: 'the file icon on the desktop' },\n },\n missingLocateMessage: 'Element not found, cannot right click',\n call: async (point) => {\n await rightClick(point);\n },\n });\n};\n\n// DoubleClick\nexport const actionDoubleClickParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe(\n 'The element to be double clicked',\n ),\n});\nexport type ActionDoubleClickParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionDoubleClick = (\n doubleClick: NonNullable<PointerInputPrimitives['doubleClick']>,\n): DeviceAction<ActionDoubleClickParam> => {\n return defineLocatedPointAction<\n typeof actionDoubleClickParamSchema,\n ActionDoubleClickParam\n >({\n name: 'DoubleClick',\n description: 'Double click the element',\n interfaceAlias: 'aiDoubleClick',\n paramSchema: actionDoubleClickParamSchema,\n sample: {\n locate: { prompt: 'the folder icon' },\n },\n missingLocateMessage: 'Element not found, cannot double click',\n call: async (point) => {\n await doubleClick(point);\n },\n });\n};\n\n// Hover\nexport const actionHoverParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe('The element to be hovered'),\n});\nexport type ActionHoverParam = {\n locate: LocateResultElement;\n};\n\nexport const defineActionHover = (\n hover: NonNullable<PointerInputPrimitives['hover']>,\n): DeviceAction<ActionHoverParam> => {\n return defineLocatedPointAction<\n typeof actionHoverParamSchema,\n ActionHoverParam\n >({\n name: 'Hover',\n description: 'Move the mouse to the element',\n interfaceAlias: 'aiHover',\n paramSchema: actionHoverParamSchema,\n sample: {\n locate: { prompt: 'the navigation menu item \"Products\"' },\n },\n missingLocateMessage: 'Element not found, cannot hover',\n call: async (point) => {\n await hover(point);\n },\n });\n};\n\n// Input\nconst inputLocateDescription =\n 'the position of the placeholder or text content in the target input field. If there is no content, locate the center of the input field.';\nexport const actionInputParamSchema = z.object({\n value: z\n .union([z.string(), z.number()])\n .transform((val) => String(val))\n .describe(\n 'The text to input. Provide the final content for replace mode, only the inserted characters for typeOnly mode, or an empty string when using clear mode to remove existing text.',\n ),\n locate: getMidsceneLocationSchema()\n .describe(inputLocateDescription)\n .optional(),\n mode: z\n .enum(['replace', 'clear', 'typeOnly'])\n .default('replace')\n .describe(\n 'Input mode: \"replace\" (default) - clear the field and input the value; \"typeOnly\" - type the value directly without clearing the field first, and should be set explicitly for incremental edits after moving the cursor; \"clear\" - clear the field without inputting new text.',\n ),\n autoDismissKeyboard: z\n .boolean()\n .optional()\n .describe(\n 'If true, the keyboard will be dismissed after the input is completed. Do not set it unless the user asks you to do so.',\n ),\n keyboardTypeDelay: z\n .number()\n .finite()\n .nonnegative()\n .optional()\n .describe(\n 'Delay in milliseconds between keystrokes when typing. Passed through from device/user configuration. Do not set it unless the user asks you to do so.',\n ),\n inputStrategy: z\n .enum(inputStrategies)\n .optional()\n .describe(\n 'Text input strategy: \"legacy\" (default) preserves the current platform behavior; \"sequential\" enters one Unicode code point at a time; \"bulk\" sends the complete text through one platform input operation when supported and requires keyboardTypeDelay to be omitted or set to 0. Do not set it unless the user asks you to do so.',\n ),\n});\nexport type ActionInputParam = {\n value: string;\n locate?: LocateResultElement;\n mode?: 'replace' | 'clear' | 'typeOnly' | 'append';\n autoDismissKeyboard?: boolean;\n keyboardTypeDelay?: number;\n inputStrategy?: InputStrategy;\n};\n\nexport const defineActionInput = (\n keyboard: KeyboardInputPrimitives,\n): DeviceAction<ActionInputParam> => {\n return defineAction<typeof actionInputParamSchema, ActionInputParam>({\n name: 'Input',\n description: 'Input the value into the element',\n interfaceAlias: 'aiInput',\n paramSchema: actionInputParamSchema,\n sample: {\n value: 'test@example.com',\n locate: { prompt: 'the email input field' },\n },\n call: async (param) => {\n // backward compat: convert deprecated 'append' to 'typeOnly'\n if ((param.mode as string) === 'append') {\n param.mode = 'typeOnly';\n }\n\n if (param.mode === 'clear') {\n await keyboard.clearInput(param.locate);\n return;\n }\n\n if (!param || !param.value) {\n return;\n }\n\n await keyboard.typeText(param.value, {\n target: param.locate,\n replace: param.mode !== 'typeOnly',\n autoDismissKeyboard: param.autoDismissKeyboard,\n keyboardTypeDelay: param.keyboardTypeDelay,\n inputStrategy: param.inputStrategy,\n });\n },\n });\n};\n\n// KeyboardPress\nexport const actionKeyboardPressParamSchema = z.object({\n locate: getMidsceneLocationSchema()\n .describe(\n 'The optional element to click before pressing the key. Omit this when the key should operate on the currently focused element, especially when copying or cutting an existing text selection.',\n )\n .optional(),\n keyName: z\n .string()\n .describe(\n \"The key to be pressed. Use '+' for key combinations, e.g., 'Control+A', 'Shift+Enter'\",\n ),\n});\nexport type ActionKeyboardPressParam = {\n locate?: LocateResultElement;\n keyName: string;\n};\n\nexport const defineActionKeyboardPress = (\n keyboardPress: KeyboardInputPrimitives['keyboardPress'],\n): DeviceAction<ActionKeyboardPressParam> => {\n return defineAction<\n typeof actionKeyboardPressParamSchema,\n ActionKeyboardPressParam\n >({\n name: 'KeyboardPress',\n description:\n 'Press a key or key combination, like \"Enter\", \"Tab\", \"Escape\", or \"Control+A\", \"Shift+Enter\". Do not use this to type text. Omit locate to operate on the current focus without clicking again, especially for Copy or Cut after text has been selected.',\n interfaceAlias: 'aiKeyboardPress',\n paramSchema: actionKeyboardPressParamSchema,\n sample: {\n keyName: 'Enter',\n },\n call: async (param) => {\n await keyboardPress(param.keyName, {\n target: param.locate,\n });\n },\n });\n};\n\n// Scroll\nexport const actionScrollParamSchema = z.object({\n scrollType: z\n .enum([\n 'singleAction',\n 'scrollToBottom',\n 'scrollToTop',\n 'scrollToRight',\n 'scrollToLeft',\n ])\n .default('singleAction')\n .describe(\n 'The scroll behavior: \"singleAction\" for a single scroll action, \"scrollToBottom\" for scrolling all the way to the bottom by rapidly scrolling 5-10 times (skipping intermediate content until reaching the bottom), \"scrollToTop\" for scrolling all the way to the top by rapidly scrolling 5-10 times (skipping intermediate content until reaching the top), \"scrollToRight\" for scrolling all the way to the right by rapidly scrolling multiple times, \"scrollToLeft\" for scrolling all the way to the left by rapidly scrolling multiple times',\n ),\n direction: z\n .enum(['down', 'up', 'right', 'left'])\n .default('down')\n .describe(\n 'The direction toward the off-screen content to reveal. \"down\" reveals content below the current viewport, \"up\" reveals content above, \"right\" reveals content to the right, and \"left\" reveals content to the left. This does not describe the movement direction of the content currently visible on the screen. Only effective when scrollType is \"singleAction\".',\n ),\n distance: z\n .number()\n .positive()\n .nullable()\n .optional()\n .describe(\n 'Positive requested scroll amount in screen-coordinate units. On touch platforms, it controls the length of the swipe gesture used to scroll; on web and desktop platforms, it controls or approximates the wheel scroll delta. Only effective when scrollType is \"singleAction\".',\n ),\n locate: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'Describe the target element to be scrolled on, like \"the table\" or \"the list\" or \"the content area\" or \"the scrollable area\". Do NOT provide a general intent like \"scroll to find some element\"',\n ),\n});\n\nexport const defineActionScroll = (\n scroll: ScrollInputPrimitives['scroll'],\n): DeviceAction<ActionScrollParam> => {\n return defineAction<typeof actionScrollParamSchema, ActionScrollParam>({\n name: 'Scroll',\n description:\n 'Scroll a page or scrollable region to reveal off-screen content. Use Scroll when the goal is to browse content outside the current viewport. For direct gesture interactions, such as adjusting a slider or wheel picker, switching between paged cards or images, following an on-screen swipe gesture to continue or dismiss, or swiping an item to delete it, use Swipe instead if available in the current Action Space. Supports scrollToBottom/scrollToTop for boundary navigation. Default: direction `down`, scrollType `singleAction`, distance `null`.',\n interfaceAlias: 'aiScroll',\n paramSchema: actionScrollParamSchema,\n sample: {\n direction: 'down',\n scrollType: 'singleAction',\n locate: { prompt: 'the center of the product list area' },\n },\n call: async (param) => {\n await scroll(param);\n },\n });\n};\n\n// DragAndDrop\nexport const actionDragAndDropParamSchema = z.object({\n from: getMidsceneLocationSchema().describe('The position to be dragged'),\n to: getMidsceneLocationSchema().describe('The position to be dropped'),\n});\nexport type ActionDragAndDropParam = {\n from: LocateResultElement;\n to: LocateResultElement;\n};\n\nexport const defineActionDragAndDrop = (\n dragAndDrop: NonNullable<PointerInputPrimitives['dragAndDrop']>,\n): DeviceAction<ActionDragAndDropParam> => {\n return defineAction<\n typeof actionDragAndDropParamSchema,\n ActionDragAndDropParam\n >({\n name: 'DragAndDrop',\n description:\n 'Pick up a specific UI element and move it to a new position (e.g., reorder a card, move a file into a folder, sort list items). The element itself moves with your finger/mouse.',\n interfaceAlias: 'aiDragAndDrop',\n paramSchema: actionDragAndDropParamSchema,\n sample: {\n from: { prompt: 'the \"report.pdf\" file icon' },\n to: { prompt: 'the upload drop zone' },\n },\n call: async (param) => {\n const from = param.from;\n const to = param.to;\n if (!from) {\n throw new Error('missing \"from\" param for drag and drop');\n }\n if (!to) {\n throw new Error('missing \"to\" param for drag and drop');\n }\n await dragAndDrop(\n { x: from.center[0], y: from.center[1] },\n { x: to.center[0], y: to.center[1] },\n );\n },\n });\n};\n\nexport const ActionLongPressParamSchema = z.object({\n locate: getMidsceneLocationSchema().describe(\n 'The element to be long pressed',\n ),\n duration: z\n .number()\n .optional()\n .describe('Long press duration in milliseconds'),\n});\n\nexport type ActionLongPressParam = {\n locate: LocateResultElement;\n duration?: number;\n};\nexport const defineActionLongPress = (\n longPress: NonNullable<PointerInputPrimitives['longPress']>,\n): DeviceAction<ActionLongPressParam> => {\n return defineLocatedPointAction<\n typeof ActionLongPressParamSchema,\n ActionLongPressParam\n >({\n name: 'LongPress',\n description: 'Long press the element',\n interfaceAlias: 'aiLongPress',\n paramSchema: ActionLongPressParamSchema,\n sample: {\n locate: { prompt: 'the message bubble' },\n },\n missingLocateMessage: 'LongPress requires an element to be located',\n call: async (point, param) => {\n await longPress(point, { duration: param.duration });\n },\n });\n};\n\nexport const ActionSwipeParamSchema = z.object({\n start: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'Optional starting point of the finger movement. Available in both relative and endpoint forms. If omitted, the center of the page is used.',\n ),\n direction: z\n .enum(['up', 'down', 'left', 'right'])\n .optional()\n .describe(\n 'Finger movement direction. Required together with a positive distance for a relative swipe. Omit when using end.',\n ),\n distance: z\n .number()\n .positive()\n .optional()\n .describe(\n 'Positive length of the finger movement in pixels. Required together with direction for a relative swipe. Omit when using end.',\n ),\n end: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'Endpoint of the finger movement. Use for an endpoint swipe, optionally with start. Do not provide direction or distance when using end.',\n ),\n duration: z\n .number()\n .default(300)\n .describe('Duration of the swipe gesture in milliseconds'),\n repeat: z\n .number()\n .optional()\n .describe(\n 'The number of times to repeat the swipe gesture. 1 for default, 0 for infinite (e.g. endless swipe until the end of the page)',\n ),\n});\n\nexport type ActionSwipeParam = {\n start?: LocateResultElement;\n direction?: 'up' | 'down' | 'left' | 'right';\n distance?: number;\n end?: LocateResultElement;\n duration?: number;\n repeat?: number;\n};\n\nexport function normalizeMobileSwipeParam(\n param: ActionSwipeParam,\n screenSize: { width: number; height: number },\n): {\n startPoint: { x: number; y: number };\n endPoint: { x: number; y: number };\n duration: number;\n repeatCount: number;\n} {\n const { width, height } = screenSize;\n const { start, end } = param;\n\n const startPoint = start\n ? { x: start.center[0], y: start.center[1] }\n : { x: width / 2, y: height / 2 };\n\n const endPoint = (() => {\n if (end) {\n if (param.direction !== undefined || param.distance !== undefined) {\n throw new Error(\n 'Invalid Swipe parameters: \"end\" cannot be combined with \"direction\" or \"distance\". Use \"end\", optionally with \"start\", for an endpoint swipe.',\n );\n }\n\n return { x: end.center[0], y: end.center[1] };\n }\n\n if (param.direction === undefined || param.distance === undefined) {\n throw new Error(\n 'Invalid Swipe parameters: a relative swipe requires both \"direction\" and a positive \"distance\".',\n );\n }\n\n if (param.distance <= 0) {\n throw new Error(\n 'Invalid Swipe parameters: \"distance\" must be a positive number.',\n );\n }\n\n return {\n x:\n startPoint.x +\n (param.direction === 'right'\n ? param.distance\n : param.direction === 'left'\n ? -param.distance\n : 0),\n y:\n startPoint.y +\n (param.direction === 'down'\n ? param.distance\n : param.direction === 'up'\n ? -param.distance\n : 0),\n };\n })();\n\n endPoint.x = Math.max(0, Math.min(endPoint.x, width));\n endPoint.y = Math.max(0, Math.min(endPoint.y, height));\n\n const duration = param.duration ?? 300;\n\n let repeatCount = typeof param.repeat === 'number' ? param.repeat : 1;\n if (repeatCount === 0) {\n repeatCount = 10;\n }\n\n return { startPoint, endPoint, duration, repeatCount };\n}\n\nexport const defineActionSwipe = (config: {\n swipe: TouchInputPrimitives['swipe'];\n size(): Promise<Size>;\n}): DeviceAction<ActionSwipeParam> => {\n return defineAction<typeof ActionSwipeParamSchema, ActionSwipeParam>({\n name: 'Swipe',\n description:\n 'Perform a touch gesture that directly manipulates the UI (e.g., adjust a continuous control such as a slider or wheel picker, switch between paged cards or images, follow an on-screen swipe gesture to continue or dismiss, or swipe an item to delete it). For browsing off-screen content in a page or scrollable region, use Scroll instead. Choose exactly one movement form: (1) relative swipe — provide \"direction\" and a positive \"distance\"; or (2) endpoint swipe — provide \"end\". \"start\" is optional for both forms and defaults to the center of the page. Do not combine \"end\" with \"direction\" or \"distance\".',\n paramSchema: ActionSwipeParamSchema,\n sample: {\n start: { prompt: 'center of the notification' },\n end: { prompt: 'upper edge of the screen' },\n },\n call: async (param) => {\n const { startPoint, endPoint, duration, repeatCount } =\n normalizeMobileSwipeParam(param, await config.size());\n for (let i = 0; i < repeatCount; i++) {\n await config.swipe(startPoint, endPoint, { duration });\n }\n },\n });\n};\n\n// ClearInput\nexport const actionClearInputParamSchema = z.object({\n locate: getMidsceneLocationSchema()\n .describe('The input field to be cleared')\n .optional(),\n});\nexport type ActionClearInputParam = {\n locate?: LocateResultElement;\n};\n\nexport const defineActionClearInput = (\n clearInput: KeyboardInputPrimitives['clearInput'],\n): DeviceAction<ActionClearInputParam> => {\n return defineAction<\n typeof actionClearInputParamSchema,\n ActionClearInputParam\n >({\n name: 'ClearInput',\n description: inputLocateDescription,\n interfaceAlias: 'aiClearInput',\n paramSchema: actionClearInputParamSchema,\n sample: {\n locate: { prompt: 'the search input field' },\n },\n call: async (param) => {\n await clearInput(param.locate);\n },\n });\n};\n\n// CursorMove\nexport const actionCursorMoveParamSchema = z.object({\n direction: z\n .enum(['left', 'right'])\n .describe('The direction to move the cursor'),\n times: z\n .number()\n .int()\n .min(1)\n .default(1)\n .describe(\n 'The number of times to move the cursor in the specified direction',\n ),\n});\nexport type ActionCursorMoveParam = {\n direction: 'left' | 'right';\n times?: number;\n};\n\nexport const defineActionCursorMove = (config: {\n keyboard: Pick<KeyboardInputPrimitives, 'keyboardPress' | 'cursorMove'>;\n sleep?(timeMs: number): Promise<void>;\n}): DeviceAction<ActionCursorMoveParam> => {\n return defineAction<\n typeof actionCursorMoveParamSchema,\n ActionCursorMoveParam\n >({\n name: 'CursorMove',\n description:\n 'Move the text cursor (caret) left or right within an input field or text area. Use this to reposition the cursor without selecting text.',\n paramSchema: actionCursorMoveParamSchema,\n sample: {\n direction: 'left',\n times: 3,\n },\n call: async (param) => {\n const times = param.times ?? 1;\n if (config.keyboard.cursorMove) {\n await config.keyboard.cursorMove(param.direction, times);\n return;\n }\n\n const wait =\n config.sleep ??\n ((timeMs: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, timeMs)));\n const arrowKey = param.direction === 'left' ? 'ArrowLeft' : 'ArrowRight';\n for (let i = 0; i < times; i++) {\n await config.keyboard.keyboardPress(arrowKey);\n await wait(100);\n }\n },\n });\n};\n\n// Pinch\nexport const ActionPinchParamSchema = z.object({\n locate: getMidsceneLocationSchema()\n .optional()\n .describe(\n 'The element to pinch on. If not specified, the center of the screen will be used',\n ),\n direction: z\n .enum(['in', 'out'])\n .describe(\n 'Pinch direction. \"in\" = pinch fingers together (zoom out / shrink), \"out\" = spread fingers apart (zoom in / enlarge).',\n ),\n distance: z\n .number()\n .positive()\n .optional()\n .describe(\n 'How far each finger moves in pixels. Defaults to a quarter of the shorter screen dimension.',\n ),\n duration: z\n .number()\n .default(500)\n .optional()\n .describe('Duration of the pinch gesture in milliseconds'),\n});\n\nexport type ActionPinchParam = {\n locate?: LocateResultElement;\n direction: 'in' | 'out';\n distance?: number;\n duration?: number;\n};\n\nexport const defineActionPinch = (config: {\n pinch: TouchInputPrimitives['pinch'];\n size(): Promise<Size>;\n}): DeviceAction<ActionPinchParam> | undefined => {\n if (!config.pinch) {\n return undefined;\n }\n\n return defineAction<typeof ActionPinchParamSchema, ActionPinchParam>({\n name: 'Pinch',\n description:\n 'Perform a two-finger pinch gesture. Use direction \"in\" to pinch fingers together (zoom out), or \"out\" to spread fingers apart (zoom in). Optionally specify distance for how far each finger moves.',\n interfaceAlias: 'aiPinch',\n paramSchema: ActionPinchParamSchema,\n sample: {\n locate: { prompt: 'the map area' },\n direction: 'out',\n distance: 200,\n },\n call: async (param) => {\n const { centerX, centerY, startDistance, endDistance, duration } =\n normalizePinchParam(param, await config.size());\n await config.pinch?.(\n { x: centerX, y: centerY },\n { startDistance, endDistance, duration },\n );\n },\n });\n};\n\nexport function normalizePinchParam(\n param: ActionPinchParam,\n screenSize: { width: number; height: number },\n): {\n centerX: number;\n centerY: number;\n startDistance: number;\n endDistance: number;\n duration: number;\n} {\n const { width, height } = screenSize;\n const element = param.locate;\n const centerX = element\n ? Math.round(element.center[0])\n : Math.round(width / 2);\n const centerY = element\n ? Math.round(element.center[1])\n : Math.round(height / 2);\n const duration = param.duration ?? 500;\n\n const baseDistance = Math.round(Math.min(width, height) / 4);\n const fingerDistance = param.distance ?? baseDistance;\n\n const startDistance = baseDistance;\n const endDistance =\n param.direction === 'out'\n ? baseDistance + fingerDistance\n : Math.max(10, baseDistance - fingerDistance);\n\n return { centerX, centerY, startDistance, endDistance, duration };\n}\n\nexport interface MobileInputActionContext {\n input: MobileInputPrimitives;\n size(): Promise<Size>;\n sleep?(timeMs: number): Promise<void>;\n getDefaultAutoDismissKeyboard?(): boolean | undefined;\n systemActions?: SystemInputActionOptions;\n}\n\nexport interface SystemInputActionConfig {\n name: string;\n description: string;\n interfaceAlias?: string;\n delayBeforeRunner?: number;\n delayAfterRunner?: number;\n}\n\nexport interface SystemInputActionOptions {\n backButton?: SystemInputActionConfig;\n homeButton?: SystemInputActionConfig;\n recentAppsButton?: SystemInputActionConfig;\n}\n\nexport interface InputPrimitiveActionOptions {\n size?: () => Promise<Size>;\n sleep?: (timeMs: number) => Promise<void>;\n includeSwipe?: boolean;\n includePinch?: boolean;\n systemActions?: SystemInputActionOptions;\n}\n\nfunction defineSystemInputAction(\n config: SystemInputActionConfig,\n call: () => Promise<void>,\n): DeviceAction<undefined, void> {\n return defineAction<undefined, undefined, void>({\n name: config.name,\n description: config.description,\n interfaceAlias: config.interfaceAlias,\n delayBeforeRunner: config.delayBeforeRunner,\n delayAfterRunner: config.delayAfterRunner,\n call,\n });\n}\n\nexport function defineActionsFromInputPrimitives(\n input: InputPrimitives,\n options: InputPrimitiveActionOptions = {},\n): DeviceAction<any>[] {\n const actions: Array<DeviceAction<any> | undefined> = [];\n const { pointer, keyboard, scroll, touch, system } = input;\n\n if (pointer) {\n actions.push(defineActionTap(pointer.tap));\n if (pointer.doubleClick) {\n actions.push(defineActionDoubleClick(pointer.doubleClick));\n }\n if (pointer.rightClick) {\n actions.push(defineActionRightClick(pointer.rightClick));\n }\n if (pointer.hover) {\n actions.push(defineActionHover(pointer.hover));\n }\n if (pointer.dragAndDrop) {\n actions.push(defineActionDragAndDrop(pointer.dragAndDrop));\n }\n if (pointer.longPress) {\n actions.push(defineActionLongPress(pointer.longPress));\n }\n }\n\n if (keyboard) {\n actions.push(\n defineActionInput(keyboard),\n defineActionClearInput(keyboard.clearInput),\n defineActionKeyboardPress(keyboard.keyboardPress),\n defineActionCursorMove({ keyboard, sleep: options.sleep }),\n );\n }\n\n if (scroll) {\n actions.push(defineActionScroll(scroll.scroll));\n }\n\n if (touch?.swipe && options.size && options.includeSwipe !== false) {\n actions.push(defineActionSwipe({ swipe: touch.swipe, size: options.size }));\n }\n\n if (touch?.pinch && options.size && options.includePinch !== false) {\n actions.push(defineActionPinch({ pinch: touch.pinch, size: options.size }));\n }\n\n if (system && options.systemActions) {\n const { systemActions } = options;\n if (system.backButton && systemActions.backButton) {\n actions.push(\n defineSystemInputAction(systemActions.backButton, system.backButton),\n );\n }\n if (system.homeButton && systemActions.homeButton) {\n actions.push(\n defineSystemInputAction(systemActions.homeButton, system.homeButton),\n );\n }\n if (system.recentAppsButton && systemActions.recentAppsButton) {\n actions.push(\n defineSystemInputAction(\n systemActions.recentAppsButton,\n system.recentAppsButton,\n ),\n );\n }\n }\n\n return actions.filter((action): action is DeviceAction<any> =>\n Boolean(action),\n );\n}\n\nexport function createDefaultMobileActions(\n context: MobileInputActionContext,\n): DeviceAction<any>[] {\n return defineActionsFromInputPrimitives(context.input, {\n size: context.size,\n sleep: context.sleep,\n systemActions: context.systemActions,\n });\n}\n\n// Sleep\nexport const ActionSleepParamSchema = z.object({\n timeMs: z\n .number()\n .default(1000)\n .optional()\n .describe('Sleep duration in milliseconds, defaults to 1000ms (1 second)'),\n});\n\nexport type ActionSleepParam = {\n timeMs?: number;\n};\n\nexport const defineActionSleep = (): DeviceAction<ActionSleepParam> => {\n return defineAction<typeof ActionSleepParamSchema, ActionSleepParam>({\n name: 'Sleep',\n description:\n 'Wait for a specified duration before continuing. Defaults to 1 second (1000ms) if not specified.',\n paramSchema: ActionSleepParamSchema,\n sample: {\n timeMs: 2000,\n },\n call: async (param) => {\n const duration = param?.timeMs ?? 1000;\n getDebug('device:common-action')(`Sleeping for ${duration}ms`);\n await new Promise((resolve) => setTimeout(resolve, duration));\n },\n });\n};\n\nexport type { DeviceAction } from '../types';\nexport {\n inputStrategies,\n type InputStrategy,\n type ResolvedTextInputOptions,\n type SequentialTextInputHandlers,\n type TextInputOptions,\n resolveInputStrategy,\n resolveTextInputOptions,\n sendTextSequentially,\n shouldInputSequentially,\n} from './input-strategy';\nexport type {\n AndroidDeviceOpt,\n AndroidDeviceInputOpt,\n IOSDeviceOpt,\n IOSDeviceInputOpt,\n HarmonyDeviceOpt,\n HarmonyDeviceInputOpt,\n} from './device-options';\n"],"names":["AbstractInterface","defineAction","config","pointFromLocate","locate","missingMessage","Error","defineLocatedPointAction","param","actionTapParamSchema","z","getMidsceneLocationSchema","defineActionTap","tap","point","registerFileChooserAcceptParamSchema","defineActionRegisterFileChooserAccept","register","actionRightClickParamSchema","defineActionRightClick","rightClick","actionDoubleClickParamSchema","defineActionDoubleClick","doubleClick","actionHoverParamSchema","defineActionHover","hover","inputLocateDescription","actionInputParamSchema","val","String","inputStrategies","defineActionInput","keyboard","actionKeyboardPressParamSchema","defineActionKeyboardPress","keyboardPress","actionScrollParamSchema","defineActionScroll","scroll","actionDragAndDropParamSchema","defineActionDragAndDrop","dragAndDrop","from","to","ActionLongPressParamSchema","defineActionLongPress","longPress","ActionSwipeParamSchema","normalizeMobileSwipeParam","screenSize","width","height","start","end","startPoint","endPoint","undefined","Math","duration","repeatCount","defineActionSwipe","i","actionClearInputParamSchema","defineActionClearInput","clearInput","actionCursorMoveParamSchema","defineActionCursorMove","times","wait","timeMs","Promise","resolve","setTimeout","arrowKey","ActionPinchParamSchema","defineActionPinch","centerX","centerY","startDistance","endDistance","normalizePinchParam","element","baseDistance","fingerDistance","defineSystemInputAction","call","defineActionsFromInputPrimitives","input","options","actions","pointer","touch","system","systemActions","action","Boolean","createDefaultMobileActions","context","ActionSleepParamSchema","defineActionSleep","getDebug"],"mappings":";;;;;;;;;;;;;;AA6KO,MAAeA;;QAgDpB;QAqDA;;AACF;AAKO,MAAMC,eAAe,CAK1BC,SAgBOA;AAGT,SAASC,gBACPC,MAAuC,EACvCC,cAAsB;IAEtB,IAAI,CAACD,QACH,MAAM,IAAIE,MAAMD;IAElB,OAAO;QAAE,GAAGD,OAAO,MAAM,CAAC,EAAE;QAAE,GAAGA,OAAO,MAAM,CAAC,EAAE;IAAC;AACpD;AAEA,SAASG,yBAGPL,MAQD;IACC,OAAOD,aAA8B;QACnC,MAAMC,OAAO,IAAI;QACjB,aAAaA,OAAO,WAAW;QAC/B,gBAAgBA,OAAO,cAAc;QACrC,aAAaA,OAAO,WAAW;QAC/B,QAAQA,OAAO,MAAM;QACrB,MAAM,OAAOM;YACX,MAAMN,OAAO,IAAI,CACfC,gBAAgBK,MAAM,MAAM,EAAEN,OAAO,oBAAoB,GACzDM;QAEJ;IACF;AACF;AAGO,MAAMC,uBAAuBC,EAAE,MAAM,CAAC;IAC3C,QAAQC,4BAA4B,QAAQ,CAAC;AAC/C;AAKO,MAAMC,kBAAkB,CAC7BC,MAEON,yBAAsE;QAC3E,MAAM;QACN,aAAa;QACb,gBAAgB;QAChB,aAAaE;QACb,QAAQ;YACN,QAAQ;gBAAE,QAAQ;YAAsB;QAC1C;QACA,sBAAsB;QACtB,MAAM,OAAOK;YACX,MAAMD,IAAIC;QACZ;IACF;AAGK,MAAMC,uCAAuCL,EAAE,MAAM,CAAC;IAC3D,OAAOA,EAAAA,KACC,CAAC;QAACA,EAAE,MAAM;QAAIA,EAAE,KAAK,CAACA,EAAE,MAAM;KAAI,EACvC,QAAQ,CACP;AAEN;AAKO,MAAMM,wCAAwC,CACnDC,WAEOhB,aAGL;QACA,MAAM;QACN,aACE;QACF,gBAAgB;QAChB,aAAac;QACb,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