|
| 1 | +""" |
| 2 | +Action Executor for Sentience Agent. |
| 3 | +
|
| 4 | +Handles parsing and execution of action commands (CLICK, TYPE, PRESS, FINISH). |
| 5 | +This separates action execution concerns from LLM interaction. |
| 6 | +""" |
| 7 | + |
| 8 | +import re |
| 9 | +from typing import Any, Union |
| 10 | + |
| 11 | +from .actions import click, click_async, press, press_async, type_text, type_text_async |
| 12 | +from .browser import AsyncSentienceBrowser, SentienceBrowser |
| 13 | +from .models import Snapshot |
| 14 | +from .protocols import AsyncBrowserProtocol, BrowserProtocol |
| 15 | + |
| 16 | + |
| 17 | +class ActionExecutor: |
| 18 | + """ |
| 19 | + Executes actions and handles parsing of action command strings. |
| 20 | +
|
| 21 | + This class encapsulates all action execution logic, making it easier to: |
| 22 | + - Test action execution independently |
| 23 | + - Add new action types in one place |
| 24 | + - Handle action parsing errors consistently |
| 25 | + """ |
| 26 | + |
| 27 | + def __init__( |
| 28 | + self, |
| 29 | + browser: SentienceBrowser | AsyncSentienceBrowser | BrowserProtocol | AsyncBrowserProtocol, |
| 30 | + ): |
| 31 | + """ |
| 32 | + Initialize action executor. |
| 33 | +
|
| 34 | + Args: |
| 35 | + browser: SentienceBrowser, AsyncSentienceBrowser, or protocol-compatible instance |
| 36 | + (for testing, can use mock objects that implement BrowserProtocol) |
| 37 | + """ |
| 38 | + self.browser = browser |
| 39 | + # Check if browser is async - support both concrete types and protocols |
| 40 | + # Check concrete types first (most reliable) |
| 41 | + if isinstance(browser, AsyncSentienceBrowser): |
| 42 | + self._is_async = True |
| 43 | + elif isinstance(browser, SentienceBrowser): |
| 44 | + self._is_async = False |
| 45 | + else: |
| 46 | + # For protocol-based browsers, check if methods are actually async |
| 47 | + # This is more reliable than isinstance checks which can match both protocols |
| 48 | + import inspect |
| 49 | + |
| 50 | + start_method = getattr(browser, "start", None) |
| 51 | + if start_method and inspect.iscoroutinefunction(start_method): |
| 52 | + self._is_async = True |
| 53 | + elif isinstance(browser, BrowserProtocol): |
| 54 | + # If it implements BrowserProtocol and start is not async, it's sync |
| 55 | + self._is_async = False |
| 56 | + else: |
| 57 | + # Default to sync for unknown types |
| 58 | + self._is_async = False |
| 59 | + |
| 60 | + def execute(self, action_str: str, snap: Snapshot) -> dict[str, Any]: |
| 61 | + """ |
| 62 | + Parse action string and execute SDK call (synchronous). |
| 63 | +
|
| 64 | + Args: |
| 65 | + action_str: Action string from LLM (e.g., "CLICK(42)", "TYPE(15, \"text\")") |
| 66 | + snap: Current snapshot (for context, currently unused but kept for API consistency) |
| 67 | +
|
| 68 | + Returns: |
| 69 | + Execution result dictionary with keys: |
| 70 | + - success: bool |
| 71 | + - action: str (e.g., "click", "type", "press", "finish") |
| 72 | + - element_id: Optional[int] (for click/type actions) |
| 73 | + - text: Optional[str] (for type actions) |
| 74 | + - key: Optional[str] (for press actions) |
| 75 | + - outcome: Optional[str] (action outcome) |
| 76 | + - url_changed: Optional[bool] (for click actions) |
| 77 | + - error: Optional[str] (if action failed) |
| 78 | + - message: Optional[str] (for finish action) |
| 79 | +
|
| 80 | + Raises: |
| 81 | + ValueError: If action format is unknown |
| 82 | + RuntimeError: If called on async browser (use execute_async instead) |
| 83 | + """ |
| 84 | + if self._is_async: |
| 85 | + raise RuntimeError( |
| 86 | + "ActionExecutor.execute() called on async browser. Use execute_async() instead." |
| 87 | + ) |
| 88 | + |
| 89 | + # Parse CLICK(42) |
| 90 | + if match := re.match(r"CLICK\s*\(\s*(\d+)\s*\)", action_str, re.IGNORECASE): |
| 91 | + element_id = int(match.group(1)) |
| 92 | + result = click(self.browser, element_id) # type: ignore |
| 93 | + return { |
| 94 | + "success": result.success, |
| 95 | + "action": "click", |
| 96 | + "element_id": element_id, |
| 97 | + "outcome": result.outcome, |
| 98 | + "url_changed": result.url_changed, |
| 99 | + } |
| 100 | + |
| 101 | + # Parse TYPE(42, "hello world") |
| 102 | + elif match := re.match( |
| 103 | + r'TYPE\s*\(\s*(\d+)\s*,\s*["\']([^"\']*)["\']\s*\)', |
| 104 | + action_str, |
| 105 | + re.IGNORECASE, |
| 106 | + ): |
| 107 | + element_id = int(match.group(1)) |
| 108 | + text = match.group(2) |
| 109 | + result = type_text(self.browser, element_id, text) # type: ignore |
| 110 | + return { |
| 111 | + "success": result.success, |
| 112 | + "action": "type", |
| 113 | + "element_id": element_id, |
| 114 | + "text": text, |
| 115 | + "outcome": result.outcome, |
| 116 | + } |
| 117 | + |
| 118 | + # Parse PRESS("Enter") |
| 119 | + elif match := re.match(r'PRESS\s*\(\s*["\']([^"\']+)["\']\s*\)', action_str, re.IGNORECASE): |
| 120 | + key = match.group(1) |
| 121 | + result = press(self.browser, key) # type: ignore |
| 122 | + return { |
| 123 | + "success": result.success, |
| 124 | + "action": "press", |
| 125 | + "key": key, |
| 126 | + "outcome": result.outcome, |
| 127 | + } |
| 128 | + |
| 129 | + # Parse FINISH() |
| 130 | + elif re.match(r"FINISH\s*\(\s*\)", action_str, re.IGNORECASE): |
| 131 | + return { |
| 132 | + "success": True, |
| 133 | + "action": "finish", |
| 134 | + "message": "Task marked as complete", |
| 135 | + } |
| 136 | + |
| 137 | + else: |
| 138 | + raise ValueError( |
| 139 | + f"Unknown action format: {action_str}\n" |
| 140 | + f'Expected: CLICK(id), TYPE(id, "text"), PRESS("key"), or FINISH()' |
| 141 | + ) |
| 142 | + |
| 143 | + async def execute_async(self, action_str: str, snap: Snapshot) -> dict[str, Any]: |
| 144 | + """ |
| 145 | + Parse action string and execute SDK call (asynchronous). |
| 146 | +
|
| 147 | + Args: |
| 148 | + action_str: Action string from LLM (e.g., "CLICK(42)", "TYPE(15, \"text\")") |
| 149 | + snap: Current snapshot (for context, currently unused but kept for API consistency) |
| 150 | +
|
| 151 | + Returns: |
| 152 | + Execution result dictionary (same format as execute()) |
| 153 | +
|
| 154 | + Raises: |
| 155 | + ValueError: If action format is unknown |
| 156 | + RuntimeError: If called on sync browser (use execute() instead) |
| 157 | + """ |
| 158 | + if not self._is_async: |
| 159 | + raise RuntimeError( |
| 160 | + "ActionExecutor.execute_async() called on sync browser. Use execute() instead." |
| 161 | + ) |
| 162 | + |
| 163 | + # Parse CLICK(42) |
| 164 | + if match := re.match(r"CLICK\s*\(\s*(\d+)\s*\)", action_str, re.IGNORECASE): |
| 165 | + element_id = int(match.group(1)) |
| 166 | + result = await click_async(self.browser, element_id) # type: ignore |
| 167 | + return { |
| 168 | + "success": result.success, |
| 169 | + "action": "click", |
| 170 | + "element_id": element_id, |
| 171 | + "outcome": result.outcome, |
| 172 | + "url_changed": result.url_changed, |
| 173 | + } |
| 174 | + |
| 175 | + # Parse TYPE(42, "hello world") |
| 176 | + elif match := re.match( |
| 177 | + r'TYPE\s*\(\s*(\d+)\s*,\s*["\']([^"\']*)["\']\s*\)', |
| 178 | + action_str, |
| 179 | + re.IGNORECASE, |
| 180 | + ): |
| 181 | + element_id = int(match.group(1)) |
| 182 | + text = match.group(2) |
| 183 | + result = await type_text_async(self.browser, element_id, text) # type: ignore |
| 184 | + return { |
| 185 | + "success": result.success, |
| 186 | + "action": "type", |
| 187 | + "element_id": element_id, |
| 188 | + "text": text, |
| 189 | + "outcome": result.outcome, |
| 190 | + } |
| 191 | + |
| 192 | + # Parse PRESS("Enter") |
| 193 | + elif match := re.match(r'PRESS\s*\(\s*["\']([^"\']+)["\']\s*\)', action_str, re.IGNORECASE): |
| 194 | + key = match.group(1) |
| 195 | + result = await press_async(self.browser, key) # type: ignore |
| 196 | + return { |
| 197 | + "success": result.success, |
| 198 | + "action": "press", |
| 199 | + "key": key, |
| 200 | + "outcome": result.outcome, |
| 201 | + } |
| 202 | + |
| 203 | + # Parse FINISH() |
| 204 | + elif re.match(r"FINISH\s*\(\s*\)", action_str, re.IGNORECASE): |
| 205 | + return { |
| 206 | + "success": True, |
| 207 | + "action": "finish", |
| 208 | + "message": "Task marked as complete", |
| 209 | + } |
| 210 | + |
| 211 | + else: |
| 212 | + raise ValueError( |
| 213 | + f"Unknown action format: {action_str}\n" |
| 214 | + f'Expected: CLICK(id), TYPE(id, "text"), PRESS("key"), or FINISH()' |
| 215 | + ) |
0 commit comments