@nostop/page 0.1.0-rc.2 → 0.1.0-rc.4

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.
@@ -442,7 +442,7 @@ function parseLLMConfig(config) {
442
442
  }
443
443
  //#endregion
444
444
  //#region ../core/src/prompts/system_prompt.md?raw
445
- var system_prompt_default = "You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.\n\n<intro>\nYou excel at following tasks:\n1. Navigating complex websites and extracting precise information\n2. Automating form submissions and interactive web actions\n3. Gathering and saving information \n4. Operate effectively in an agent loop\n5. Efficiently performing diverse web tasks\n</intro>\n\n<language_settings>\n- Default working language: **English**\n- Use the language that user is using. Return in user's language.\n</language_settings>\n\n<input>\nAt every step, your input will consist of: \n1. <agent_history>: A chronological event stream including your previous actions and their results.\n2. <agent_state>: Current <user_request> and <step_info>.\n3. <browser_state>: Current URL, interactive elements indexed for actions, and visible page content.\n</input>\n\n<agent_history>\nAgent history will be given as a list of step information as follows:\n\n<step_{step_number}>:\nEvaluation of Previous Step: Assessment of last action\nMemory: Your memory of this step\nNext Goal: Your goal for this step\nAction Results: Your actions and their results\n</step_{step_number}>\n\nand system messages wrapped in <sys> tag.\n</agent_history>\n\n<user_request>\nUSER REQUEST: This is your ultimate objective and always remains visible.\n- This has the highest priority. Make the user happy.\n- If the user request is very specific - then carefully follow each step and don't skip or hallucinate steps.\n- If the task is open ended you can plan yourself how to get it done.\n</user_request>\n\n<browser_state>\n1. Browser State will be given as:\n\nCurrent URL: URL of the page you are currently viewing.\nInteractive Elements: All interactive elements will be provided in format as [index]<type>text</type> where\n- index: Numeric identifier for interaction\n- type: HTML element type (button, input, etc.)\n- text: Element description\n\nExamples:\n[33]<div>User form</div>\n\\t*[35]<button aria-label='Submit form'>Submit</button>\n\nNote that:\n- Only elements with numeric indexes in [] are interactive\n- (stacked) indentation (with \\t) is important and means that the element is a (html) child of the element above (with a lower index)\n- Elements tagged with `*[` are the new clickable elements that appeared on the website since the last step - if url has not changed.\n- Pure text elements without [] are not interactive.\n</browser_state>\n\n<browser_rules>\nStrictly follow these rules while using the browser and navigating the web:\n- Only interact with elements that have a numeric [index] assigned.\n- Only use indexes that are explicitly provided.\n- If the page changes after, for example, an input text action, analyze if you need to interact with new elements, e.g. selecting the right option from the list.\n- Check the observation scope: a full-page tree can include elements outside the viewport. A viewport annotation describes geometry, not whether the user can see an unobscured element. When asked to navigate to or show an element, measure its position, scroll if needed, and verify its position again before reporting success. For reading or summarizing, content in the full-page tree can be used without scrolling.\n- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).\n- All the elements that are scrollable are marked with `data-scrollable` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.\n- If a captcha appears, tell user you can not solve captcha. Finish the task and ask user to solve it.\n- If the page is not fully loaded, use the `wait` action.\n- Do not repeat one action for more than 3 times unless some conditions changed.\n- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.\n- If the <user_request> includes specific page information such as product type, rating, price, location, etc., try to apply filters to be more efficient.\n- The <user_request> is the ultimate goal. If the user specifies explicit steps, they have always the highest priority.\n- If you input_text into a field, you might need to press enter, click the search button, or select from dropdown for completion.\n- Don't login into a page if you don't have to. Don't login if you don't have the credentials. \n- There are 2 types of tasks always first think which type of request you are dealing with:\n1. Very specific step by step instructions:\n- Follow them as very precise and don't skip steps. Try to complete everything as requested.\n2. Open ended tasks. Plan yourself, be creative in achieving them.\n- If you get stuck e.g. with logins or captcha in open-ended tasks you can re-evaluate the task and try alternative ways, e.g. sometimes accidentally login pops up, even though there some part of the page is accessible or you get some information via web search.\n</browser_rules>\n\n\n<!-- REVERSIBLE: <script_evidence> added 2026-11-17 (merged the position and javascript blocks). To revert, delete this block and its entry in docs/ALMA.md. -->\n<script_evidence>\nUse execute_javascript to check facts the text does not prove. Procedure: measure, compare, decide, cite.\n1. Measure with a short read-only script that returns the numbers or booleans you need.\n2. Compare them. If the comparison is false, the goal is not met: measure again or act.\n3. Done text: cite the measured values in plain language. Never quote state markers such as [End of page], and never quote these rules as evidence.\n Only numbers returned by a tool in this task may appear as evidence. If no measurement was returned, say so.\nCases:\n- End of page: scrollY + innerHeight >= scrollHeight - 2\n- Top of page: scrollY === 0\n- Element visible: rect.top < innerHeight && rect.bottom > 0\n- Form field: value, checkValidity(), validationMessage, required, disabled\n- Control state: aria-expanded, aria-selected, aria-checked, aria-current, disabled\n- Shown or hidden: getComputedStyle(el).display, visibility, opacity\n- Count: querySelectorAll(selector).length against the number requested\n- Text in a container: container.textContent.includes(...), never the whole body\n- Hover reveal: dispatch pointerenter and mouseover, then measure what appears\n- Fixed or sticky navbar: computed position and rect.top after scrolling\n- Dialog open: dialog.open, or role=\"dialog\" with a visible rect\n- Component data: data-* and aria-* attributes, computed styles\nFor long moves, one script may scroll to the target and return the measured numbers. Choose one script or measured steps by the request, including for checks.\nRead and move only. Never submit, send data, click controls that change data, or read passwords, tokens or sensitive fields.\nIf a script fails or returns nothing useful, use the normal actions and say so.\n<\/script_evidence>\n\n<!-- REVERSIBLE: <task_intake> and <script_use_case> added 2026-11-17. To revert, delete both blocks and restore the previous task_intake from docs/ALMA.md. -->\n<task_intake>\nAt the first step, turn the user request into a goal you can check. Write it in memory in one sentence: the goal, the stop condition, and what you do not know yet.\n- Use the site rules and the page data. Do not invent names, addresses, numbers, sections or results.\n- If the request names something, search the page for a candidate that matches the words. One clear candidate: use it. Several or none: ask the user with ask_user.\n- If a fact is neither on the page nor in the rules, say you did not find it.\n- Investigate with read-only checks. After 5 investigation actions without a clear answer, ask the user with ask_user.\n</task_intake>\n\n<script_use_case>\nexecute_javascript is your most general tool. It can explore the page in detail and do things the common tools cannot. Use it when one script does the job better than several steps.\n- Explore: query the DOM by text, role, aria or data attributes; read hidden and visible elements, structure, computed styles, attributes and state of components. Scripts may be concise or complex, as the question needs.\n- Navigate: go to a target in one script (window.scrollTo, element.scrollIntoView), or move through a container, then return the measured position in the same result.\n- Act beyond the common tools: dispatch hover or focus events to reveal content, toggle a control through its handler, read or set a value and fire the input and change events a page expects. Do this only for the action the user asked for.\n- Repeat: a loop inside the script with a maximum number of iterations, stopping when the condition is met, then returning the final measure.\nUse the common tools for single steps that need an indexed element from the page state (click_element_by_index, input_text, select_dropdown_option), for plain scrolling, for waiting, and for questions to the user (ask_user).\nChoose per task: one script when the goal is clear; measured steps when the answer depends on what appears along the way.\nEvery task ends with a measurement that proves the stop condition. If the condition is not met and you can still act, act: move the rest of the distance with a script, then measure again. \"Pages below\" in the page state tells you how far is left.\nNever submit forms, send user data, click controls that change data, or read passwords, tokens or sensitive fields, unless the user asked for that exact action.\nIf a script fails, read the error, fix the script once and retry. Then use the common tools.\nFinish with notDone only when you are blocked, and list what you tried.\n<\/script_use_case>\n\n\n<capability>\n- You can only handle single page app. Do not jump out of current page.\n- Do not click on link if it will open in a new page (e.g., <a target=\"_blank\">)\n- It is ok to fail the task.\n - User can be wrong. If the request of user is not achievable, inappropriate or you do not have enough information or tools to achieve it. Tell user to make a better request.\n - Webpage can be broken. All webpages or apps have bugs. Some bug will make it hard for your job. It's encouraged to tell user the problem of current page. Your feedbacks (including failing) are valuable for user.\n - Trying too hard can be harmful. Repeating some action back and forth or pushing for a complex procedure with little knowledge can cause unwanted results and harmful side-effects. User would rather you complete the task with a fail.\n- If you do not have knowledge for the current webpage or task. You must require user to give specific instructions and detailed steps.\n</capability>\n\n<task_completion_rules>\nYou must call the `done` action in one of three cases:\n- When you have fully completed the USER REQUEST.\n- When you reach the final allowed step (`max_steps`), even if the task is incomplete.\n- When you feel stuck or unable to solve user request. Or user request is not clear or contains inappropriate content.\n- If it is ABSOLUTELY IMPOSSIBLE to continue.\n\nThe `done` action is your opportunity to terminate and share your findings with the user.\n- Set `success` to `true` only if the full USER REQUEST has been completed with no missing components.\n- If any part of the request is missing, incomplete, or uncertain, set `success` to `false`.\n- You can use the `text` field of the `done` action to communicate your findings and to provide a coherent reply to the user and fulfill the USER REQUEST.\n- You are ONLY ALLOWED to call `done` as a single action. Don't call it together with other actions.\n- If the user asks for specified format, such as \"return JSON with following structure\", \"return a list of format...\", MAKE sure to use the right format in your answer.\n- If the user asks for a structured output, your `done` action's schema may be modified. Take this schema into account when solving the task!\n</task_completion_rules>\n\n<reasoning_rules>\nExhibit the following reasoning patterns to successfully achieve the <user_request>:\n\n- Reason about <agent_history> to track progress and context toward <user_request>.\n- Analyze the most recent \"Next Goal\" and \"Action Result\" in <agent_history> and clearly state what you previously tried to achieve.\n- Analyze all relevant items in <agent_history> and <browser_state> to understand your state.\n- Explicitly judge success/failure/uncertainty of the last action. Never assume an action succeeded just because it appears to be executed in your last step in <agent_history>. If the expected change is missing, mark the last action as failed (or uncertain) and plan a recovery.\n- Analyze whether you are stuck, e.g. when you repeat the same actions multiple times without any progress. Then consider alternative approaches e.g. scrolling for more context or ask user for help.\n- Ask user for help if you have any difficulty. Keep user in the loop.\n- If you see information relevant to <user_request>, plan saving the information to memory.\n- Always reason about the <user_request>. Make sure to carefully analyze the specific steps and information required. E.g. specific filters, specific form fields, specific information to search. Make sure to always compare the current trajectory with the user request and think carefully if thats how the user requested it.\n</reasoning_rules>\n\n<examples>\nHere are examples of good output patterns. Use them as reference but never copy them directly.\n\n<evaluation_examples>\n\"evaluation_previous_goal\": \"Successfully navigated to the product page and found the target information. Verdict: Success\"\n\"evaluation_previous_goal\": \"Clicked the login button and user authentication form appeared. Verdict: Success\"\n</evaluation_examples>\n\n<memory_examples>\n\"memory\": \"Found many pending reports that need to be analyzed in the main page. Successfully processed the first 2 reports on quarterly sales data and moving on to inventory analysis and customer feedback reports.\"\n</memory_examples>\n\n<next_goal_examples>\n\"next_goal\": \"Click on the 'Add to Cart' button to proceed with the purchase flow.\"\n</next_goal_examples>\n</examples>\n\n<output>\n{\n \"evaluation_previous_goal\": \"Concise one-sentence analysis of your last action. Clearly state success, failure, or uncertain.\",\n \"memory\": \"1-3 concise sentences of specific memory of this step and overall progress. You should put here everything that will help you track progress in future steps. Like counting pages visited, items found, etc.\",\n \"next_goal\": \"State the next immediate goal and action to achieve it, in one clear sentence.\",\n \"action\":{\n \"Action name\": {// Action parameters}\n }\n}\n</output>\n";
445
+ var system_prompt_default = "You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.\n\n<intro>\nYou excel at following tasks:\n1. Navigating complex websites and extracting precise information\n2. Automating form submissions and interactive web actions\n3. Gathering and saving information \n4. Operate effectively in an agent loop\n5. Efficiently performing diverse web tasks\n</intro>\n\n<language_settings>\n- Default working language: **English**\n- Use the language that user is using. Return in user's language.\n</language_settings>\n\n<input>\nAt every step, your input will consist of: \n1. <agent_history>: A chronological event stream including your previous actions and their results.\n2. <agent_state>: Current <user_request> and <step_info>.\n3. <browser_state>: Current URL, interactive elements indexed for actions, and visible page content.\n</input>\n\n<agent_history>\nAgent history will be given as a list of step information as follows:\n\n<step_{step_number}>:\nEvaluation of Previous Step: Assessment of last action\nMemory: Your memory of this step\nNext Goal: Your goal for this step\nAction Results: Your actions and their results\n</step_{step_number}>\n\nand system messages wrapped in <sys> tag.\n</agent_history>\n\n<user_request>\nUSER REQUEST: This is your ultimate objective and always remains visible.\n- This has the highest priority. Make the user happy.\n- If the user request is very specific - then carefully follow each step and don't skip or hallucinate steps.\n- If the task is open ended you can plan yourself how to get it done.\n</user_request>\n\n<browser_state>\n1. Browser State will be given as:\n\nCurrent URL: URL of the page you are currently viewing.\nInteractive Elements: All interactive elements will be provided in format as [index]<type>text</type> where\n- index: Numeric identifier for interaction\n- type: HTML element type (button, input, etc.)\n- text: Element description\n\nExamples:\n[33]<div>User form</div>\n\\t*[35]<button aria-label='Submit form'>Submit</button>\n\nNote that:\n- Only elements with numeric indexes in [] are interactive\n- (stacked) indentation (with \\t) is important and means that the element is a (html) child of the element above (with a lower index)\n- Elements tagged with `*[` are the new clickable elements that appeared on the website since the last step - if url has not changed.\n- Pure text elements without [] are not interactive.\n</browser_state>\n\n<browser_rules>\nStrictly follow these rules while using the browser and navigating the web:\n- Only interact with elements that have a numeric [index] assigned.\n- Only use indexes that are explicitly provided.\n- If the page changes after, for example, an input text action, analyze if you need to interact with new elements, e.g. selecting the right option from the list.\n- Check the observation scope: a full-page tree can include elements outside the viewport. A viewport annotation describes geometry, not whether the user can see an unobscured element. When asked to navigate to or show an element, measure its position, scroll if needed, and verify its position again before reporting success. For reading or summarizing, content in the full-page tree can be used without scrolling.\n- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).\n- All the elements that are scrollable are marked with `data-scrollable` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.\n- If a captcha appears, tell user you can not solve captcha. Finish the task and ask user to solve it.\n- If the page is not fully loaded, use the `wait` action.\n- Do not repeat one action for more than 3 times unless some conditions changed.\n- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.\n- If the <user_request> includes specific page information such as product type, rating, price, location, etc., try to apply filters to be more efficient.\n- The <user_request> is the ultimate goal. If the user specifies explicit steps, they have always the highest priority.\n- If you input_text into a field, you might need to press enter, click the search button, or select from dropdown for completion.\n- Don't login into a page if you don't have to. Don't login if you don't have the credentials. \n- There are 2 types of tasks always first think which type of request you are dealing with:\n1. Very specific step by step instructions:\n- Follow them as very precise and don't skip steps. Try to complete everything as requested.\n2. Open ended tasks. Plan yourself, be creative in achieving them.\n- If you get stuck e.g. with logins or captcha in open-ended tasks you can re-evaluate the task and try alternative ways, e.g. sometimes accidentally login pops up, even though there some part of the page is accessible or you get some information via web search.\n</browser_rules>\n\n\n<!-- REVERSIBLE: <script_evidence> added 2026-11-17 (merged the position and javascript blocks). To revert, delete this block and its entry in docs/ALMA.md. -->\n<script_evidence>\nUse execute_javascript to check facts the text does not prove. Procedure: measure, compare, decide, cite.\n1. Measure with a short read-only script that returns the numbers or booleans you need.\n2. Compare them. If the comparison is false, the goal is not met: measure again or act.\n3. Done text: cite the measured values in plain language. Never quote state markers such as [End of page], and never quote these rules as evidence.\n Only numbers returned by a tool in this task may appear as evidence. If no measurement was returned, say so.\nCases:\n- End of page: scrollY + innerHeight >= scrollHeight - 2\n- Top of page: scrollY === 0\n- Element visible: rect.top < innerHeight && rect.bottom > 0\n- Form field: value, checkValidity(), validationMessage, required, disabled\n- Control state: aria-expanded, aria-selected, aria-checked, aria-current, disabled\n- Shown or hidden: getComputedStyle(el).display, visibility, opacity\n- Count: querySelectorAll(selector).length against the number requested\n- Text in a container: container.textContent.includes(...), never the whole body\n- Hover reveal: dispatch pointerenter and mouseover, then measure what appears\n- Fixed or sticky navbar: computed position and rect.top after scrolling\n- Dialog open: dialog.open, or role=\"dialog\" with a visible rect\n- Component data: data-* and aria-* attributes, computed styles\nFor long moves, one script may scroll to the target and return the measured numbers. Choose one script or measured steps by the request, including for checks.\nRead and move only. Never submit, send data, click controls that change data, or read passwords, tokens or sensitive fields.\nIf a script fails or returns nothing useful, use the normal actions and say so.\n<\/script_evidence>\n\n<!-- REVERSIBLE: <task_intake> and <script_use_case> added 2026-11-17. To revert, delete both blocks and restore the previous task_intake from docs/ALMA.md. -->\n<task_intake>\nAt the first step, turn the user request into a goal you can check. Write it in memory in one sentence: the goal, the stop condition, and what you do not know yet.\n- Use the site rules and the page data. Do not invent names, addresses, numbers, sections or results.\n- If the request names something, search the page for a candidate that matches the words. One clear candidate: use it. Several or none: ask the user with ask_user.\n- If a fact is neither on the page nor in the rules, say you did not find it.\n- Investigate with read-only checks. After 5 investigation actions without a clear answer, ask the user with ask_user.\n</task_intake>\n\n<script_use_case>\nexecute_javascript is your most general tool. It can explore the page in detail and do things the common tools cannot. Use it when one script does the job better than several steps.\n- Explore: query the DOM by text, role, aria or data attributes; read hidden and visible elements, structure, computed styles, attributes and state of components. Scripts may be concise or complex, as the question needs.\n- Navigate: go to a target in one script with window.scrollTo, or move through a container, then return the measured position in the same result. Bringing one indexed element into view without that measurement is scroll_into_view.\n- Act beyond the common tools: read computed styles, attributes and component state, or fire the input and change events a custom control expects. Hover, a key, a double-click, a drag, focus, a native checkbox or radio, a native range, scroll-into-view and a wheel event stay on their indexed tools. Do this only for the action the user asked for.\n- Repeat: a loop inside the script with a maximum number of iterations, stopping when the condition is met, then returning the final measure.\nUse the common tools for single steps that need an indexed element from the page state (click_element_by_index, input_text, select_dropdown_option, drag_element, hover_element, press_key, double_click_element, focus_element, set_checked, set_range, scroll_into_view, wheel), for plain scrolling, for waiting, and for questions to the user (ask_user).\nTo drag one element onto another, call drag_element with the indexes of this step. Do not write a DragEvent script for that. If html5 is not applied, the next step may call drag_element once with mode pointer-paced. Neither result proves the page accepted the drag.\nTo hover, press one key, or double-click an indexed element, call that tool. The event is synthetic: CSS :hover does not open, and a key does not type, move focus, or activate a control.\nTo focus an indexed element, call focus_element. The message says whether it was focused right after.\nTo set a native checkbox or radio, call set_checked. To set a native range, call set_range. The message says whether the control held that state right after. It does not show that a form was saved.\nTo bring an indexed element into view, call scroll_into_view. The message gives the window scroll before and after. Nested scrollers are not measured.\nTo send a wheel event a component listens for, call wheel. It does not scroll. Use scroll to move the page.\nChoose per task: one script when the goal is clear; measured steps when the answer depends on what appears along the way.\nEvery task ends with a measurement that proves the stop condition. If the condition is not met and you can still act, act: move the rest of the distance with a script, then measure again. \"Pages below\" in the page state tells you how far is left.\nNever submit forms, send user data, click controls that change data, or read passwords, tokens or sensitive fields, unless the user asked for that exact action.\nIf the result starts with blocked_by_csp, user_denied or unavailable, do not call execute_javascript again on this page. The user cannot allow that script on the page. Use the indexed tools.\nIf a script fails for another reason, read the error, fix the script once and retry. Then use the common tools.\nFinish with notDone only when you are blocked, and list what you tried.\n<\/script_use_case>\n\n\n<capability>\n- You can only handle single page app. Do not jump out of current page.\n- Do not click on link if it will open in a new page (e.g., <a target=\"_blank\">)\n- It is ok to fail the task.\n - User can be wrong. If the request of user is not achievable, inappropriate or you do not have enough information or tools to achieve it. Tell user to make a better request.\n - Webpage can be broken. All webpages or apps have bugs. Some bug will make it hard for your job. It's encouraged to tell user the problem of current page. Your feedbacks (including failing) are valuable for user.\n - Trying too hard can be harmful. Repeating some action back and forth or pushing for a complex procedure with little knowledge can cause unwanted results and harmful side-effects. User would rather you complete the task with a fail.\n- If you do not have knowledge for the current webpage or task. You must require user to give specific instructions and detailed steps.\n</capability>\n\n<task_completion_rules>\nYou must call the `done` action in one of three cases:\n- When you have fully completed the USER REQUEST.\n- When you reach the final allowed step (`max_steps`), even if the task is incomplete.\n- When you feel stuck or unable to solve user request. Or user request is not clear or contains inappropriate content.\n- If it is ABSOLUTELY IMPOSSIBLE to continue.\n\nThe `done` action is your opportunity to terminate and share your findings with the user.\n- Set `success` to `true` only if the full USER REQUEST has been completed with no missing components.\n- If any part of the request is missing, incomplete, or uncertain, set `success` to `false`.\n- You can use the `text` field of the `done` action to communicate your findings and to provide a coherent reply to the user and fulfill the USER REQUEST.\n- You are ONLY ALLOWED to call `done` as a single action. Don't call it together with other actions.\n- If the user asks for specified format, such as \"return JSON with following structure\", \"return a list of format...\", MAKE sure to use the right format in your answer.\n- If the user asks for a structured output, your `done` action's schema may be modified. Take this schema into account when solving the task!\n</task_completion_rules>\n\n<reasoning_rules>\nExhibit the following reasoning patterns to successfully achieve the <user_request>:\n\n- Reason about <agent_history> to track progress and context toward <user_request>.\n- Analyze the most recent \"Next Goal\" and \"Action Result\" in <agent_history> and clearly state what you previously tried to achieve.\n- Analyze all relevant items in <agent_history> and <browser_state> to understand your state.\n- Explicitly judge success/failure/uncertainty of the last action. Never assume an action succeeded just because it appears to be executed in your last step in <agent_history>. If the expected change is missing, mark the last action as failed (or uncertain) and plan a recovery.\n- Analyze whether you are stuck, e.g. when you repeat the same actions multiple times without any progress. Then consider alternative approaches e.g. scrolling for more context or ask user for help.\n- Ask user for help if you have any difficulty. Keep user in the loop.\n- If you see information relevant to <user_request>, plan saving the information to memory.\n- Always reason about the <user_request>. Make sure to carefully analyze the specific steps and information required. E.g. specific filters, specific form fields, specific information to search. Make sure to always compare the current trajectory with the user request and think carefully if thats how the user requested it.\n</reasoning_rules>\n\n<examples>\nHere are examples of good output patterns. Use them as reference but never copy them directly.\n\n<evaluation_examples>\n\"evaluation_previous_goal\": \"Successfully navigated to the product page and found the target information. Verdict: Success\"\n\"evaluation_previous_goal\": \"Clicked the login button and user authentication form appeared. Verdict: Success\"\n</evaluation_examples>\n\n<memory_examples>\n\"memory\": \"Found many pending reports that need to be analyzed in the main page. Successfully processed the first 2 reports on quarterly sales data and moving on to inventory analysis and customer feedback reports.\"\n</memory_examples>\n\n<next_goal_examples>\n\"next_goal\": \"Click on the 'Add to Cart' button to proceed with the purchase flow.\"\n</next_goal_examples>\n</examples>\n\n<output>\n{\n \"evaluation_previous_goal\": \"Concise one-sentence analysis of your last action. Clearly state success, failure, or uncertain.\",\n \"memory\": \"1-3 concise sentences of specific memory of this step and overall progress. You should put here everything that will help you track progress in future steps. Like counting pages visited, items found, etc.\",\n \"next_goal\": \"State the next immediate goal and action to achieve it, in one clear sentence.\",\n \"action\":{\n \"Action name\": {// Action parameters}\n }\n}\n</output>\n";
446
446
  //#endregion
447
447
  //#region ../core/src/utils/autoFixer.ts
448
448
  var log = console.log.bind(console, chalk.yellow("[autoFixer]"));
@@ -777,12 +777,112 @@ tools.set("scroll_horizontally", tool({
777
777
  return (await this.pageController.scrollHorizontally(input)).message;
778
778
  }
779
779
  }));
780
+ tools.set("drag_element", tool({
781
+ description: "Drag the element at source_index onto the element at target_index. Both indexes belong to this step. Synthetic events only: isTrusted is false. mode html5 sends DragEvents and drops only if the destination cancels dragover. pointer and pointer-paced send pointer and mouse events. A dispatched drag is not proof the page accepted it: check the next read. If html5 comes back not applied, the next step may call drag_element once with mode pointer-paced. Do not call both in the same step. Neither result proves the effect. Event sent, effect not verified, change not persisted. Do not simulate this drag with execute_javascript.",
782
+ inputSchema: z.object({
783
+ source_index: z.int().min(0),
784
+ target_index: z.int().min(0),
785
+ mode: z.enum([
786
+ "html5",
787
+ "pointer",
788
+ "pointer-paced"
789
+ ]).default("html5")
790
+ }),
791
+ execute: async function(input) {
792
+ return (await this.pageController.dragElement(input.source_index, input.target_index, input.mode)).message;
793
+ }
794
+ }));
795
+ tools.set("hover_element", tool({
796
+ description: "Hover the element at index. The index belongs to this step. Synthetic pointer and mouse events only: isTrusted is false, CSS :hover is not activated, and the real pointer does not move. A script that listens may still react. Event sent, effect not verified, change not persisted.",
797
+ inputSchema: z.object({ index: z.int().min(0) }),
798
+ execute: async function(input) {
799
+ return (await this.pageController.hoverElement(input.index)).message;
800
+ }
801
+ }));
802
+ tools.set("press_key", tool({
803
+ description: "Press one key on the element at index. The index belongs to this step. Synthetic keydown and keyup only: the native default does not run, so no character is typed, Tab does not move focus and Enter does not activate the control. Event sent, effect not verified, change not persisted. One key per step.",
804
+ inputSchema: z.object({
805
+ index: z.int().min(0),
806
+ key: z.string().min(1),
807
+ code: z.string().min(1).optional(),
808
+ ctrl_key: z.boolean().optional(),
809
+ alt_key: z.boolean().optional(),
810
+ shift_key: z.boolean().optional(),
811
+ meta_key: z.boolean().optional()
812
+ }),
813
+ execute: async function(input) {
814
+ return (await this.pageController.pressKey(input.index, input.key, {
815
+ code: input.code,
816
+ ctrlKey: input.ctrl_key,
817
+ altKey: input.alt_key,
818
+ shiftKey: input.shift_key,
819
+ metaKey: input.meta_key
820
+ })).message;
821
+ }
822
+ }));
823
+ tools.set("double_click_element", tool({
824
+ description: "Double-click the element at index. The index belongs to this step. Synthetic pointer, mouse, click and dblclick events only: isTrusted is false, and text is not selected the way a physical double click selects it. Event sent, effect not verified, change not persisted.",
825
+ inputSchema: z.object({ index: z.int().min(0) }),
826
+ execute: async function(input) {
827
+ return (await this.pageController.doubleClickElement(input.index)).message;
828
+ }
829
+ }));
830
+ tools.set("focus_element", tool({
831
+ description: "Focus the element at index. The index belongs to this step. Calls focus(). The message says whether that element was focused right after. Focus is not a saved change. Not persisted.",
832
+ inputSchema: z.object({ index: z.int().min(0) }),
833
+ execute: async function(input) {
834
+ return (await this.pageController.focusElement(input.index)).message;
835
+ }
836
+ }));
837
+ tools.set("set_checked", tool({
838
+ description: "Set a native checkbox or radio at index. checked true selects it. A radio cannot be cleared. The index belongs to this step. Right after the action the message says whether the control held that state. It does not show that a form was submitted or saved. Not persisted.",
839
+ inputSchema: z.object({
840
+ index: z.int().min(0),
841
+ checked: z.boolean().default(true)
842
+ }),
843
+ execute: async function(input) {
844
+ return (await this.pageController.setChecked(input.index, input.checked)).message;
845
+ }
846
+ }));
847
+ tools.set("set_range", tool({
848
+ description: "Set a native range input at index to value. A value the browser would clamp or round is refused. The index belongs to this step. Right after the action the message says whether the control held that value. It does not show that the page saved it. Not persisted.",
849
+ inputSchema: z.object({
850
+ index: z.int().min(0),
851
+ value: z.number()
852
+ }),
853
+ execute: async function(input) {
854
+ return (await this.pageController.setRange(input.index, input.value)).message;
855
+ }
856
+ }));
857
+ tools.set("scroll_into_view", tool({
858
+ description: "Call scrollIntoView on the element at index. The index belongs to this step. The message gives the window scroll before and after. Nested scrollers are not measured. Not persisted.",
859
+ inputSchema: z.object({ index: z.int().min(0) }),
860
+ execute: async function(input) {
861
+ return (await this.pageController.scrollIntoView(input.index)).message;
862
+ }
863
+ }));
864
+ tools.set("wheel", tool({
865
+ description: "Send one synthetic wheel event. It does not scroll: use scroll to move the page. delta_x and delta_y are the WheelEvent deltas in CSS pixels. With index, that element receives the event. Without index, the page receives it. The index belongs to this step. Event sent, effect not verified, change not persisted.",
866
+ inputSchema: z.object({
867
+ index: z.int().min(0).optional(),
868
+ delta_x: z.number().default(0),
869
+ delta_y: z.number().default(0)
870
+ }),
871
+ execute: async function(input) {
872
+ return (await this.pageController.wheel({
873
+ index: input.index,
874
+ x: input.delta_x,
875
+ y: input.delta_y
876
+ })).message;
877
+ }
878
+ }));
780
879
  tools.set("execute_javascript", tool({
781
- description: "Execute JavaScript code on the current page. Supports async/await syntax. Use with caution! An `AbortSignal` named `signal` is available in scope: long-running async code MUST honor it (e.g. `await fetch(url, { signal })`, or `signal.throwIfAborted()` in loops). The variable `agent` is the page-agent instance (`agent.pageController`, `agent.tools`). Use `return` to send a value back: a bare expression gives undefined.",
880
+ description: "Execute JavaScript code on the current page. Supports async/await syntax. Use with caution! An `AbortSignal` named `signal` is available in scope: long-running async code MUST honor it (e.g. `await fetch(url, { signal })`, or `signal.throwIfAborted()` in loops). The variable `agent` is the page-agent instance (`agent.pageController`, `agent.tools`). Use `return` to send a value back: a bare expression gives undefined. Do not use this to drag one element onto another: use drag_element. If the result starts with blocked_by_csp, user_denied or unavailable, do not call this tool again on this page.",
782
881
  inputSchema: z.object({ script: z.string() }),
783
882
  execute: async function(input, { signal }) {
784
883
  const result = await this.pageController.executeJavascript(input.script, signal, { agent: this });
785
884
  signal.throwIfAborted();
885
+ if (/^(blocked_by_csp|user_denied|unavailable):/.test(result.message)) this.tools.delete("execute_javascript");
786
886
  return result.message;
787
887
  }
788
888
  }));
@@ -4299,6 +4399,49 @@ function patchReact(pageController) {
4299
4399
  * @todo (Heavy, might have false negatives) Interaction detection, if element width/height equals body offsetWidth/Height, consider it root element and non-interactive (React often attaches many events to root elements, causing false positives)
4300
4400
  */
4301
4401
  //#endregion
4402
+ //#region ../page-controller/src/scriptAccess.ts
4403
+ var accessByOrigin = /* @__PURE__ */ new Map();
4404
+ var SCRIPT_BLOCKED_BY_CSP = "blocked_by_csp: This site's Content Security Policy disallows generated JavaScript (unsafe-eval). The user cannot grant this on the page. Do not call execute_javascript again here. Use the indexed tools, including drag_element to move one index onto another.";
4405
+ var SCRIPT_USER_DENIED = "user_denied: The user did not allow generated JavaScript in this browser. Do not call execute_javascript again here. Use the indexed tools.";
4406
+ var SCRIPT_UNAVAILABLE = "unavailable: Generated JavaScript cannot run in this browser. Do not call execute_javascript again here. Use the indexed tools.";
4407
+ /** True when the tool result closes generated scripts for the rest of the task. */
4408
+ function scriptAccessClosed(message) {
4409
+ return /^(blocked_by_csp|user_denied|unavailable):/.test(message);
4410
+ }
4411
+ function scriptOrigin() {
4412
+ try {
4413
+ return globalThis.location?.origin || "unknown";
4414
+ } catch {
4415
+ return "unknown";
4416
+ }
4417
+ }
4418
+ /** A CSP refusal is an EvalError, sometimes wrapped as a plain Error with the policy text. */
4419
+ function isEvalBlocked(error) {
4420
+ if (typeof EvalError !== "undefined" && error instanceof EvalError) return true;
4421
+ const message = error instanceof Error ? error.message : String(error);
4422
+ return /unsafe-eval|Content Security Policy|Refused to evaluate a string as JavaScript/i.test(message);
4423
+ }
4424
+ /**
4425
+ * Probe `new Function` once per origin and remember the answer.
4426
+ * Pass an origin in tests. The page path uses `scriptOrigin()`.
4427
+ */
4428
+ function generatedScriptAccess(origin = scriptOrigin()) {
4429
+ const cached = accessByOrigin.get(origin);
4430
+ if (cached) return cached;
4431
+ let access = "allowed";
4432
+ try {
4433
+ new Function("");
4434
+ } catch (error) {
4435
+ if (!isEvalBlocked(error)) throw error;
4436
+ access = "blocked_by_csp";
4437
+ }
4438
+ accessByOrigin.set(origin, access);
4439
+ return access;
4440
+ }
4441
+ function rememberScriptAccess(origin, access) {
4442
+ accessByOrigin.set(origin, access);
4443
+ }
4444
+ //#endregion
4302
4445
  //#region ../page-controller/src/scriptResult.ts
4303
4446
  /** Longest script result sent back to the model. Longer results are cut and say so. */
4304
4447
  var SCRIPT_RESULT_MAX_CHARS = 4e3;
@@ -4344,6 +4487,83 @@ function shouldRefresh(input) {
4344
4487
  return input.neverRead || input.ageSeconds > input.maxAgeSeconds;
4345
4488
  }
4346
4489
  //#endregion
4490
+ //#region ../page-controller/src/surfaceIndexes.ts
4491
+ /**
4492
+ * A point inside both the surface rectangle and the viewport.
4493
+ * `targetAt` rejects coordinates outside the viewport, so a center that falls outside is moved
4494
+ * into the visible overlap. Returns null when that overlap is empty or thinner than one pixel.
4495
+ */
4496
+ function visibleSurfacePoint(bounds, viewport) {
4497
+ if (!(viewport.width >= 1) || !(viewport.height >= 1)) return null;
4498
+ if (![
4499
+ bounds.x,
4500
+ bounds.y,
4501
+ bounds.width,
4502
+ bounds.height
4503
+ ].every(Number.isFinite)) return null;
4504
+ if (!(bounds.width > 0) || !(bounds.height > 0)) return null;
4505
+ const left = Math.max(bounds.x, 0);
4506
+ const top = Math.max(bounds.y, 0);
4507
+ const right = Math.min(bounds.x + bounds.width, viewport.width);
4508
+ const bottom = Math.min(bounds.y + bounds.height, viewport.height);
4509
+ if (right - left < 1 || bottom - top < 1) return null;
4510
+ const x = clamp(Math.round((left + right) / 2), 0, viewport.width - 1);
4511
+ const y = clamp(Math.round((top + bottom) / 2), 0, viewport.height - 1);
4512
+ if (x >= left && x < right && y >= top && y < bottom) return {
4513
+ x,
4514
+ y
4515
+ };
4516
+ const fallbackX = clamp(Math.floor(left), 0, viewport.width - 1);
4517
+ const fallbackY = clamp(Math.floor(top), 0, viewport.height - 1);
4518
+ if (fallbackX >= left && fallbackX < right && fallbackY >= top && fallbackY < bottom) return {
4519
+ x: fallbackX,
4520
+ y: fallbackY
4521
+ };
4522
+ return null;
4523
+ }
4524
+ function clamp(value, min, max) {
4525
+ return Math.min(max, Math.max(min, value));
4526
+ }
4527
+ /**
4528
+ * Appends one numbered line per surface that has bounds and no tree id.
4529
+ * A failed hit-test is skipped. The original observation is not mutated.
4530
+ */
4531
+ async function appendSurfaceIndexes(observation, surfaces, targetAt, viewport) {
4532
+ const ids = observation.ids.slice();
4533
+ const labels = observation.labels.slice();
4534
+ const lines = [];
4535
+ const points = /* @__PURE__ */ new Map();
4536
+ for (const surface of surfaces) {
4537
+ if (surface.id !== null) continue;
4538
+ const point = visibleSurfacePoint(surface.bounds, viewport);
4539
+ if (!point) continue;
4540
+ try {
4541
+ const hit = await targetAt(point.x, point.y);
4542
+ if (hit.tag.toLowerCase() !== surface.tag.toLowerCase()) continue;
4543
+ if (ids.includes(hit.id)) continue;
4544
+ const index = ids.length;
4545
+ const quoted = JSON.stringify(surface.label ?? "");
4546
+ ids.push(hit.id);
4547
+ labels.push(`${surface.tag} ${quoted}`);
4548
+ points.set(index, point);
4549
+ lines.push(`[${index}] ${surface.tag} ${quoted} (not in the tree; drag target for this read)`);
4550
+ } catch {}
4551
+ }
4552
+ if (lines.length === 0) return {
4553
+ observation,
4554
+ points
4555
+ };
4556
+ return {
4557
+ observation: {
4558
+ ...observation,
4559
+ text: `${observation.text.replace(/\s*$/, "")}\n${lines.join("\n")}`,
4560
+ ids,
4561
+ labels
4562
+ },
4563
+ points
4564
+ };
4565
+ }
4566
+ //#endregion
4347
4567
  //#region ../page-controller/src/PageController.ts
4348
4568
  /**
4349
4569
  * Copyright (C) 2025 Alibaba Group Holding Limited
@@ -4363,6 +4583,22 @@ function describeFailure(error) {
4363
4583
  if (error.code === "stale_id" || error.code === "stale_snapshot" || error.code === "stale_node") text += " The page changed since it was read: use the indexes of the next page state, and do not assume the same element is behind this index.";
4364
4584
  return text;
4365
4585
  }
4586
+ /** Window scroll position. A missing or non-finite value is reported as zero. */
4587
+ function readWindowScroll() {
4588
+ const x = window.scrollX;
4589
+ const y = window.scrollY;
4590
+ return {
4591
+ x: Number.isFinite(x) ? Math.round(x) : 0,
4592
+ y: Number.isFinite(y) ? Math.round(y) : 0
4593
+ };
4594
+ }
4595
+ /** Index actions that exist only on the accessibility tree. */
4596
+ function treeRequired(action) {
4597
+ return {
4598
+ success: false,
4599
+ message: `❌ ${action} needs the accessibility tree. This step is the element list, so these indexes cannot be used.`
4600
+ };
4601
+ }
4366
4602
  /**
4367
4603
  * PageController manages DOM state and element interactions.
4368
4604
  * It provides async methods for all DOM operations, keeping state isolated.
@@ -4398,8 +4634,19 @@ var PageController = class extends EventTarget {
4398
4634
  indexSource = "dom";
4399
4635
  /** The last accessibility read: index -> node ID and label. */
4400
4636
  axObservation = null;
4637
+ /**
4638
+ * Viewport point of a surface index added after the tree. The id behind that index is a visual
4639
+ * target, so later gestures use this point instead of looking the element up again.
4640
+ */
4641
+ surfacePoints = /* @__PURE__ */ new Map();
4401
4642
  /** Why the last read fell back from the accessibility tree to the element list, if it did. */
4402
4643
  fallbackNote = "";
4644
+ /**
4645
+ * Milliseconds of the last successful accessibility read, including surface indexes.
4646
+ * Null until that read succeeds. A fallback to the element list does not invent a duration.
4647
+ * This is not a precision score and it is not a speed budget.
4648
+ */
4649
+ lastTreeReadMs = null;
4403
4650
  /** Created on first use; the core behind it is loaded on the first capture. */
4404
4651
  accessibilityController = null;
4405
4652
  /** Accessibility interactions in progress that need the mask out of the way. */
@@ -4432,6 +4679,13 @@ var PageController = class extends EventTarget {
4432
4679
  async getLastUpdateTime() {
4433
4680
  return this.lastTimeUpdate;
4434
4681
  }
4682
+ /**
4683
+ * Duration of the last successful accessibility read, in milliseconds.
4684
+ * Null when that read has not succeeded. The number is not a precision score.
4685
+ */
4686
+ async getLastTreeReadMs() {
4687
+ return this.lastTreeReadMs;
4688
+ }
4435
4689
  /** Set by the agent: true while a task runs. Scripts never refresh the element list then. */
4436
4690
  isBusy = () => false;
4437
4691
  /**
@@ -4493,6 +4747,7 @@ var PageController = class extends EventTarget {
4493
4747
  ];
4494
4748
  if (tree.filteredNodes > 0) notes.push(`${tree.filteredNodes} nodes outside the viewport are not listed: scroll to list them.`);
4495
4749
  if (tree.hiddenNodes > 0) notes.push(`"… +N hidden" marks ${tree.hiddenNodes} nodes that did not fit: scroll so that fewer are in view.`);
4750
+ if (this.surfacePoints.size > 0) notes.push(`${this.surfacePoints.size} surface${this.surfacePoints.size === 1 ? "" : "s"} with no tree node (canvas, svg or role=application) are listed after the tree. The line gives the tag and label, not a role. The index is a drag target for this step only.`);
4496
4751
  elementsLabel = notes.join("\n");
4497
4752
  }
4498
4753
  const scrollHintAbove = pi.pixels_above > 4 && !fullPage ? `... ${pi.pixels_above} pixels above (${pi.pages_above.toFixed(1)} pages) - scroll to see more ...` : fullPage ? "[Start of full-page tree]" : "[Start of page]";
@@ -4539,7 +4794,7 @@ var PageController = class extends EventTarget {
4539
4794
  }
4540
4795
  /**
4541
4796
  * The ID of the accessibility node behind an index of the last read, for use with
4542
- * `accessibility` (hover, drag, keys and the other actions the index tools do not cover).
4797
+ * `accessibility` (the same node the index tools act on).
4543
4798
  */
4544
4799
  async accessibilityId(index) {
4545
4800
  return this.axTarget(index).id;
@@ -4614,6 +4869,7 @@ var PageController = class extends EventTarget {
4614
4869
  }
4615
4870
  this.indexSource = "dom";
4616
4871
  this.axObservation = null;
4872
+ this.surfacePoints.clear();
4617
4873
  if (this.mask) this.mask.wrapper.style.pointerEvents = "none";
4618
4874
  cleanUpHighlights();
4619
4875
  const blacklist = [...this.config.interactiveBlacklist || [], ...Array.from(document.querySelectorAll("[data-page-agent-not-interactive]"))];
@@ -4638,18 +4894,46 @@ var PageController = class extends EventTarget {
4638
4894
  async updateAccessibilityTree() {
4639
4895
  cleanUpHighlights();
4640
4896
  await this.mask?.startProgress();
4897
+ const started = performance.now();
4641
4898
  try {
4642
4899
  const observation = await this.accessibility.observeIndexed({ viewportExpansion: resolveViewportExpansion(this.config.viewportExpansion) });
4643
- this.axObservation = observation;
4644
- this.simplifiedHTML = observation.text;
4900
+ const indexed = await this.withSurfaceIndexes(observation);
4901
+ this.axObservation = indexed;
4902
+ this.simplifiedHTML = indexed.text;
4645
4903
  this.indexSource = "accessibility";
4646
4904
  this.selectorMap.clear();
4647
- this.elementTextMap = new Map(observation.labels.map((label, index) => [index, label]));
4905
+ this.elementTextMap = new Map(indexed.labels.map((label, index) => [index, label]));
4906
+ this.lastTreeReadMs = Math.round(performance.now() - started);
4907
+ if (this.config.logObservations !== false) console.log("%c[page-agent] accessibility read", LOG_STYLE, `${this.lastTreeReadMs}ms`);
4648
4908
  } finally {
4649
4909
  this.mask?.stopProgress();
4650
4910
  }
4651
4911
  }
4652
4912
  /**
4913
+ * Gives a numeric index to canvas, svg and role=application surfaces that are not tree nodes.
4914
+ * A failure here keeps the tree that was already read.
4915
+ */
4916
+ async withSurfaceIndexes(observation) {
4917
+ this.surfacePoints = /* @__PURE__ */ new Map();
4918
+ try {
4919
+ const indexed = await appendSurfaceIndexes(observation, await this.accessibility.surfaces(), async (x, y) => {
4920
+ const hit = await this.accessibility.targetAt(x, y);
4921
+ return {
4922
+ id: hit.id,
4923
+ tag: hit.tag
4924
+ };
4925
+ }, {
4926
+ width: window.innerWidth,
4927
+ height: window.innerHeight
4928
+ });
4929
+ this.surfacePoints = indexed.points;
4930
+ return indexed.observation;
4931
+ } catch (error) {
4932
+ console.warn("[PageController] surface indexes unavailable for this read", error);
4933
+ return observation;
4934
+ }
4935
+ }
4936
+ /**
4653
4937
  * Clean up all element highlights
4654
4938
  */
4655
4939
  async cleanUpHighlights() {
@@ -4791,11 +5075,115 @@ var PageController = class extends EventTarget {
4791
5075
  };
4792
5076
  }
4793
5077
  /**
5078
+ * Drag one index of the current read onto another.
5079
+ * Accessibility indexes only. The events are synthetic (`isTrusted` is false).
5080
+ * `html5` drops only when the destination cancels `dragover`.
5081
+ */
5082
+ async dragElement(sourceIndex, targetIndex, mode = "html5") {
5083
+ if (this.indexSource !== "accessibility") return {
5084
+ success: false,
5085
+ message: "❌ Drag needs the accessibility tree. This step is the element list, so these indexes cannot be dragged."
5086
+ };
5087
+ try {
5088
+ const source = this.axTarget(sourceIndex);
5089
+ const target = this.axTarget(targetIndex);
5090
+ const outcome = await this.accessibility.drag(source.id, target.id, mode);
5091
+ const followUp = mode === "html5" && outcome.status === "not_applied" ? " On the next step, call drag_element once with mode \"pointer-paced\". Neither result proves the effect." : "";
5092
+ return {
5093
+ success: outcome.status !== "not_applied",
5094
+ message: `📤 Dragged ${source.label} onto ${target.label} (${mode}). ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.` + followUp
5095
+ };
5096
+ } catch (error) {
5097
+ return {
5098
+ success: false,
5099
+ message: `❌ Failed to drag: ${describeFailure(error)}`
5100
+ };
5101
+ }
5102
+ }
5103
+ /** Synthetic hover. CSS `:hover` stays off. One index of this read. */
5104
+ async hoverElement(index) {
5105
+ if (this.indexSource !== "accessibility") return treeRequired("Hover");
5106
+ return this.axAction("hover element", index, (id) => this.accessibility.hover(id), (outcome, label) => `📤 Hover events sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`);
5107
+ }
5108
+ /**
5109
+ * Synthetic keydown and keyup. The key's native default does not run: no character is typed,
5110
+ * Tab does not move focus and Enter does not activate the control.
5111
+ */
5112
+ async pressKey(index, key, options = {}) {
5113
+ if (this.indexSource !== "accessibility") return treeRequired("Key");
5114
+ return this.axAction("press key", index, (id) => this.accessibility.pressKey(id, key, options), (outcome, label) => `📤 Key ${JSON.stringify(key)} sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`);
5115
+ }
5116
+ /** Synthetic double click. It does not select text the way a physical double click does. */
5117
+ async doubleClickElement(index) {
5118
+ if (this.indexSource !== "accessibility") return treeRequired("Double-click");
5119
+ return this.axAction("double-click element", index, (id) => this.accessibility.doubleClick(id), (outcome, label) => `📤 Double-click events sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`);
5120
+ }
5121
+ /**
5122
+ * Calls `focus()` on an index. The result says whether that element was focused right after.
5123
+ * Focus is not a saved change.
5124
+ */
5125
+ async focusElement(index) {
5126
+ if (this.indexSource !== "accessibility") return treeRequired("Focus");
5127
+ return this.axAction("focus element", index, (id) => this.accessibility.focus(id), (outcome, label) => outcome.status === "applied" ? `✅ Focus observed on ${label}. ${outcome.summary} Observed right after focus(). Not persisted. These indexes die on the next read.` : `⚠️ Focus was requested on ${label}. ${outcome.summary} Effect not observed. Not persisted. These indexes die on the next read.`);
5128
+ }
5129
+ /** Checks or unchecks a native checkbox, or selects a native radio. One index of this read. */
5130
+ async setChecked(index, checked) {
5131
+ if (this.indexSource !== "accessibility") return treeRequired("Set-checked");
5132
+ return this.axAction("set checked", index, (id) => this.accessibility.setChecked(id, checked), (outcome, label) => `📤 Set checked=${checked} on ${label}. ${outcome.summary} Not persisted. These indexes die on the next read.`);
5133
+ }
5134
+ /** Sets a native range input. A value the browser would clamp or round is refused by the core. */
5135
+ async setRange(index, value) {
5136
+ if (this.indexSource !== "accessibility") return treeRequired("Set-range");
5137
+ return this.axAction("set range", index, (id) => this.accessibility.setRange(id, value), (outcome, label) => `📤 Set range=${value} on ${label}. ${outcome.summary} Not persisted. These indexes die on the next read.`);
5138
+ }
5139
+ /**
5140
+ * Calls `scrollIntoView`. The message reports window scroll before and after.
5141
+ * A scroller inside the page is not measured. The status stays `requested`.
5142
+ */
5143
+ async scrollIntoView(index) {
5144
+ if (this.indexSource !== "accessibility") return treeRequired("Scroll-into-view");
5145
+ const before = readWindowScroll();
5146
+ const result = await this.axAction("scroll into view", index, (id) => this.accessibility.scrollIntoView(id), (_outcome, label) => `📤 scrollIntoView called on ${label}. Not persisted. These indexes die on the next read.`);
5147
+ const after = readWindowScroll();
5148
+ result.message += ` Window scroll went from (${before.x}, ${before.y}) to (${after.x}, ${after.y}). Nested scrollers were not measured.`;
5149
+ return result;
5150
+ }
5151
+ /**
5152
+ * One synthetic wheel event. It does not scroll. Without an index the event goes to the page.
5153
+ */
5154
+ async wheel(input) {
5155
+ if (this.indexSource !== "accessibility") return treeRequired("Wheel");
5156
+ const offsets = {
5157
+ x: input.x,
5158
+ y: input.y
5159
+ };
5160
+ if (input.index === void 0) try {
5161
+ return {
5162
+ success: true,
5163
+ message: `📤 Wheel event sent to the page. ${(await this.accessibility.wheel(offsets)).summary} Event sent. This tool did not scroll. Effect not verified: check the next page state. Not persisted.`
5164
+ };
5165
+ } catch (error) {
5166
+ return {
5167
+ success: false,
5168
+ message: `❌ Failed to wheel: ${describeFailure(error)}`
5169
+ };
5170
+ }
5171
+ return this.axAction("wheel", input.index, (id) => this.accessibility.wheel(id, offsets), (outcome, label) => `📤 Wheel event sent to ${label}. ${outcome.summary} Event sent. This tool did not scroll. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`);
5172
+ }
5173
+ /**
4794
5174
  * Execute arbitrary JavaScript on the page.
4795
5175
  * The optional `signal` is exposed to the script scope so cooperative code
4796
5176
  * can abort promptly when the task is stopped.
5177
+ *
5178
+ * When the page CSP disallows `unsafe-eval`, this does not call `eval`. The same origin
5179
+ * keeps that answer, and the message tells the agent not to try again.
4797
5180
  */
4798
5181
  async executeJavascript(script, signal, scope = {}) {
5182
+ const origin = scriptOrigin();
5183
+ if (generatedScriptAccess(origin) === "blocked_by_csp") return {
5184
+ success: false,
5185
+ message: SCRIPT_BLOCKED_BY_CSP
5186
+ };
4799
5187
  try {
4800
5188
  const names = Object.keys(scope);
4801
5189
  const asyncFunction = eval(`(async (${[...names, "signal"].join(", ")}) => { ${script} })`);
@@ -4805,6 +5193,13 @@ var PageController = class extends EventTarget {
4805
5193
  message: `✅ Executed JavaScript. Result: ${formatScriptResult(result)}`
4806
5194
  };
4807
5195
  } catch (error) {
5196
+ if (isEvalBlocked(error)) {
5197
+ rememberScriptAccess(origin, "blocked_by_csp");
5198
+ return {
5199
+ success: false,
5200
+ message: SCRIPT_BLOCKED_BY_CSP
5201
+ };
5202
+ }
4808
5203
  return {
4809
5204
  success: false,
4810
5205
  message: `❌ Error executing JavaScript: ${error}`
@@ -4839,6 +5234,7 @@ var PageController = class extends EventTarget {
4839
5234
  this.isIndexed = false;
4840
5235
  this.indexSource = "dom";
4841
5236
  this.axObservation = null;
5237
+ this.surfacePoints.clear();
4842
5238
  this.fallbackNote = "";
4843
5239
  this.accessibilityController?.destroy();
4844
5240
  this.accessibilityController = null;
@@ -6504,6 +6900,55 @@ function toolVisual(name, input, output) {
6504
6900
  tone: "act",
6505
6901
  summary: indexOf(input)
6506
6902
  };
6903
+ case "hover_element": return {
6904
+ icon: "cursor",
6905
+ tone: "move",
6906
+ summary: indexOf(input)
6907
+ };
6908
+ case "double_click_element": return {
6909
+ icon: "cursor",
6910
+ tone: "act",
6911
+ summary: indexOf(input)
6912
+ };
6913
+ case "press_key": return {
6914
+ icon: "keyboard",
6915
+ tone: "act",
6916
+ summary: truncate(textOf(args.key), 24)
6917
+ };
6918
+ case "focus_element": return {
6919
+ icon: "cursor",
6920
+ tone: "act",
6921
+ summary: indexOf(input)
6922
+ };
6923
+ case "set_checked": return {
6924
+ icon: "check",
6925
+ tone: "act",
6926
+ summary: `${indexOf(input)} ${args.checked === false ? "off" : "on"}`.trim()
6927
+ };
6928
+ case "set_range": return {
6929
+ icon: "list",
6930
+ tone: "act",
6931
+ summary: `${indexOf(input)} ${textOf(args.value)}`.trim()
6932
+ };
6933
+ case "scroll_into_view": return {
6934
+ icon: "scroll",
6935
+ tone: "move",
6936
+ summary: indexOf(input)
6937
+ };
6938
+ case "wheel": return {
6939
+ icon: "scroll",
6940
+ tone: "move",
6941
+ summary: textOf(args.delta_y) || indexOf(input)
6942
+ };
6943
+ case "drag_element": {
6944
+ const from = input?.source_index;
6945
+ const to = input?.target_index;
6946
+ return {
6947
+ icon: "cursor",
6948
+ tone: "move",
6949
+ summary: typeof from === "number" && typeof to === "number" ? `#${from} → #${to}` : ""
6950
+ };
6951
+ }
6507
6952
  case "input_text": return {
6508
6953
  icon: "keyboard",
6509
6954
  tone: "act",