The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(computer_use): compact permissions/vision_routing/backend/__init__ docstrings and spacing
Teknium7e939af62741
diff --git a/tools/computer_use/__init__.py b/tools/computer_use/__init__.pyindex eb2a9714b13..4de6c2bb6ad 100644--- a/tools/computer_use/__init__.py+++ b/tools/computer_use/__init__.py@@ -1,17 +1,14 @@"""Computer use toolset — universal (any-model) desktop control via cua-driver.-Drives apps through cua-driver's background primitive (focus-without-raise +-pid-scoped event posting): it does NOT steal the user's cursor, keyboard focus,-or Space. Plain OpenAI function-calling schema; vision models get SOM captures-(numbered overlays + AX tree) and click by index, non-vision models use the AX-tree alone. Model-facing guidance lives in the schema description and each-action result's `verdict`.+Drives apps through cua-driver's background primitive (focus-without-raise + pid-scoped+event posting): it does NOT steal the user's cursor, keyboard focus, or Space. Plain+OpenAI function-calling schema; vision models get SOM captures (numbered overlays + AX+tree) and click by index, non-vision models use the AX tree alone. Model-facing guidance+lives in the schema description and each action result's `verdict`.-* `tool.py` — `computer_use` handler, approval gate, response shaping.-* `backend.py` — abstract `ComputerUseBackend` + result dataclasses.-* `cua_backend.py` — default backend (MCP over stdio to `cua-driver`), with- `cua_backend_parse` / `_session` / `_daemon` siblings.-* `schema.py` — the model-facing schema (byte-frozen).+Modules: `tool.py` (handler, approval gate, response shaping), `backend.py` (abstract+`ComputerUseBackend` + result dataclasses), `cua_backend.py` (default MCP-over-stdio+backend + `cua_backend_parse`/`_session`/`_daemon` siblings), `schema.py` (byte-frozen)."""from __future__ import annotationsdiff --git a/tools/computer_use/backend.py b/tools/computer_use/backend.pyindex ee255ef7a31..b2b334a5071 100644--- a/tools/computer_use/backend.py+++ b/tools/computer_use/backend.py@@ -16,11 +16,9 @@ _JPEG_SOF_MARKERS = frozenset({0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0def image_dimensions_from_bytes(raw: bytes) -> Optional[Tuple[int, int]]:- """Return (width, height) for PNG / JPEG bytes, or None when unreadable.-- PNG: IHDR. JPEG: walk segments (skipping 0xFF fill bytes) to the first SOF- marker; stop at SOS. Used by the tool layer's provider min-size guard.- """+ """(width, height) for PNG / JPEG bytes, or None when unreadable. PNG: IHDR. JPEG: walk+ segments (skipping 0xFF fill bytes) to the first SOF marker; stop at SOS. Used by the+ tool layer's provider min-size guard."""if raw.startswith(b"\x89PNG\r\n\x1a\n") and len(raw) >= 24:try:width, height = struct.unpack(">II", raw[16:24])@@ -77,13 +75,9 @@ class UIElement:@dataclassclass CaptureResult:- """Result of a screen capture call.-- At least one of png_b64 / elements is populated depending on capture mode:- mode="vision" → png_b64 only; mode="ax" → elements only; mode="som" (default)- → both: the PNG already carries numbered overlays drawn by the backend and- `elements` holds the matching index → element mapping.- """+ """Result of a screen capture call. mode="vision" → png_b64 only; mode="ax" → elements+ only; mode="som" (default) → both: the PNG already carries numbered overlays drawn by+ the backend and `elements` holds the matching index → element mapping."""mode: strwidth: int # screenshot width (logical px, pre-Anthropic-scale)@@ -105,11 +99,10 @@ class CaptureResult:class ActionResult:"""Result of any action (click / type / scroll / drag / key / wait).- ``ok`` is tool/transport success only — NOT the semantic verdict. Read- ``effect`` / ``escalation`` (cua-driver's structured verdict) to decide the- next rung of the verify → escalate ladder. All structured fields are optional- and additive: an older driver that omits ``structuredContent`` leaves them- ``None`` and behavior is unchanged.+ ``ok`` is tool/transport success only — NOT the semantic verdict; read ``effect`` /+ ``escalation`` (cua-driver's structured verdict) to pick the next rung of the+ verify → escalate ladder. Structured fields are optional and additive: an older+ driver that omits ``structuredContent`` leaves them ``None``, behavior unchanged."""ok: booldiff --git a/tools/computer_use/permissions.py b/tools/computer_use/permissions.pyindex 5c69d63e4e5..3521af89f86 100644--- a/tools/computer_use/permissions.py+++ b/tools/computer_use/permissions.py@@ -1,15 +1,12 @@"""Cross-platform Computer Use readiness + macOS permission helpers.-"Ready to drive" differs per platform: macOS needs explicit TCC grants-(Accessibility + Screen Recording) reported/requested via cua-driver-``permissions status`` / ``permissions grant``; Windows/Linux have no TCC-toggles, so readiness == driver health. The grants attach to cua-driver's OWN-identity (``com.trycua.driver``), not Hermes, so ``grant`` launches CuaDriver-via LaunchServices for correct dialog attribution.--``cua-driver doctor --json`` is the universal signal; ``computer_use_status``-folds it with the macOS detail into one payload for the desktop card, the-``hermes computer-use permissions`` CLI and ``/api/tools/computer-use/status``.+"Ready to drive" differs per platform: macOS needs explicit TCC grants (Accessibility ++Screen Recording) via cua-driver ``permissions status`` / ``permissions grant``;+Windows/Linux have no TCC toggles, so readiness == driver health. The grants attach to+cua-driver's OWN identity (``com.trycua.driver``), not Hermes, so ``grant`` launches+CuaDriver via LaunchServices for correct dialog attribution. ``cua-driver doctor --json``+is the universal signal; ``computer_use_status`` folds it with the macOS detail into one+payload for the desktop card, the ``permissions`` CLI and ``/api/tools/computer-use/status``."""from __future__ import annotations@@ -30,46 +27,39 @@ _BOOLS = ("accessibility", "screen_recording", "screen_recording_capturable")def _resolve_driver_cmd(override: Optional[str]) -> Optional[str]:"""Use the runtime resolver for UI status and permission commands too."""from tools.computer_use.cua_backend import resolve_cua_driver_cmd-return resolve_cua_driver_cmd(override)-def _child_env() -> Dict[str, str]:"""cua-driver child env (telemetry policy + provider secrets stripped);degrades to ``os.environ`` on import error so probes never break."""try:from tools.computer_use.cua_backend import sanitized_cua_driver_env-return sanitized_cua_driver_env()except Exception:return dict(os.environ)-def _run(binary: str, *args: str, timeout: float) -> subprocess.CompletedProcess:return subprocess.run([binary, *args], capture_output=True, text=True, encoding='utf-8',errors='replace', timeout=timeout, env=_child_env(),stdin=subprocess.DEVNULL, creationflags=windows_hide_flags())-def _json_out(binary: str, *args: str, timeout: float) -> Any:"""Run ``binary args`` and parse stdout as JSON (``None`` on empty output)."""raw = (_run(binary, *args, timeout=timeout).stdout or "").strip()return json.loads(raw) if raw else None-def _doctor(binary: str) -> Optional[Dict[str, Any]]:"""``cua-driver doctor --json`` → ``{ok, checks:[{label,status,message}]}``."""try:data = _json_out(binary, "doctor", "--json", timeout=12)except Exception:- return None+ data = Noneif not isinstance(data, dict):return Nonechecks = [{k: str(p.get(k, "")) for k in ("label", "status", "message")}for p in data.get("probes", []) if isinstance(p, dict)]return {"ok": bool(data.get("ok")), "checks": checks}-def _mac_permissions(binary: str, out: Dict[str, Any]) -> None:"""Fold ``cua-driver permissions status --json`` booleans into ``out``."""try:diff --git a/tools/computer_use/vision_routing.py b/tools/computer_use/vision_routing.pyindex 7b60986f8dc..009489544f6 100644--- a/tools/computer_use/vision_routing.py+++ b/tools/computer_use/vision_routing.py@@ -28,14 +28,10 @@ from typing import Any, Dict, Optionallogger = logging.getLogger(__name__)-def _explicit_aux_vision_override(cfg: Optional[Dict[str, Any]]) -> bool:- """True when ``auxiliary.vision`` carries a non-default user override.-- Mirrors ``agent.image_routing._explicit_aux_vision_override`` so the capture- path and the user-attached-image path agree. ``provider: "auto"``, blank- values, or a missing block all count as *not* explicit.- """+ """True when ``auxiliary.vision`` carries a non-default user override. Mirrors+ ``agent.image_routing._explicit_aux_vision_override`` so the capture path and the+ user-attached-image path agree; ``provider: "auto"``, blanks or a missing block are *not* explicit."""aux = cfg.get("auxiliary") if isinstance(cfg, dict) else Nonevision = aux.get("vision") if isinstance(aux, dict) else Noneif not isinstance(vision, dict):@@ -45,25 +41,19 @@ def _explicit_aux_vision_override(cfg: Optional[Dict[str, Any]]) -> bool:base_url = str(vision.get("base_url") or "").strip()return not (provider in ("", "auto") and not model and not base_url)-def _lookup_user_declared_supports_vision(provider: str, model: str, cfg: Optional[Dict[str, Any]]) -> Optional[bool]:"""Config-declared ``supports_vision`` for the active route (None on failure)."""try:from agent.image_routing import _supports_vision_override-return _supports_vision_override(cfg, provider, model)except Exception as exc: # pragma: no cover - defensivelogger.debug("computer_use vision_routing: config override lookup failed: %s", exc)return None-def _lookup_supports_vision(provider: str, model: str, cfg: Optional[Dict[str, Any]] = None) -> Optional[bool]:- """Config/models.dev ``supports_vision`` for *(provider, model)*.-- Prefers ``agent.image_routing._lookup_supports_vision``; falls back to raw- models.dev capabilities only when that import is unavailable. Any lookup- error yields None (caller fails closed toward aux routing).- """+ """Config/models.dev ``supports_vision`` for *(provider, model)*. Prefers+ ``agent.image_routing._lookup_supports_vision``; falls back to raw models.dev capabilities+ only when that import is unavailable. Any lookup error → None (caller fails closed to aux)."""if not provider or not model:return Nonetry:@@ -74,21 +64,16 @@ def _lookup_supports_vision(provider: str, model: str, cfg: Optional[Dict[str, Aif _lookup_image_supports is not None:return _lookup_image_supports(provider, model, cfg)from agent.models_dev import get_model_capabilities-caps = get_model_capabilities(provider, model)except Exception as exc: # pragma: no cover - defensivelogger.debug("computer_use vision_routing: caps lookup failed for %s:%s — %s", provider, model, exc)return Nonereturn None if caps is None else bool(getattr(caps, "supports_vision", False))-def _provider_accepts_multimodal_tool_result(provider: str, model: str) -> Optional[bool]:- """Whether *provider*+*model* carries images inside tool-result messages.-- Reuses ``tools.vision_tools._supports_media_in_tool_results`` to stay in- lockstep with the ``vision_analyze`` native fast path. None on import- failure so callers fall back to aux routing rather than guessing.- """+ """Whether *provider*+*model* carries images inside tool-result messages. Reuses+ ``tools.vision_tools._supports_media_in_tool_results`` to stay in lockstep with the+ ``vision_analyze`` fast path; None on import failure so callers fall back to aux, not guess."""if not provider:return Nonetry:@@ -98,14 +83,10 @@ def _provider_accepts_multimodal_tool_result(provider: str, model: str) -> Optioreturn Nonereturn bool(_supports_media_in_tool_results(provider, model))-def should_route_capture_to_aux_vision(provider: str, model: str, cfg: Optional[Dict[str, Any]]) -> bool:- """True iff the captured screenshot should be pre-analysed via aux vision.-- *provider* is the lower-case canonical id, *model* the slug as sent to the- provider, *cfg* the loaded ``config.yaml`` dict (or None). False means keep- the multimodal envelope (main model handles vision natively).- """+ """True iff the screenshot should be pre-analysed via aux vision; False keeps the+ multimodal envelope. *provider* is the lower-case canonical id, *model* the slug as+ sent to the provider, *cfg* the loaded ``config.yaml`` dict (or None)."""if _explicit_aux_vision_override(cfg):return Trueuser_declared = _lookup_user_declared_supports_vision(provider, model, cfg)@@ -117,5 +98,4 @@ def should_route_capture_to_aux_vision(provider: str, model: str, cfg: Optional[return Truereturn _lookup_supports_vision(provider, model, cfg) is not True-__all__ = ["should_route_capture_to_aux_vision"]