droid-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- droid_agent/__init__.py +3 -0
- droid_agent/__main__.py +4 -0
- droid_agent/actions.py +147 -0
- droid_agent/adb.py +198 -0
- droid_agent/cli.py +404 -0
- droid_agent/device.py +130 -0
- droid_agent/mcp_server.py +117 -0
- droid_agent/output.py +41 -0
- droid_agent/session.py +108 -0
- droid_agent/ui.py +288 -0
- droid_agent-0.1.0.dist-info/METADATA +191 -0
- droid_agent-0.1.0.dist-info/RECORD +15 -0
- droid_agent-0.1.0.dist-info/WHEEL +4 -0
- droid_agent-0.1.0.dist-info/entry_points.txt +3 -0
- droid_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
droid_agent/__init__.py
ADDED
droid_agent/__main__.py
ADDED
droid_agent/actions.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Touch / input actions resolved against the ref map."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from droid_agent.adb import Adb, AdbError
|
|
8
|
+
from droid_agent.session import Session, resolve_ref
|
|
9
|
+
|
|
10
|
+
# Android keyevent codes for the common keys agents need.
|
|
11
|
+
KEYCODES = {
|
|
12
|
+
"back": 4, "home": 3, "recents": 187, "overview": 187,
|
|
13
|
+
"enter": 66, "dpad_up": 19, "dpad_down": 20, "dpad_left": 21,
|
|
14
|
+
"dpad_right": 22, "dpad_center": 23, "tab": 61, "space": 62,
|
|
15
|
+
"del": 67, "delete": 67, "backspace": 67, "search": 84,
|
|
16
|
+
"menu": 82, "power": 26, "wake": 224, "sleep": 223,
|
|
17
|
+
"vol_up": 24, "vol_down": 25, "mute": 164,
|
|
18
|
+
"camera": 27, "escape": 111,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
_REF_RE = re.compile(r"^#?(\d+)$")
|
|
22
|
+
_XY_RE = re.compile(r"^(\d+)[,\s]+(\d+)$")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def parse_target(target: int | str) -> tuple[str, tuple[int, int]]:
|
|
26
|
+
"""'7' | '#7' | '540,1050' | '540 1050' -> ('ref'|'xy', payload)."""
|
|
27
|
+
s = str(target).strip()
|
|
28
|
+
m = _XY_RE.match(s)
|
|
29
|
+
if m:
|
|
30
|
+
return "xy", (int(m.group(1)), int(m.group(2)))
|
|
31
|
+
m = _REF_RE.match(s)
|
|
32
|
+
if m:
|
|
33
|
+
return "ref", (int(m.group(1)), 0)
|
|
34
|
+
raise AdbError(f"Cannot parse target: {target!r} (use a ref like 3 or x,y)")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _resolve(session: Session | None, target: int | str,
|
|
38
|
+
what: str) -> tuple[int, int]:
|
|
39
|
+
kind, payload = parse_target(target)
|
|
40
|
+
if kind == "xy":
|
|
41
|
+
return payload
|
|
42
|
+
ref = payload[0]
|
|
43
|
+
el = resolve_ref(session, ref)
|
|
44
|
+
if not el or "center" not in el:
|
|
45
|
+
raise AdbError(
|
|
46
|
+
f"No element #{ref} in the current dump.\n"
|
|
47
|
+
f"Run `droid-agent dump` first to refresh the ref map."
|
|
48
|
+
)
|
|
49
|
+
try:
|
|
50
|
+
cx, cy = int(el["center"][0]), int(el["center"][1])
|
|
51
|
+
except (TypeError, ValueError, IndexError, KeyError):
|
|
52
|
+
raise AdbError(
|
|
53
|
+
f"Element #{ref} has no usable coordinates — the stored dump "
|
|
54
|
+
f"is corrupt. Run `droid-agent dump` again."
|
|
55
|
+
)
|
|
56
|
+
label = el.get("label") or el.get("kind") or ""
|
|
57
|
+
_ = what, label # kept for logging hooks
|
|
58
|
+
return cx, cy
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Actions:
|
|
62
|
+
def __init__(self, adb: Adb):
|
|
63
|
+
self.adb = adb
|
|
64
|
+
|
|
65
|
+
def tap(self, target: int | str, session: Session | None = None
|
|
66
|
+
) -> tuple[int, int]:
|
|
67
|
+
x, y = _resolve(session, target, "tap")
|
|
68
|
+
self.adb.shell(f"input tap {x} {y}")
|
|
69
|
+
return x, y
|
|
70
|
+
|
|
71
|
+
def long_press(self, target: int | str, duration_ms: int = 800,
|
|
72
|
+
session: Session | None = None) -> tuple[int, int]:
|
|
73
|
+
x, y = _resolve(session, target, "long-press")
|
|
74
|
+
self.adb.shell(f"input swipe {x} {y} {x} {y} {duration_ms}")
|
|
75
|
+
return x, y
|
|
76
|
+
|
|
77
|
+
def swipe(self, x1: int, y1: int, x2: int, y2: int,
|
|
78
|
+
duration_ms: int = 300) -> tuple[int, int, int, int]:
|
|
79
|
+
self.adb.shell(f"input swipe {x1} {y1} {x2} {y2} {duration_ms}")
|
|
80
|
+
return x1, y1, x2, y2
|
|
81
|
+
|
|
82
|
+
def swipe_dir(self, direction: str, size: tuple[int, int],
|
|
83
|
+
distance: float = 0.6, duration_ms: int = 300
|
|
84
|
+
) -> tuple[int, int, int, int]:
|
|
85
|
+
w, h = size
|
|
86
|
+
cx, cy = w // 2, h // 2
|
|
87
|
+
dx, dy = int(w * distance / 2), int(h * distance / 2)
|
|
88
|
+
start, end = {
|
|
89
|
+
"up": ((cx, cy + dy), (cx, cy - dy)),
|
|
90
|
+
"down": ((cx, cy - dy), (cx, cy + dy)),
|
|
91
|
+
"left": ((cx + dx, cy), (cx - dx, cy)),
|
|
92
|
+
"right": ((cx - dx, cy), (cx + dx, cy)),
|
|
93
|
+
}.get(direction, (None, None))
|
|
94
|
+
if not start or not end:
|
|
95
|
+
raise AdbError(f"Unknown direction {direction!r} (up/down/left/right)")
|
|
96
|
+
return self.swipe(start[0], start[1], end[0], end[1], duration_ms)
|
|
97
|
+
|
|
98
|
+
def type_text(self, text: str, clear: bool = False) -> list[str]:
|
|
99
|
+
"""Type text; newlines become Enter keypresses.
|
|
100
|
+
|
|
101
|
+
Returns a list of warnings (e.g. `%s` sequences the device will
|
|
102
|
+
mangle — `input text` has no escape for it).
|
|
103
|
+
"""
|
|
104
|
+
warnings: list[str] = []
|
|
105
|
+
if "%s" in text or "%%" in text:
|
|
106
|
+
warnings.append(
|
|
107
|
+
"text contains '%s' — `input text` treats it as a space "
|
|
108
|
+
"and cannot escape it; the device will receive a space")
|
|
109
|
+
if clear:
|
|
110
|
+
# no select-all keycombo over `input` — hammer backspace in one
|
|
111
|
+
# shell call (50 chars max, covers typical fields)
|
|
112
|
+
self.adb.shell("; ".join(["input keyevent 67"] * 50))
|
|
113
|
+
lines = text.split("\n")
|
|
114
|
+
for i, line in enumerate(lines):
|
|
115
|
+
if i:
|
|
116
|
+
self.adb.shell("input keyevent 66") # ENTER
|
|
117
|
+
if not line:
|
|
118
|
+
continue
|
|
119
|
+
# inside the quoted arg only `"` `$` `\` backtick need escaping
|
|
120
|
+
escaped = (
|
|
121
|
+
line.replace("\\", "\\\\")
|
|
122
|
+
.replace('"', '\\"')
|
|
123
|
+
.replace("$", "\\$")
|
|
124
|
+
.replace("`", "\\`")
|
|
125
|
+
.replace(" ", "%s")
|
|
126
|
+
)
|
|
127
|
+
self.adb.shell(f'input text "{escaped}"')
|
|
128
|
+
return warnings
|
|
129
|
+
|
|
130
|
+
def key(self, name: str) -> int:
|
|
131
|
+
code = KEYCODES.get(name.lower())
|
|
132
|
+
if code is None:
|
|
133
|
+
if name.isdigit():
|
|
134
|
+
code = int(name)
|
|
135
|
+
if code > 999:
|
|
136
|
+
raise AdbError(f"keyevent code out of range: {code}")
|
|
137
|
+
else:
|
|
138
|
+
raise AdbError(
|
|
139
|
+
f"Unknown key {name!r}. Known: {', '.join(sorted(KEYCODES))}"
|
|
140
|
+
)
|
|
141
|
+
self.adb.shell(f"input keyevent {code}")
|
|
142
|
+
return code
|
|
143
|
+
|
|
144
|
+
def wait(self, seconds: float) -> None:
|
|
145
|
+
import time
|
|
146
|
+
|
|
147
|
+
time.sleep(max(0.0, seconds))
|
droid_agent/adb.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Thin wrapper around the ``adb`` binary.
|
|
2
|
+
|
|
3
|
+
Zero dependencies: locates the platform-tools adb executable and provides
|
|
4
|
+
text/binary command execution plus device listing.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AdbError(RuntimeError):
|
|
17
|
+
"""Raised when an adb command fails or adb cannot be located."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
ADB_NOT_FOUND = (
|
|
21
|
+
"adb executable not found.\n"
|
|
22
|
+
"Install Android platform-tools and make sure 'adb' is on your PATH:\n"
|
|
23
|
+
" https://developer.android.com/tools/releases/platform-tools\n"
|
|
24
|
+
"Or set ANDROID_HOME / ANDROID_SDK_ROOT to your SDK directory."
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def find_adb(explicit: str | None = None) -> str:
|
|
29
|
+
"""Locate the adb binary: explicit path -> PATH -> SDK env vars."""
|
|
30
|
+
candidates: list[str] = []
|
|
31
|
+
if explicit:
|
|
32
|
+
if not os.path.isfile(explicit):
|
|
33
|
+
raise AdbError(f"--adb path does not exist: {explicit}")
|
|
34
|
+
return explicit
|
|
35
|
+
which = shutil.which("adb")
|
|
36
|
+
if which:
|
|
37
|
+
candidates.append(which)
|
|
38
|
+
for env in ("ANDROID_HOME", "ANDROID_SDK_ROOT"):
|
|
39
|
+
root = os.environ.get(env)
|
|
40
|
+
if root:
|
|
41
|
+
exe = "adb.exe" if sys.platform == "win32" else "adb"
|
|
42
|
+
candidates.append(os.path.join(root, "platform-tools", exe))
|
|
43
|
+
for path in candidates:
|
|
44
|
+
if path and os.path.isfile(path):
|
|
45
|
+
return path
|
|
46
|
+
if which:
|
|
47
|
+
return which
|
|
48
|
+
raise AdbError(ADB_NOT_FOUND)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Device:
|
|
53
|
+
serial: str
|
|
54
|
+
state: str # device / unauthorized / offline / no permissions
|
|
55
|
+
model: str = ""
|
|
56
|
+
product: str = ""
|
|
57
|
+
transport_id: str = ""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Adb:
|
|
61
|
+
"""Command runner bound to one adb binary and (optionally) one device."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, serial: str | None = None, adb_path: str | None = None,
|
|
64
|
+
timeout: float = 30.0):
|
|
65
|
+
self.serial = serial
|
|
66
|
+
self.adb_path = find_adb(adb_path)
|
|
67
|
+
self.timeout = timeout
|
|
68
|
+
|
|
69
|
+
def _base(self) -> list[str]:
|
|
70
|
+
args = [self.adb_path]
|
|
71
|
+
if self.serial:
|
|
72
|
+
args += ["-s", self.serial]
|
|
73
|
+
return args
|
|
74
|
+
|
|
75
|
+
def run(self, *args: str, timeout: float | None = None) -> str:
|
|
76
|
+
"""Run an adb command, return stdout as text. Raise AdbError on failure."""
|
|
77
|
+
try:
|
|
78
|
+
proc = subprocess.run(
|
|
79
|
+
self._base() + list(args),
|
|
80
|
+
capture_output=True,
|
|
81
|
+
timeout=timeout or self.timeout,
|
|
82
|
+
)
|
|
83
|
+
except subprocess.TimeoutExpired:
|
|
84
|
+
raise AdbError(
|
|
85
|
+
f"adb {' '.join(args)} timed out — device unresponsive?")
|
|
86
|
+
except (FileNotFoundError, OSError) as e:
|
|
87
|
+
raise AdbError(f"cannot run adb at {self.adb_path!r}: {e}")
|
|
88
|
+
stderr = proc.stderr.decode("utf-8", "replace").strip()
|
|
89
|
+
stdout = proc.stdout.decode("utf-8", "replace")
|
|
90
|
+
if proc.returncode != 0:
|
|
91
|
+
raise AdbError(
|
|
92
|
+
f"adb {' '.join(args)} failed ({proc.returncode}): "
|
|
93
|
+
f"{stderr or stdout.strip()}"
|
|
94
|
+
)
|
|
95
|
+
# adb occasionally reports errors on stdout/stderr with rc=0
|
|
96
|
+
for channel in (stdout, stderr):
|
|
97
|
+
if channel.lstrip().lower().startswith("error:"):
|
|
98
|
+
raise AdbError(channel.strip())
|
|
99
|
+
return stdout
|
|
100
|
+
|
|
101
|
+
def shell(self, cmd: str, timeout: float | None = None) -> str:
|
|
102
|
+
return self.run("shell", cmd, timeout=timeout)
|
|
103
|
+
|
|
104
|
+
def exec_out(self, cmd: str, timeout: float | None = None) -> bytes:
|
|
105
|
+
"""Binary-safe exec-out (screenshots, file reads)."""
|
|
106
|
+
proc = subprocess.run(
|
|
107
|
+
self._base() + ["exec-out", cmd],
|
|
108
|
+
capture_output=True,
|
|
109
|
+
timeout=timeout or self.timeout,
|
|
110
|
+
)
|
|
111
|
+
if proc.returncode != 0:
|
|
112
|
+
raise AdbError(
|
|
113
|
+
f"adb exec-out failed ({proc.returncode}): "
|
|
114
|
+
f"{proc.stderr.decode('utf-8', 'replace').strip()}"
|
|
115
|
+
)
|
|
116
|
+
return proc.stdout
|
|
117
|
+
|
|
118
|
+
def push(self, local: str, remote: str) -> str:
|
|
119
|
+
return self.run("push", local, remote)
|
|
120
|
+
|
|
121
|
+
def pull(self, remote: str, local: str) -> str:
|
|
122
|
+
return self.run("pull", remote, local)
|
|
123
|
+
|
|
124
|
+
# -- connectivity ----------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def connect(self, host: str, port: int = 5555) -> str:
|
|
127
|
+
return self.run("connect", f"{host}:{port}").strip()
|
|
128
|
+
|
|
129
|
+
def pair(self, host: str, port: int, code: str) -> str:
|
|
130
|
+
"""Android 11+ wireless pairing."""
|
|
131
|
+
return self.run("pair", f"{host}:{port}", code).strip()
|
|
132
|
+
|
|
133
|
+
def disconnect(self, host: str | None = None,
|
|
134
|
+
port: int | None = None) -> str:
|
|
135
|
+
if host and port:
|
|
136
|
+
target = f"{host}:{port}"
|
|
137
|
+
elif host:
|
|
138
|
+
target = host
|
|
139
|
+
else:
|
|
140
|
+
target = ""
|
|
141
|
+
return self.run("disconnect", *([target] if target else [])).strip()
|
|
142
|
+
|
|
143
|
+
# -- listing -----------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
def devices(self) -> list[Device]:
|
|
146
|
+
out = self.run("devices", "-l")
|
|
147
|
+
result: list[Device] = []
|
|
148
|
+
attr_prefixes = ("model:", "device:", "product:",
|
|
149
|
+
"transport_id:", "usb:")
|
|
150
|
+
for line in out.splitlines()[1:]:
|
|
151
|
+
line = line.strip()
|
|
152
|
+
if not line:
|
|
153
|
+
continue
|
|
154
|
+
parts = line.split()
|
|
155
|
+
if len(parts) < 2:
|
|
156
|
+
continue
|
|
157
|
+
# state = tokens until the first key:value attribute
|
|
158
|
+
# (handles multi-word states like "no permissions (...)")
|
|
159
|
+
state_parts = []
|
|
160
|
+
idx = 1
|
|
161
|
+
while idx < len(parts) and not parts[idx].startswith(attr_prefixes):
|
|
162
|
+
state_parts.append(parts[idx])
|
|
163
|
+
idx += 1
|
|
164
|
+
dev = Device(serial=parts[0], state=" ".join(state_parts) or "?")
|
|
165
|
+
for kv in parts[idx:]:
|
|
166
|
+
if kv.startswith("model:"):
|
|
167
|
+
dev.model = kv.split(":", 1)[1]
|
|
168
|
+
elif kv.startswith("product:"):
|
|
169
|
+
dev.product = kv.split(":", 1)[1]
|
|
170
|
+
elif kv.startswith("transport_id:"):
|
|
171
|
+
dev.transport_id = kv.split(":", 1)[1]
|
|
172
|
+
result.append(dev)
|
|
173
|
+
return result
|
|
174
|
+
|
|
175
|
+
def require_device(self) -> None:
|
|
176
|
+
"""Fail fast if no device is reachable; auto-select a single device."""
|
|
177
|
+
devs = [d for d in self.devices() if d.state == "device"]
|
|
178
|
+
if not devs:
|
|
179
|
+
raise AdbError(
|
|
180
|
+
"No device attached.\n"
|
|
181
|
+
" - USB: plug in a device with USB debugging enabled\n"
|
|
182
|
+
" - WiFi: droid-agent connect <ip>:5555\n"
|
|
183
|
+
" - Emulator: start one, it shows up automatically"
|
|
184
|
+
)
|
|
185
|
+
if self.serial:
|
|
186
|
+
if not any(d.serial == self.serial for d in devs):
|
|
187
|
+
raise AdbError(
|
|
188
|
+
f"Device '{self.serial}' not found. Attached: "
|
|
189
|
+
+ ", ".join(d.serial for d in devs)
|
|
190
|
+
)
|
|
191
|
+
elif len(devs) == 1:
|
|
192
|
+
self.serial = devs[0].serial
|
|
193
|
+
else:
|
|
194
|
+
raise AdbError(
|
|
195
|
+
"Multiple devices attached — pick one with -s:\n"
|
|
196
|
+
+ "\n".join(f" {d.serial} ({d.model or 'device'})"
|
|
197
|
+
for d in devs)
|
|
198
|
+
)
|