Skip to content

The agent that grows with you

refactor(computer_use): single-blank layout between top-level defs (AST-identical)

Teknium8f877d40f92b
diff --git a/tools/computer_use/backend.py b/tools/computer_use/backend.py
index b2b334a5071..dcd5e903f3f 100644
--- a/tools/computer_use/backend.py
+++ b/tools/computer_use/backend.py
@@ -14,7 +14,6 @@ from typing import Any, Dict, List, Optional, Tuple
_JPEG_SOF_MARKERS = frozenset({0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF})
-
def image_dimensions_from_bytes(raw: bytes) -> Optional[Tuple[int, int]]:
"""(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
diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py
index 3400daa9d31..defa7470c68 100644
--- a/tools/computer_use/cua_backend.py
+++ b/tools/computer_use/cua_backend.py
@@ -86,7 +86,6 @@ def _computer_use_cfg() -> Dict[str, Any]:
except Exception:
return {}
-
def _cua_no_overlay() -> bool:
"""Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on
macOS (cursor-overlay redraw loop can peg a core after a session), headless
@@ -111,13 +110,11 @@ def _cua_no_overlay() -> bool:
pass
return os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY")
-
def _cua_telemetry_disabled() -> bool:
"""True unless ``computer_use.cua_telemetry`` opts in (unreadable config
fails SAFE toward disabling telemetry)."""
return not bool(_computer_use_cfg().get("cua_telemetry", False))
-
def _cua_configured_permission_mode() -> str:
"""``computer_use.permission_mode``: ``standard`` (default) or ``bounded``;
unknown values fall closed to ``standard``. ``unrestricted`` is deliberately
@@ -126,14 +123,12 @@ def _cua_configured_permission_mode() -> str:
raw = str(_computer_use_cfg().get("permission_mode", "standard") or "").strip().lower()
return raw if raw in {"standard", "bounded"} else "standard"
-
def _cua_capability_manifest() -> Optional[str]:
"""``computer_use.capability_manifest`` path, or None. Existence is
validated by ``_EmbeddedCuaDaemon`` so a missing file fails loudly."""
raw = _computer_use_cfg().get("capability_manifest")
return raw.strip() if isinstance(raw, str) and raw.strip() else None
-
def _manifest_is_mode_independent(path: str) -> bool:
"""True when this manifest may accompany any permission mode: v1/v2 declare
``mode: bounded`` and abort startup under an unrestricted runtime; v3 has no
@@ -151,7 +146,6 @@ def _manifest_is_mode_independent(path: str) -> bool:
version = parsed.get("version") if isinstance(parsed, dict) else None
return isinstance(version, int) and not isinstance(version, bool) and version >= 3
-
def _computer_use_max_image_dimension() -> Optional[int]:
"""``computer_use.max_image_dimension`` longest-edge cap (default 1456,
matching the aux-vision downscale); ``0``/negative -> None (unset)."""
@@ -161,7 +155,6 @@ def _computer_use_max_image_dimension() -> Optional[int]:
return 1456
return dim if dim > 0 else None
-
def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
"""Env for spawning cua-driver: ``base_env`` (default ``os.environ``) plus
``CUA_DRIVER_RS_TELEMETRY_ENABLED=0`` unless the user opted in. Used by
@@ -171,7 +164,6 @@ def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str,
env[_CUA_TELEMETRY_ENV_VAR] = "0"
return env
-
def sanitized_cua_driver_env() -> Dict[str, str]:
"""``cua_driver_child_env()`` with Hermes provider secrets stripped —
cua-driver is a third-party binary and must never inherit API keys.
@@ -184,7 +176,6 @@ def sanitized_cua_driver_env() -> Dict[str, str]:
except Exception:
return env
-
def _run_driver(driver_cmd: str, *args: str, timeout: float) -> subprocess.CompletedProcess:
"""Run a short cua-driver verb with the sanitized env, hidden window and
stdin=DEVNULL (older drivers fall into a stdin-reading mode on unknown
@@ -231,7 +222,6 @@ def _linux_session_locked() -> Optional[bool]:
except Exception:
return None
-
def _empty_discovery_reason() -> str:
"""One-line diagnosis for 'window discovery found nothing'."""
if _linux_session_locked() is True:
@@ -268,7 +258,6 @@ _update_checked = False
# failing installer can't loop — the second start() goes straight to the error.
_contract_repair_attempted = False
-
def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]:
"""Try one automatic driver repair; return the post-repair contract (or the
original when no repair was attempted / it failed). Never raises. An
@@ -301,7 +290,6 @@ def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]:
except Exception:
return contract
-
def _maybe_nudge_update() -> None:
"""Emit an update nudge at most once per process, off-thread so the
(cached, ~20h) GitHub poll never blocks the first computer_use action."""
diff --git a/tools/computer_use/cua_backend_capture.py b/tools/computer_use/cua_backend_capture.py
index 18a4a14e4ff..70645486ff1 100644
--- a/tools/computer_use/cua_backend_capture.py
+++ b/tools/computer_use/cua_backend_capture.py
@@ -77,7 +77,6 @@ _FULL_SCREEN_NOTE = (
"with elements"
)
-
def _linux_x11_active_window_id() -> Optional[int]:
"""Best-effort read of ``_NET_ACTIVE_WINDOW`` via xprop. Never raises."""
if sys.platform != "linux" or not os.environ.get("DISPLAY"):
@@ -89,7 +88,6 @@ def _linux_x11_active_window_id() -> Optional[int]:
return None
return _parse_xprop_net_active_window(proc.stdout or "") if proc.returncode == 0 else None
-
def _select_capture_target(
windows: List[Dict[str, Any]],
*,
@@ -115,7 +113,6 @@ def _select_capture_target(
return w
return pool[0] if pool else windows[0]
-
def _sorted_windows(out: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Normalised windows from a list_windows result, ``z_index`` DESCENDING
(frontmost at index 0 — the default target for capture()/focus_app())."""
@@ -123,7 +120,6 @@ def _sorted_windows(out: Dict[str, Any]) -> List[Dict[str, Any]]:
windows.sort(key=lambda w: w["z_index"], reverse=True)
return windows
-
def _tree_and_title(out: Dict[str, Any]) -> Tuple[str, str]:
"""``(tree_markdown, window_title)`` from a get_window_state result."""
data = out.get("data")
@@ -131,7 +127,6 @@ def _tree_and_title(out: Dict[str, Any]) -> Tuple[str, str]:
match = _WINDOW_TITLE_RE.search(tree)
return tree, (match.group(1) if match else "")
-
def _gws_is_empty(out: Dict[str, Any]) -> bool:
"""True when a get_window_state result carries neither a screenshot nor a
parseable tree. Modern drivers put the payload in structuredContent with
@@ -144,7 +139,6 @@ def _gws_is_empty(out: Dict[str, Any]) -> bool:
tree, _ = _tree_and_title(out)
return not tree.strip()
-
def _png_metrics(png_b64: str, width: int, height: int) -> Tuple[int, int, int]:
"""Return ``(png_bytes_len, width, height)``, replacing the given size with
the sniffed one when the bytes decode to a readable PNG/JPEG header."""
@@ -158,12 +152,10 @@ def _png_metrics(png_b64: str, width: int, height: int) -> Tuple[int, int, int]:
png_bytes_len = len(png_b64) * 3 // 4
return png_bytes_len, width, height
-
def _is_desktop_window(w: Dict[str, Any], names: Tuple[str, ...] = _DESKTOP_WINDOW_NAMES) -> bool:
haystack = f"{w.get('app_name', '')} {w.get('title', '')}".lower()
return any(name in haystack for name in names)
-
def _app_aliases(raw_app: Dict[str, Any]) -> set:
return {
value.strip().lower()
diff --git a/tools/computer_use/cua_backend_daemon.py b/tools/computer_use/cua_backend_daemon.py
index 24cca945fb2..b42980e371b 100644
--- a/tools/computer_use/cua_backend_daemon.py
+++ b/tools/computer_use/cua_backend_daemon.py
@@ -25,7 +25,6 @@ logger = logging.getLogger("tools.computer_use.cua_backend")
_CUA_DRIVER_BUNDLE_ID = "com.trycua.driver"
_CUA_DRIVER_TEAM_IDS = ("4YEC26S9KF", "YCK386LBJ7")
-
def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]:
"""Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the
resolved binary path only — no /Applications fallback, which could be a DIFFERENT install
@@ -38,7 +37,6 @@ def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]:
executable = os.path.join(candidate, "Contents", "MacOS", "cua-driver")
return candidate if os.path.isfile(executable) and os.access(executable, os.X_OK) else None
-
def _validate_cua_driver_app_signature(app_path: str) -> None:
"""Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open``
hands LaunchServices whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY
@@ -73,7 +71,6 @@ def _validate_cua_driver_app_signature(app_path: str) -> None:
f"{_CUA_DRIVER_TEAM_IDS!r}; refusing to launch it. (Set computer_use.allow_unsigned_driver: "
"true in config.yaml only for local unsigned driver builds.)")
-
def _embedded_daemon_spawn_command(driver_cmd: str, serve_args: List[str], *, platform: str,
app_path: Optional[str] = None) -> List[str]:
"""Build the private-daemon launch while preserving macOS TCC identity."""
@@ -86,7 +83,6 @@ def _embedded_daemon_spawn_command(driver_cmd: str, serve_args: List[str], *, pl
_validate_cua_driver_app_signature(resolved_app)
return ["/usr/bin/open", "-n", "-g", "-a", resolved_app, "--args", *serve_args]
-
def _wait_or_kill(process: Any) -> None:
"""Wait 5s for a graceful exit, then terminate (2s), then kill."""
try:
diff --git a/tools/computer_use/cua_backend_driver.py b/tools/computer_use/cua_backend_driver.py
index 9f312ad9469..6ae49087997 100644
--- a/tools/computer_use/cua_backend_driver.py
+++ b/tools/computer_use/cua_backend_driver.py
@@ -37,14 +37,12 @@ _CUA_DRIVER_RUNTIME_CONTRACT_ARGS = {
}
_SEMVER_RE = re.compile(r"v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?")
-
def _cb():
"""Origin module, looked up lazily so ``patch("tools.computer_use.cua_backend.X")`` applies."""
from tools.computer_use import cua_backend
return cua_backend
-
def _driver_json(driver_cmd: str, *args: str, timeout: float, require_ok: bool) -> Optional[Dict[str, Any]]:
"""Run a driver verb and parse its stdout as a JSON object; None on spawn
failure, empty stdout (older drivers print usage to stderr), unparseable or
@@ -70,7 +68,6 @@ def _driver_json(driver_cmd: str, *args: str, timeout: float, require_ok: bool)
def _has_path_separator(value: str) -> bool:
return os.sep in value or (os.altsep is not None and os.altsep in value)
-
def _wsl_windows_path_to_posix(path: str) -> str:
"""Translate a Windows absolute manifest command to its DrvFS
``/mnt/<drive>/...`` form when Hermes runs in WSL (a Windows cua-driver
@@ -91,7 +88,6 @@ def _wsl_windows_path_to_posix(path: str) -> str:
return path
return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:]))
-
def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]:
"""Candidate commands in resolution order. ``override`` / a non-empty
``HERMES_CUA_DRIVER_CMD`` is authoritative (if wrong, report the driver
@@ -118,7 +114,6 @@ def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]:
]
return [_CUA_DRIVER_DEFAULT_CMD, *installed]
-
def resolve_cua_driver_cmd(override: Optional[str] = None) -> Optional[str]:
"""Resolve the cua-driver executable for every runtime/status surface.
An override is never silently replaced by another binary."""
@@ -129,12 +124,10 @@ def resolve_cua_driver_cmd(override: Optional[str] = None) -> Optional[str]:
return expanded if _has_path_separator(expanded) else resolved
return None
-
def cua_driver_binary_available() -> bool:
"""True if `cua-driver` resolves via env, PATH, or known install paths."""
return _cb().resolve_cua_driver_cmd() is not None
-
def cua_driver_install_hint() -> str:
scripts = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts"
if sys.platform == "win32":
@@ -163,7 +156,6 @@ def _mcp_args_with_overlay_flag(
return [*args, "--no-overlay"]
return list(args)
-
@functools.lru_cache(maxsize=1)
def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool:
"""True if ``<driver> --help`` mentions ``--no-overlay`` (probed once).
@@ -174,7 +166,6 @@ def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool:
except Exception:
return False
-
def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[str, List[str]]:
"""``(command, args)`` that spawn cua-driver's stdio MCP server, asked of
the driver itself via ``cua-driver manifest`` (``mcp_invocation``) so a
@@ -261,7 +252,6 @@ def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str
return _not_ready("driver manifest is missing: " + ", ".join(missing), raw_version)
return {"ready": True, "binary": resolved, "version": raw_version, "reason": ""}
-
def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]:
"""``cua-driver check-update --json`` payload (``{current_version,
latest_version, update_available, ...}``), or ``None`` when the binary is
@@ -278,7 +268,6 @@ def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict
data = _driver_json(driver_cmd, "check-update", "--json", timeout=timeout, require_ok=False)
return None if data is None or data.get("error") else data
-
def cua_driver_update_nudge() -> Optional[str]:
"""One-line "an update is available" message, or ``None`` when up to date,
indeterminate, or the driver is too old to report."""
diff --git a/tools/computer_use/cua_backend_input.py b/tools/computer_use/cua_backend_input.py
index 5725c3ee548..7022379b0bd 100644
--- a/tools/computer_use/cua_backend_input.py
+++ b/tools/computer_use/cua_backend_input.py
@@ -17,7 +17,6 @@ _FOREGROUND_UNSUPPORTED_MSG = (
"assuming the reported package version describes the live schema."
)
-
def _refuse(action: str, message: str, **fields: Any) -> ActionResult:
return ActionResult(ok=False, action=action, message=message, **fields)
diff --git a/tools/computer_use/cua_backend_parse.py b/tools/computer_use/cua_backend_parse.py
index 5a02428beda..d6902ab480e 100644
--- a/tools/computer_use/cua_backend_parse.py
+++ b/tools/computer_use/cua_backend_parse.py
@@ -32,7 +32,6 @@ _ELEMENT_LINE_RE = re.compile(
A parenthesised pure-digit group is an ORDER index, not a label, and is excluded so the id=
label wins. Group 1 index, group 2 role, groups 3-6 the label in whichever form matched."""
-
def _mcp_field(obj, snake: str, camel: str, default=None):
"""Read an MCP model field across the 1.x -> 2.x rename: mcp 2.0 exposes snake_case
attributes and keeps camelCase only as a serialization alias, so ``getattr(result,
@@ -45,7 +44,6 @@ def _mcp_field(obj, snake: str, camel: str, default=None):
value = getattr(obj, camel, _MISSING)
return default if value is _MISSING else value
-
def _action_result_from(name: str, ok: bool, message: str, meta: Dict[str, Any],
structured: Dict[str, Any], *, requested_delivery: Optional[str] = None) -> ActionResult:
"""Build an ActionResult, lifting cua-driver's structured verdict. structuredContent is
@@ -72,12 +70,10 @@ def _action_result_from(name: str, ok: bool, message: str, meta: Dict[str, Any],
code=_typed(_pick("code") or _pick("reason_code"), str),
)
-
def _z_index_uninformative(windows: List[Dict[str, Any]]) -> bool:
"""True when every window shares the same z_index (common on Linux/X11)."""
return len({w.get("z_index", 0) for w in windows}) <= 1
-
def _parse_xprop_net_active_window(stdout: str) -> Optional[int]:
"""Parse ``xprop -root _NET_ACTIVE_WINDOW`` stdout into a window id: the ``window id #
0x...`` form, falling back to the first hex token."""
@@ -85,7 +81,6 @@ def _parse_xprop_net_active_window(stdout: str) -> Optional[int]:
match = re.search(r"window id # (0x[0-9a-fA-F]+)", text) or re.search(r"(0x[0-9a-fA-F]+)", text)
return int(match.group(1), 16) if match else None
-
def _is_real_app_window(w: Dict[str, Any]) -> bool:
"""Return False for desktop/shell helper windows that capture as empty."""
title = w.get("title", "")
@@ -94,7 +89,6 @@ def _is_real_app_window(w: Dict[str, Any]) -> bool:
for p in _NON_APP_WINDOW_TITLE_PREFIXES
)
-
def _parse_elements_from_tree(markdown: str) -> List[UIElement]:
"""Parse UIElements from get_window_state AX-tree markdown — last-resort fallback for
drivers without ``structuredContent.elements``. Bounds are always ``(0, 0, 0, 0)`` (the
@@ -110,7 +104,6 @@ def _parse_elements_from_tree(markdown: str) -> List[UIElement]:
for m in _ELEMENT_LINE_RE.finditer(markdown)
]
-
def _parse_elements_from_structured(raw_elements: List[Dict[str, Any]]) -> List[UIElement]:
"""Read the canonical ``structuredContent.elements`` array: ``element_index``, ``role``,
``label`` and, when AT-SPI / AXFrame returned usable bounds, ``frame`` ``{x, y, w, h}`` —
@@ -137,23 +130,19 @@ def _parse_elements_from_structured(raw_elements: List[Dict[str, Any]]) -> List[
))
return elements
-
def _image_dimensions_from_bytes(raw: bytes) -> Tuple[int, int]:
"""Best-effort PNG/JPEG dimension sniff; ``(0, 0)`` when unreadable or non-positive."""
dims = image_dimensions_from_bytes(raw)
return dims if dims and dims[0] > 0 and dims[1] > 0 else (0, 0)
-
def _split_tree_text(full_text: str) -> Tuple[str, str]:
"""Split get_window_state text into (summary_line, tree_markdown)."""
summary, _, tree = full_text.partition("\n")
return summary, tree
-
_MODIFIER_NAMES = frozenset({"cmd", "command", "shift", "option", "alt", "ctrl", "control", "fn"})
_KEY_ALIASES = {"command": "cmd", "alt": "option", "control": "ctrl"}
-
def _parse_key_combo(keys: str) -> Tuple[Optional[str], List[str]]:
"""Parse 'cmd+s' / 'ctrl-alt-t' into (key, modifiers); last non-modifier wins."""
modifiers: List[str] = []
@@ -166,7 +155,6 @@ def _parse_key_combo(keys: str) -> Tuple[Optional[str], List[str]]:
key = part
return key, modifiers
-
def _extract_tool_result(mcp_result: Any) -> Dict[str, Any]:
"""Flatten an mcp CallToolResult into ``{data, images, image_mime_types, structuredContent,
isError}``. ``data`` is the joined text parts (parsed as JSON when it looks like JSON);
@@ -198,7 +186,6 @@ def _extract_tool_result(mcp_result: Any) -> Dict[str, Any]:
"isError": _mcp_field(mcp_result, "is_error", "isError", False) is True,
}
-
def _image_from_tool_result(out: Dict[str, Any]) -> tuple[Optional[str], Optional[str]]:
"""Pull ``(b64, mime_type)`` out of a flattened tool result. cua-driver delivers screenshots
as an MCP ``image`` part (``out["images"]``) or as ``screenshot_png_b64`` in structuredContent
@@ -213,7 +200,6 @@ def _image_from_tool_result(out: Dict[str, Any]) -> tuple[Optional[str], Optiona
return b64, (structured.get("screenshot_mime_type") or structured.get("mime_type") or None)
return None, None
-
def _positive_int(value: Any) -> Optional[int]:
"""Return a positive integer, rejecting booleans and malformed values."""
if isinstance(value, bool) or not isinstance(value, (int, str)):
@@ -224,7 +210,6 @@ def _positive_int(value: Any) -> Optional[int]:
return None
return parsed if parsed > 0 else None
-
def _is_placeholder_id(value: Any) -> bool:
"""True when *value* is a schema-filler id (``0`` / negative) rather than a target: some
providers zero-fill every optional integer, and treating that as targeting would drop the
@@ -236,7 +221,6 @@ def _is_placeholder_id(value: Any) -> bool:
except ValueError:
return False
-
def _ingest_windows(raw_windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Normalise cua-driver ``list_windows`` entries, dropping unusable ones. Every downstream
call needs integer ``pid`` and ``window_id``; on X11 the PID comes from the optional
@@ -262,7 +246,6 @@ def _ingest_windows(raw_windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
})
return windows
-
def _windows_from_tool_result(out: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Return list_windows payloads across cua-driver result shapes: structuredContent.windows,
then ``windows`` / ``_legacy_windows`` in the text payload, then on the envelope itself."""
@@ -277,7 +260,6 @@ def _windows_from_tool_result(out: Dict[str, Any]) -> List[Dict[str, Any]]:
return value
return []
-
def _apps_from_windows(windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
apps: List[Dict[str, Any]] = []
seen: set[tuple[str, int]] = set()
diff --git a/tools/computer_use/cua_backend_session.py b/tools/computer_use/cua_backend_session.py
index 5d5aa2246ed..36b9d26a540 100644
--- a/tools/computer_use/cua_backend_session.py
+++ b/tools/computer_use/cua_backend_session.py
@@ -67,7 +67,6 @@ class _AsyncBridge:
self._thread.join(timeout=2.0)
self._thread = self._loop = None
-
# Fail-closed messages for calls whose effect on the remote screen is unknown. The action
# MAY have landed, so it is never replayed; the caller decides after taking fresh state.
_UNKNOWN_OUTCOME_MESSAGES = {
@@ -81,7 +80,6 @@ _UNKNOWN_OUTCOME_MESSAGES = {
"whether to act again."),
}
-
def _outcome_unknown(name: str, exc: Exception, code: str) -> Dict[str, Any]:
"""Fail-closed ``isError`` result for *code* (see ``_UNKNOWN_OUTCOME_MESSAGES``)."""
message = _UNKNOWN_OUTCOME_MESSAGES[code].format(name=name)
@@ -90,7 +88,6 @@ def _outcome_unknown(name: str, exc: Exception, code: str) -> Dict[str, Any]:
return {"data": message, "images": [], "image_mime_types": [],
"structuredContent": structured, "isError": True}
-
def _tool_field(obj: Any, *names: str) -> Any:
"""``_mcp_field`` plus the ``model_extra`` fallback some MCP SDKs (Pydantic v2) forward custom fields via."""
value = _mcp_field(obj, names[0], names[-1])
@@ -98,10 +95,8 @@ def _tool_field(obj: Any, *names: str) -> Any:
value = (getattr(obj, "model_extra", None) or {}).get(names[-1])
return value
-
_CLI_ATTEMPTS = 4 # CLI fallback transport retries (backoff 0.5s doubling)
-
def _cli_run_json(cmd: List[str], env: Dict[str, str], name: str, timeout: float) -> Any:
"""Run ``cua-driver call`` with backoff until it prints JSON; return the parsed value.
"daemon is not running" is PERMANENT for this invocation (the CLI needs the machine-wide
@@ -140,7 +135,6 @@ def _cli_run_json(cmd: List[str], env: Dict[str, str], name: str, timeout: float
raise RuntimeError(f"cua-driver CLI fallback for {name} returned no JSON after "
f"{_CLI_ATTEMPTS} attempts: {last_err}")
-
def _cli_result(parsed: Any, shot_file: Optional[str]) -> Dict[str, Any]:
"""Remap a ``cua-driver call`` JSON body into the ``_extract_tool_result`` shape."""
if not isinstance(parsed, dict):
diff --git a/tools/computer_use/permissions.py b/tools/computer_use/permissions.py
index 3521af89f86..6cda1185b84 100644
--- a/tools/computer_use/permissions.py
+++ b/tools/computer_use/permissions.py
@@ -23,7 +23,6 @@ from hermes_cli._subprocess_compat import windows_hide_flags
_RUNTIME_PLATFORMS = frozenset({"darwin", "win32", "linux"})
_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
@@ -75,7 +74,6 @@ def _mac_permissions(binary: str, out: Dict[str, Any]) -> None:
if isinstance(data.get("source"), dict):
out["source"] = data["source"]
-
def computer_use_status(driver_cmd: Optional[str] = None) -> Dict[str, Any]:
"""Unified, OS-aware Computer Use readiness for the desktop card.
@@ -108,7 +106,6 @@ def computer_use_status(driver_cmd: Optional[str] = None) -> Dict[str, Any]:
out["ready"] = doctor["ok"] # no TCC model off macOS
return out
-
def request_permissions_grant(driver_cmd: Optional[str] = None) -> int:
"""Run ``cua-driver permissions grant`` (macOS); stream its output.
diff --git a/tools/computer_use/schema.py b/tools/computer_use/schema.py
index b929471fb97..c7406bf5bb5 100644
--- a/tools/computer_use/schema.py
+++ b/tools/computer_use/schema.py
@@ -207,7 +207,6 @@ COMPUTER_USE_SCHEMA: Dict[str, Any] = {
"parameters": {"type": "object", "properties": _PROPERTIES, "required": ["action"]},
}
-
def get_computer_use_schema() -> Dict[str, Any]:
"""Return the generic OpenAI function-calling schema."""
return COMPUTER_USE_SCHEMA