Repository navigation
feat(computer): a driver may run beside the device it drives, over adb on Android (FD-6950) #922
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
michaelzheng67
wants to merge
1
commit into
main
Choose a base branch
from
feat/computer-driver-read-files
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+480
−38
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
packages/agentenv-protocol/src/agentenv_protocol/computer/_adb.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)}") | ||
| 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) | ||
|
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))}") | ||
|
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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
run_in_sessioncheckscommand -vbefore applyingenv. A caller that supplies a customPATHto run a program in/data/local/tmp, for example, getsInvalidArgumenteven though that program exists in the requested environment. Check for the program using the supplied environment too.Prompt To Fix With AI