|
| 1 | +"""Native TypeSafe Jev decisions, without a chat/LLM compatibility layer.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import json |
| 5 | +import logging |
| 6 | +import math |
| 7 | +import time |
| 8 | +from contextlib import suppress |
| 9 | +from io import BytesIO |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +from llama_index.core.base.llms.types import ChatMessage, ToolCallBlock |
| 13 | +from PIL import Image as PILImage |
| 14 | +from PIL import ImageOps, UnidentifiedImageError |
| 15 | + |
| 16 | +from mobilerun.agent.selectors.base import SelectionRequest |
| 17 | +from mobilerun.agent.selectors.decision import Decision |
| 18 | +from mobilerun.config_manager.config_manager import AgentConfig |
| 19 | +from mobilerun.config_manager.prompt_loader import PromptLoader |
| 20 | + |
| 21 | +logger = logging.getLogger("mobilerun") |
| 22 | + |
| 23 | + |
| 24 | +async def _log_request_progress(started: float) -> None: |
| 25 | + """Keep slow uploads visibly distinct from a stalled agent loop.""" |
| 26 | + while True: |
| 27 | + await asyncio.sleep(5) |
| 28 | + logger.info( |
| 29 | + "Jev request still in flight (%.0fs); waiting for TypeSafe.", |
| 30 | + time.monotonic() - started, |
| 31 | + ) |
| 32 | + |
| 33 | + |
| 34 | +def _prepare_screenshot(screenshot: bytes) -> bytes: |
| 35 | + return _prepare_image(screenshot)[0] |
| 36 | + |
| 37 | + |
| 38 | +def _prepare_image(screenshot: bytes) -> tuple[bytes, tuple[float, float]]: |
| 39 | + """Fit TypeSafe's 280–1568px per-side limits without cropping the UI. |
| 40 | +
|
| 41 | + https://docs.typesafe.ai/images#limits |
| 42 | + Jev selects element-index actions, so this provider-local resize must not |
| 43 | + change the UI state's native bounds or the driver's tap coordinates. |
| 44 | + """ |
| 45 | + try: |
| 46 | + with PILImage.open(BytesIO(screenshot)) as original: |
| 47 | + if getattr(original, "is_animated", False): |
| 48 | + raise ValueError("TypeSafe screenshots must be still images") |
| 49 | + image = ImageOps.exif_transpose(original).convert("RGB") |
| 50 | + except (UnidentifiedImageError, OSError) as exc: |
| 51 | + raise ValueError("TypeSafe requires a valid screenshot image") from exc |
| 52 | + |
| 53 | + width, height = image.size |
| 54 | + scale = min(1.0, 1568 / max(width, height)) |
| 55 | + if min(width, height) * scale < 280: |
| 56 | + scale = min(280 / min(width, height), 1568 / max(width, height)) |
| 57 | + size = (max(1, round(width * scale)), max(1, round(height * scale))) |
| 58 | + if size != image.size: |
| 59 | + image = image.resize(size, PILImage.Resampling.LANCZOS) |
| 60 | + # Very narrow/tall images cannot satisfy both limits by scaling alone. |
| 61 | + padded = (max(280, size[0]), max(280, size[1])) |
| 62 | + image = ImageOps.pad(image, padded, color="white", centering=(0, 0)) |
| 63 | + output = BytesIO() |
| 64 | + # Full-screen PNGs with wallpaper and coordinate grids can exceed 700 KB. |
| 65 | + # Baseline JPEG is supported by TypeSafe and keeps the same dimensions and |
| 66 | + # full UI while substantially reducing upload time on slow connections. |
| 67 | + image.save(output, format="JPEG", quality=85, optimize=True, progressive=False) |
| 68 | + # Share of the sent image the screenshot covers; padding is right/bottom. |
| 69 | + return output.getvalue(), (size[0] / padded[0], size[1] / padded[1]) |
| 70 | + |
| 71 | + |
| 72 | +MAX_CHOICES = 255 |
| 73 | + |
| 74 | + |
| 75 | +_LOCATE_INSTRUCTIONS = ( |
| 76 | + "If the chosen action taps an on-screen element, the element to tap." |
| 77 | +) |
| 78 | + |
| 79 | + |
| 80 | +_LOCATE_UI = ( |
| 81 | + "No accessibility tree is available. Use the screenshot; an on-screen tap " |
| 82 | + "is located on it." |
| 83 | +) |
| 84 | + |
| 85 | + |
| 86 | +def _history_item(item: Any) -> Any: |
| 87 | + """Serialize a history message, keeping native tool calls and their ids.""" |
| 88 | + if not isinstance(item, ChatMessage): |
| 89 | + return item |
| 90 | + entry: dict[str, Any] = {"role": item.role.value, "content": item.content or ""} |
| 91 | + calls = [] |
| 92 | + for block in item.blocks: |
| 93 | + if isinstance(block, ToolCallBlock): |
| 94 | + arguments = block.tool_kwargs |
| 95 | + if isinstance(arguments, str): |
| 96 | + with suppress(ValueError): |
| 97 | + arguments = json.loads(arguments) if arguments.strip() else {} |
| 98 | + calls.append( |
| 99 | + { |
| 100 | + "id": block.tool_call_id, |
| 101 | + "name": block.tool_name, |
| 102 | + "parameters": arguments, |
| 103 | + } |
| 104 | + ) |
| 105 | + if calls: |
| 106 | + entry["tool_calls"] = calls |
| 107 | + call_id = item.additional_kwargs.get("tool_call_id") |
| 108 | + if call_id: |
| 109 | + entry["tool_call_id"] = call_id |
| 110 | + return entry |
| 111 | + |
| 112 | + |
| 113 | +class TypeSafeDecisionModel: |
| 114 | + """Choose only among supplied actions; abstain on low-confidence answers. |
| 115 | +
|
| 116 | + SDK constructor options (including api_key, base_url and timeout) are |
| 117 | + forwarded unchanged. Authentication defaults to TYPESAFE_API_KEY. |
| 118 | + """ |
| 119 | + |
| 120 | + screenshot_max_side = 1568 |
| 121 | + # A Choice accepts 255 options, three of which are abstain and completion. |
| 122 | + max_options = MAX_CHOICES - 3 |
| 123 | + # Box locates on-screen taps, so screenshot-only screens need no grid. |
| 124 | + locates_points = True |
| 125 | + |
| 126 | + def __init__( |
| 127 | + self, |
| 128 | + model: str | None = None, |
| 129 | + min_confidence: float = 0.0, |
| 130 | + **kwargs: Any, |
| 131 | + ): |
| 132 | + if not 0 <= min_confidence <= 1: |
| 133 | + raise ValueError("min_confidence must be between 0 and 1") |
| 134 | + try: |
| 135 | + from typesafe_sdk import AsyncTypeSafeClient |
| 136 | + except ImportError as exc: |
| 137 | + raise ImportError( |
| 138 | + "TypeSafe decision models require the TypeSafe SDK. " |
| 139 | + 'Install it with: pip install "mobilerun[typesafe]"' |
| 140 | + ) from exc |
| 141 | + self._client_type = AsyncTypeSafeClient |
| 142 | + self._client_kwargs = dict(kwargs) |
| 143 | + if model is not None: |
| 144 | + self._client_kwargs["model"] = model |
| 145 | + self.min_confidence = min_confidence |
| 146 | + |
| 147 | + async def decide(self, request: SelectionRequest) -> Decision | None: |
| 148 | + from typesafe_sdk import Choice |
| 149 | + |
| 150 | + if not request.options: |
| 151 | + raise ValueError("TypeSafe decisions require non-empty action options") |
| 152 | + |
| 153 | + # Opaque, unique labels preserve option identity even when descriptions |
| 154 | + # collide. The returned label is never interpreted as a tool call. |
| 155 | + indices = {f"action_{i}": i for i in range(len(request.options))} |
| 156 | + criteria: dict[str, Any] = { |
| 157 | + label: { |
| 158 | + "description": request.options[i].description, |
| 159 | + "tool": request.options[i].action.name, |
| 160 | + "parameters": request.options[i].action.parameters, |
| 161 | + } |
| 162 | + for label, i in indices.items() |
| 163 | + } |
| 164 | + criteria["abstain"] = "None of the available actions safely advances the goal." |
| 165 | + if "complete" in request.tools: |
| 166 | + criteria["complete_success"] = ( |
| 167 | + "The goal is already achieved, as verified by the current state." |
| 168 | + ) |
| 169 | + criteria["complete_failure"] = ( |
| 170 | + "The goal cannot be achieved with the available capabilities." |
| 171 | + ) |
| 172 | + if len(criteria) > MAX_CHOICES: |
| 173 | + raise ValueError( |
| 174 | + f"TypeSafe accepts at most {MAX_CHOICES} choices, got {len(criteria)}" |
| 175 | + ) |
| 176 | + |
| 177 | + state: dict[str, Any] = { |
| 178 | + "goal": request.goal, |
| 179 | + "memory": request.memory, |
| 180 | + "history": [_history_item(item) for item in request.history], |
| 181 | + "variables": request.variables, |
| 182 | + } |
| 183 | + locating = request.screenshot is not None and any( |
| 184 | + option.point_space for option in request.options |
| 185 | + ) |
| 186 | + if request.state is not None: |
| 187 | + state.update( |
| 188 | + # Screenshot-only text describes the LLMs' coordinate grid, |
| 189 | + # which the clean screenshot sent here does not have. |
| 190 | + ui=_LOCATE_UI if locating else request.state.formatted_text, |
| 191 | + focused_text=request.state.focused_text, |
| 192 | + phone_state=request.state.phone_state, |
| 193 | + ) |
| 194 | + request_kwargs: dict[str, Any] = {} |
| 195 | + questions: dict[str, Any] = {} |
| 196 | + if request.screenshot is not None: |
| 197 | + from typesafe_sdk import Image |
| 198 | + |
| 199 | + prepared_screenshot, coverage = _prepare_image(request.screenshot) |
| 200 | + state["screenshot"] = Image(prepared_screenshot) |
| 201 | + if locating: |
| 202 | + from typesafe_sdk import Box |
| 203 | + |
| 204 | + questions["target"] = Box(instructions=_LOCATE_INSTRUCTIONS) |
| 205 | + # Vision is already explicitly enabled by the caller. TypeSafe also |
| 206 | + # requires this per-request opt-in for its experimental image API. |
| 207 | + request_kwargs["extra_headers"] = {"TypeSafe-Danger-Zone-Images": "true"} |
| 208 | + |
| 209 | + instructions = request.instructions |
| 210 | + if not instructions: |
| 211 | + instructions = await PromptLoader.load_prompt( |
| 212 | + AgentConfig().get_decision_system_prompt_path(), |
| 213 | + request.get_decision_prompt_variables(), |
| 214 | + ) |
| 215 | + started = time.monotonic() |
| 216 | + logger.info( |
| 217 | + "Jev selecting from %d actions%s...", |
| 218 | + len(request.options), |
| 219 | + ( |
| 220 | + f" (image {len(prepared_screenshot) / 1024:.0f} KiB)" |
| 221 | + if request.screenshot is not None |
| 222 | + else "" |
| 223 | + ), |
| 224 | + ) |
| 225 | + progress = asyncio.create_task(_log_request_progress(started)) |
| 226 | + # A scoped client avoids leaking HTTP resources, including on cancellation. |
| 227 | + try: |
| 228 | + async with self._client_type(**self._client_kwargs) as client: |
| 229 | + result = await client.system_one( |
| 230 | + state=state, |
| 231 | + questions={ |
| 232 | + "action": Choice(instructions=instructions, criteria=criteria), |
| 233 | + **questions, |
| 234 | + }, |
| 235 | + **request_kwargs, |
| 236 | + ) |
| 237 | + finally: |
| 238 | + progress.cancel() |
| 239 | + with suppress(asyncio.CancelledError): |
| 240 | + await progress |
| 241 | + answer = result.choices.get("action") |
| 242 | + target = result.boxes.get("target") if questions else None |
| 243 | + logger.info( |
| 244 | + "Jev returned %s (confidence=%s)%s in %.2fs.", |
| 245 | + getattr(answer, "choice", "<missing>"), |
| 246 | + getattr(answer, "confidence", None), |
| 247 | + ( |
| 248 | + f", target {target.box} (confidence={target.confidence})" |
| 249 | + if target is not None |
| 250 | + else "" |
| 251 | + ), |
| 252 | + time.monotonic() - started, |
| 253 | + ) |
| 254 | + if answer is None or answer.choice not in criteria: |
| 255 | + raise ValueError("TypeSafe returned an unknown or missing action choice") |
| 256 | + confidence = answer.confidence |
| 257 | + if not math.isfinite(confidence) or not 0 <= confidence <= 1: |
| 258 | + raise ValueError("TypeSafe returned an invalid action confidence") |
| 259 | + if confidence < self.min_confidence or answer.choice == "abstain": |
| 260 | + return None |
| 261 | + if answer.choice in {"complete_success", "complete_failure"}: |
| 262 | + success = answer.choice == "complete_success" |
| 263 | + return Decision( |
| 264 | + confidence=confidence, |
| 265 | + success=success, |
| 266 | + message=( |
| 267 | + "Goal achieved." |
| 268 | + if success |
| 269 | + else "Goal cannot be achieved with the available actions." |
| 270 | + ), |
| 271 | + ) |
| 272 | + index = indices[answer.choice] |
| 273 | + if request.options[index].point_space is None: |
| 274 | + return Decision(option_index=index, confidence=confidence) |
| 275 | + if target is None: |
| 276 | + raise ValueError("TypeSafe did not locate the on-screen tap") |
| 277 | + if target.confidence is not None and not ( |
| 278 | + math.isfinite(target.confidence) |
| 279 | + and target.confidence >= self.min_confidence |
| 280 | + ): |
| 281 | + return None |
| 282 | + box = target.box |
| 283 | + return Decision( |
| 284 | + option_index=index, |
| 285 | + confidence=confidence, |
| 286 | + point=( |
| 287 | + min(1.0, (box.left + box.right) / 2 / coverage[0]), |
| 288 | + min(1.0, (box.top + box.bottom) / 2 / coverage[1]), |
| 289 | + ), |
| 290 | + ) |
0 commit comments