Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
pointer_position,
pointer_up,
press,
read_files,
record,
run_in_session,
scroll,
Expand Down Expand Up @@ -138,8 +139,8 @@ def __getattr__(name: str) -> Any:
"display", "set_display", "capture", "click", "drag", "scroll", "type_text", "press",
"pointer_move", "pointer_down", "pointer_up", "pointer_position", "key_down", "key_up",
"navigate", "history", "tabs", "dialog", "upload", "page_state",
"run_in_session", "write_files", "record", "Recording", "RecordHints", "RecordedFrame", "RecordedSegment",
"frames_in_thread", "RecordingManifest", "ManifestSegment",
"run_in_session", "write_files", "read_files", "record", "Recording", "RecordHints", "RecordedFrame",
"RecordedSegment", "frames_in_thread", "RecordingManifest", "ManifestSegment",
"ComputerError", "InvalidArgument", "OutOfBounds", "StaleFrame", "InputBusy", "PermissionDenied", "Unsupported",
"BackgroundUnavailable", "TargetUnavailable", "DeviceUnavailable", "DialogOpen", "LimitExceeded", "Timeout",
"DeliveryFailed",
Expand Down
119 changes: 119 additions & 0 deletions packages/agentenv-protocol/src/agentenv_protocol/computer/_adb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""The base class's defaults for the OS operations on Android, for a driver beside the device: each goes through adb,
as the device's ``shell`` user and never ``su``, the home being /sdcard. adb is ``AGENTENV_ADB`` or the one on PATH, and
reads its own ``ANDROID_SERIAL`` and ``ADB_SERVER_SOCKET`` for the device and the server it goes through. A file
written is announced to the media scanner, so the gallery and file apps list it."""
from __future__ import annotations

import asyncio
import contextlib
import os
import shlex
import tempfile
import uuid
from pathlib import Path, PurePosixPath

from ._linux import DRAIN_S, _Capped
from .errors import DeliveryFailed, DeviceUnavailable, InvalidArgument
from .operations import ExecResult

#: The variable naming the adb binary.
ADB_ENV = "AGENTENV_ADB"
HOME = PurePosixPath("/sdcard")
#: How long one adb check may take, and one push or pull of a file.
ADB_TIMEOUT_S = 60
TRANSFER_TIMEOUT_S = 600
#: What the device prints on stderr, exiting 127, when a command can't start: its folder or its program isn't there.
CANNOT_RUN = "agentenv-cannot-run:"
MEDIA_SCAN = "android.intent.action.MEDIA_SCANNER_SCAN_FILE"


def adb() -> str:
return os.environ.get(ADB_ENV) or "adb"


async def run_in_session(argv: list[str], cwd: str | None, env: dict[str, str] | None, timeout_s: float, *,
output_bytes: int) -> ExecResult:
"""Run ``argv`` on the device with ``env`` added, in ``cwd`` relative to /sdcard, keeping at most ``output_bytes``
of each stream as it's read; past ``timeout_s`` adb is killed, which ends the command."""
folder, program = shlex.quote(str(HOME / (cwd or ""))), shlex.quote(argv[0])
assignments = "".join(f"{shlex.quote(f'{name}={value}')} " for name, value in (env or {}).items())
lookup = f"PATH={shlex.quote(env['PATH'])}; " if env and "PATH" in env else ""
command = (f"cd {folder} 2>/dev/null || {{ echo '{CANNOT_RUN} no such folder' >&2; exit 127; }}; "
f"({lookup}command -v {program}) >/dev/null 2>&1 || {{ echo '{CANNOT_RUN} not found' >&2; exit 127; }}; "
f"exec {'env ' + assignments if assignments else ''}{shlex.join(argv)}")
Comment on lines +39 to +43

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Custom program paths fail

run_in_session checks command -v before applying env. A caller that supplies a custom PATH to run a program in /data/local/tmp, for example, gets InvalidArgument even though that program exists in the requested environment. Check for the program using the supplied environment too.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/agentenv-protocol/src/agentenv_protocol/computer/_adb.py
Line: 39-42

Comment:
**Custom program paths fail**

`run_in_session` checks `command -v` before applying `env`. A caller that supplies a custom `PATH` to run a program in `/data/local/tmp`, for example, gets `InvalidArgument` even though that program exists in the requested environment. Check for the program using the supplied environment too.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

process = await _spawn("shell", command)
outputs = [_Capped(output_bytes), _Capped(output_bytes)]
readers = asyncio.gather(*(out.read(stream) for out, stream in zip(outputs, (process.stdout, process.stderr))))
timed_out = False
try:
await asyncio.wait_for(process.wait(), timeout_s)
except asyncio.TimeoutError:
timed_out = True
with contextlib.suppress(ProcessLookupError):
process.kill()
await process.wait()
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(readers, DRAIN_S)
stdout, stderr = outputs
if process.returncode == 127 and stderr.kept.startswith(CANNOT_RUN.encode()):
why = stderr.kept.decode(errors="replace").removeprefix(CANNOT_RUN).strip()
raise InvalidArgument(f"cannot run {argv[0]!r} in {cwd or '~'!r}: {why} on the device")
return ExecResult(exit_code=None if timed_out else process.returncode, stdout=bytes(stdout.kept),
stderr=bytes(stderr.kept), timed_out=timed_out, truncated=stdout.cut or stderr.cut)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


async def write_files(files: dict[str, bytes]) -> None:
"""Write each file under /sdcard atomically, pushed beside it and renamed over it, then announce it to the media
scanner."""
for relative, data in files.items():
target = HOME / relative
partial = target.parent / f".agentenv-{uuid.uuid4().hex[:12]}.part"
with tempfile.TemporaryDirectory() as scratch:
local = Path(scratch) / target.name
local.write_bytes(data)
await _adb("shell", f"mkdir -p {shlex.quote(str(target.parent))}")
try:
await _adb("push", str(local), str(partial), timeout_s=TRANSFER_TIMEOUT_S)
await _adb("shell", f"mv -f {shlex.quote(str(partial))} {shlex.quote(str(target))}")
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
except BaseException:
with contextlib.suppress(Exception):
await _adb("shell", f"rm -f {shlex.quote(str(partial))}")
raise
await _adb("shell", f"am broadcast -a {MEDIA_SCAN} -d {shlex.quote('file://' + str(target))}")


async def read_files(paths: list[str], into: Path) -> None:
"""Pull each of ``paths`` under /sdcard that exists to the same path under ``into``; adb failing raises, rather
than reading as a missing path."""
for relative in paths:
remote = str(HOME / relative)
answer = (await _adb("shell", f"if [ -e {shlex.quote(remote)} ]; then echo yes; else echo no; fi")).strip()
if answer == b"no":
continue
if answer != b"yes":
raise DeliveryFailed(f"the device didn't say whether {relative!r} exists: {answer[:200]!r}")
(into / relative).parent.mkdir(parents=True, exist_ok=True)
await _adb("pull", remote, str((into / relative).parent), timeout_s=TRANSFER_TIMEOUT_S)


async def _spawn(*args: str) -> asyncio.subprocess.Process:
try:
return await asyncio.create_subprocess_exec(adb(), *args, stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
except FileNotFoundError:
raise DeviceUnavailable(f"{adb()} is not installed") from None


async def _adb(*args: str, timeout_s: float = ADB_TIMEOUT_S) -> bytes:
"""adb's output, or DeliveryFailed with what it said when it fails or doesn't answer within ``timeout_s``."""
process = await _spawn(*args)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout_s)
except asyncio.TimeoutError:
with contextlib.suppress(ProcessLookupError):
process.kill()
await process.wait()
raise DeliveryFailed(f"adb {args[0]} gave no answer in {timeout_s:g}s") from None
if process.returncode != 0:
raise DeliveryFailed(f"adb {args[0]}: {(stderr or stdout).decode(errors='replace').strip()}")
return stdout
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from typing import TYPE_CHECKING

from . import clock
from .dataplane import DEFAULT_DATA_PATHS
from .recording import recording_params
from ..types import METHOD_ADD, EnvironmentExtension, EnvironmentTool, IntakeDeclaration, IntakeFormat, intake_extension

Expand Down Expand Up @@ -86,15 +85,16 @@ def extension_params(driver: ComputerDriverEnvironment, uri: str) -> dict:


def computer_features(driver: ComputerDriverEnvironment) -> dict:
"""computer/v1's params: what the seven tools take, how input is delivered, the platform and the default data
paths."""
"""computer/v1's params: what the seven tools take, how input is delivered, the platform, the default data paths
and where the driver runs."""
return {
"buttons": list(driver.buttons), "max_click_count": driver.max_click_count,
"keys": driver.keys if driver.keys == "all" else list(driver.keys), "max_text_length": driver.max_text_length,
"max_wait_ms": driver.max_wait_ms, "max_drag_points": driver.max_drag_points,
"max_duration_ms": driver.max_duration_ms, "max_key_repeat": driver.max_key_repeat,
"max_scroll_amount": driver.max_scroll_amount, "delivery": "foreground", "platform": driver.platform.as_dict(),
"supports": list(driver.supports), "default_data_paths": list(DEFAULT_DATA_PATHS), "screen": driver.screen_kind,
"supports": list(driver.supports), "default_data_paths": list(driver.default_data_paths),
"screen": driver.screen_kind, "placement": driver.placement,
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ def check_features(cls: type) -> None:
problems.append(f"Settings is ComputerSettings or a subclass of it, got {cls.Settings!r}")
if cls.screen_kind not in ("desktop", "page"):
problems.append(f"screen_kind is desktop or page, got {cls.screen_kind!r}")
if cls.placement == "provider":
problems.append("placement provider, a driver its device's provider serves, isn't supported yet: use inside "
"or beside")
elif cls.placement not in ("inside", "beside"):
problems.append(f"placement is inside or beside, got {cls.placement!r}")
if ("set_display" in declared(cls)) != bool(cls.display_modes):
problems.append("display_modes and @set_display come together")
problems += check_recording(cls.recording)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import asyncio
import base64
import contextlib
import hashlib
import io
import json
import math
Expand Down Expand Up @@ -52,8 +53,10 @@
DATA_PLANE = (INTAKE_EXTENSION_URI, DATA_OBJECTS_EXTENSION_URI)
#: Where the fixture is staged and keeps its state, relative to the session user's home.
STAGE = ".agentenv-probe"
#: How the probe reads a staged file's owner: through the python3 the fixture runs on, the same on every OS.
#: How the probe reads a staged file's owner: through the python3 the fixture runs on, the same on every OS; beside a
#: device, which has no python3, through its stat.
OWNER = ("python3", "-c", "import os, sys; print(os.stat(sys.argv[1]).st_uid)")
DEVICE_OWNER = ("stat", "-c", "%u")
#: Where a page driver's computer_upload takes files from, relative to the session user's home.
UPLOADS = "Uploads"
#: What the probe answers the page fixture's prompt with.
Expand Down Expand Up @@ -144,6 +147,8 @@ def __init__(self, driver: Driver, session: ClientSession, ready_timeout_s: floa
self.gtk = not self.page and platform.get("display") == "wayland"
self.fixture = "page_fixture.py" if self.page else "wayland_fixture.py" if self.gtk else "fixture.py"
self.windows = platform.get("os") == "windows"
#: Whether the driver runs beside its device, which may have no python3, and keeps its recordings off it.
self.beside = self.features.get("placement") == "beside"
#: The chord that selects a text box's text: Tk's Ctrl+/, which the Tk desk binds everywhere, or on the GTK
#: desk GTK's own Ctrl+A.
self.select_all = ["Control", "a"] if self.gtk else ["Control", "/"]
Expand Down Expand Up @@ -690,7 +695,8 @@ async def one_account() -> str | None:

async def one_user() -> str | None:
uid = (await self.driver.run("id", "-u"))["stdout"].strip()
owner = (await self.driver.run(*OWNER, f"{STAGE}/{self.fixture}"))["stdout"].strip()
reader = DEVICE_OWNER if self.beside else OWNER
owner = (await self.driver.run(*reader, f"{STAGE}/{self.fixture}"))["stdout"].strip()
if uid == "0":
return "commands run as root"
return None if owner == uid else f"data/add wrote as uid {owner}, commands run as uid {uid}"
Expand Down Expand Up @@ -1177,8 +1183,11 @@ async def _segments_match(self, wire: dict, fps: int) -> str | None:

async def _read_back(self, segment: ManifestSegment) -> bytes | str:
"""A segment a recording without a grant kept on the computer, read back and matched to its manifest entry's
size and digest; what is wrong, as a string, when it can't be."""
size and digest; what is wrong, as a string, when it can't be. Beside a device, through data/get, which reads
the recordings where the driver keeps them, needing no python3."""
path = f"{RECORDINGS_DIR}/{segment.path}"
if self.beside:
return await self._read_back_through_data_get(segment, path)
out = await self.driver.run("python3", "-c", READ_DIGEST, path)
if out.get("exit_code") != 0:
return f"segment {segment.index} couldn't be read back: {out.get('stderr', '')[-200:]}"
Expand All @@ -1196,6 +1205,18 @@ async def _read_back(self, segment: ManifestSegment) -> bytes | str:
data += read
return data

async def _read_back_through_data_get(self, segment: ManifestSegment, path: str) -> bytes | str:
got = await self.driver.rpc("data/get", {"paths": [path]})
parts = (got.get("result") or {}).get("parts")
if not parts:
return f"segment {segment.index} couldn't be read back through data/get: it answered {str(got)[:200]}"
data = base64.b64decode(parts[0]["file"]["bytes"])
digest = hashlib.sha256(data).hexdigest()
if (len(data), digest) != (segment.bytes, segment.sha256):
return f"segment {segment.index}'s file is {len(data)} bytes, sha256 {digest[:12]}; " \
f"the manifest says {segment.bytes}, {segment.sha256[:12]}"
return data

async def _annotated_click(self, wire: dict, size: tuple[int, int], point: tuple[int, int],
inside: tuple[int, int], was: tuple[int, int, int]) -> str | None:
"""What is wrong with an annotated recording of one click at frame pixel ``point`` of a frame ``size``, the
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""The data plane on a computer: ``data/add`` writes files under the session user's home, ``data/get`` returns the
files under the paths its caller names, or under ``DEFAULT_DATA_PATHS`` when it names none, leaving out those under a
path one of the computer's apps keeps its data in. Each file part names its path, relative to the home, under the
``data-objects/v1`` marker."""
files under the paths its caller names, or under the driver's ``default_data_paths`` when it names none, leaving out
those under a path one of the computer's apps keeps its data in. Each file part names its path, relative to the home,
under the ``data-objects/v1`` marker. A driver beside a device reads its files with ``@read_files``; the recordings
it keeps are in its own home."""
from __future__ import annotations

import base64
Expand All @@ -27,6 +28,8 @@
MAX_URL_BYTES = 1 << 30
#: What ``data/get`` returns when its caller names no paths: the folders a desktop keeps its user's files in.
DEFAULT_DATA_PATHS = ("Desktop", "Documents", "Downloads")
#: Where the base class writes recordings, relative to the driver's home, and keeps them when there is no grant.
RECORDINGS_DIR = ".agentenv-recordings"
_PATHS = TypeAdapter(list[RelativePath])


Expand All @@ -35,6 +38,8 @@ class DataPlane:

_computer: ComputerRuntime
settings: ComputerSettings
default_data_paths: tuple[str, ...]
placement: str

@add_data
async def _computer_data_add(self, parts: list) -> None:
Expand All @@ -56,19 +61,39 @@ async def _computer_data_add(self, parts: list) -> None:
async def _computer_data_get(self, write_namespace: Optional[WriteNamespaceGrant] = None,
paths: Optional[list[str]] = None) -> list:
try:
named = _PATHS.validate_python(paths) if paths is not None else list(DEFAULT_DATA_PATHS)
named = _PATHS.validate_python(paths) if paths is not None else list(self.default_data_paths)
except ValidationError:
raise ValueError(f"data/get on a computer takes paths relative to the home, not {paths!r}") from None
return await file_parts(Path.home(), named, write_namespace, leaving_out=await self._computer.app_paths())
leaving_out = await self._computer.app_paths()
if not self._computer.has("read_files"):
return await file_parts(Path.home(), named, write_namespace, leaving_out=leaving_out)
kept_here = [path for path in named
if self.placement == "beside" and PurePosixPath(path).is_relative_to(RECORDINGS_DIR)]
on_device = [path for path in named if path not in kept_here]
with tempfile.TemporaryDirectory() as into:
if on_device:
await self._computer.call("read_files", on_device, Path(into))
return await parts_of(listed(Path(into), on_device, leaving_out) + listed(Path.home(), kept_here),
write_namespace)


async def file_parts(home: Path, paths: list[str], write_namespace: Optional[WriteNamespaceGrant],
leaving_out: list[str] = ()) -> list:
"""A part for each file under ``paths`` of ``home`` but under none of ``leaving_out``, naming its path relative to
``home``: uploaded under ``write_namespace`` when there is one, else inline. A file a running app removes before it's
read is left out."""
files = [(relative, source) for relative, source in data_files(home, paths)
if not any(PurePosixPath(relative).is_relative_to(owned) for owned in leaving_out)]
return await parts_of(listed(home, paths, leaving_out), write_namespace)


def listed(home: Path, paths: list[str], leaving_out: list[str] = ()) -> list[tuple[str, Path]]:
"""Every file under ``paths`` of ``home`` but under none of ``leaving_out``, by its path relative to ``home``."""
return [(relative, source) for relative, source in data_files(home, paths)
if not any(PurePosixPath(relative).is_relative_to(owned) for owned in leaving_out)]


async def parts_of(files: list[tuple[str, Path]], write_namespace: Optional[WriteNamespaceGrant]) -> list:
"""A part for each of ``files``, named by its relative path: all uploaded under one ``write_namespace``, whose
limits they share, when there is one, else inline."""
parts = []
if write_namespace is not None:
uploader = NamespaceUploader(write_namespace)
Expand Down
Loading
Loading