pilotdroid 0.6.1__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.
pilotdroid/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """pilotdroid — uiautomator2-compatible Python client for the pilotdroid agent.
2
+
3
+ import pilotdroid
4
+ d = pilotdroid.connect(port=17932, serial="<adb serial>")
5
+ d(text="OK").click()
6
+ """
7
+
8
+ from .u2shim import connect, Device # noqa: F401
@@ -0,0 +1,390 @@
1
+ #!/usr/bin/env python3
2
+ """Minimal pilotdroid agent client — speaks the PD01 18-byte frame protocol.
3
+
4
+ Frame: magic"PD01"(4) ver(u8) ch(u8) type(u16) flags(u16) req_id(u32) len(u32)
5
+ + msgpack payload (all integers big-endian, docs/02-protocol.md §2)
6
+
7
+ Usage: agent_client.py [--port PORT] <cmd> [args]
8
+ hello | ping | inject-tap X Y | inject-swipe X1 Y1 X2 Y2 MS | dump | shot OUT |
9
+ stop | bench (all ops + latency JSON)
10
+ """
11
+ import json, socket, struct, sys, threading, time
12
+
13
+ import msgpack
14
+
15
+ MAGIC = b"PD01"
16
+ VER = 0
17
+ CH_CTRL = 0
18
+ F_RESP, F_MORE, F_ERR, F_NOACK = 0x0001, 0x0002, 0x0004, 0x0008
19
+
20
+ T = dict(HELLO=0x0001, HELLO_ACK=0x0002, PING=0x0003, PONG=0x0004,
21
+ INJECT=0x0010, INJECT_RESULT=0x0011, DUMP=0x0020, QUERY=0x0021,
22
+ SCREENSHOT=0x0030, BATCH=0x0040, BATCH_RESULT=0x0041,
23
+ STREAM_CTRL=0x0050, FRAME=0x0001, WATCH_HIT=0x0002,
24
+ TEXT=0x0060, WATCH=0x0070, WATCH_ARM=0x0071,
25
+ WATCH_DISARM=0x0072, APP_INFO=0x0080, AGENT_STOP=0x00F0)
26
+
27
+
28
+ class Agent:
29
+ def __init__(self, port=17932):
30
+ self.port = port
31
+ self.sock = None
32
+ self.req_id = 0
33
+ self._lock = threading.Lock()
34
+
35
+ def connect(self):
36
+ self.sock = socket.create_connection(("127.0.0.1", self.port), timeout=10)
37
+ self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
38
+ return self
39
+
40
+ def close(self):
41
+ if self.sock:
42
+ self.sock.close()
43
+
44
+ def _recvn(self, n):
45
+ buf = b""
46
+ while len(buf) < n:
47
+ d = self.sock.recv(n - len(buf))
48
+ if not d:
49
+ raise ConnectionError("agent closed the socket")
50
+ buf += d
51
+ return buf
52
+
53
+ def call(self, mtype, payload=None, flags=0):
54
+ # one control conn serializes all ops (a second conn would REPLACE
55
+ # this session) — lock so a watcher thread + user thread can share.
56
+ with self._lock:
57
+ return self._call_locked(mtype, payload, flags)
58
+
59
+ def _call_locked(self, mtype, payload=None, flags=0):
60
+ self.req_id += 1
61
+ body = msgpack.packb(payload or {}, use_bin_type=True)
62
+ hdr = MAGIC + struct.pack(">BBHHI", VER, CH_CTRL, mtype, flags,
63
+ self.req_id) + struct.pack(">I", len(body))
64
+ self.sock.sendall(hdr + body)
65
+ if flags & F_NOACK:
66
+ return None # fire-and-forget: contract says no response frame
67
+ rh = self._recvn(18)
68
+ assert rh[:4] == MAGIC, f"bad magic {rh[:4]!r}"
69
+ ver, ch, rtype, flags, rid = struct.unpack(">BBHHI", rh[4:14])
70
+ plen = struct.unpack(">I", rh[14:18])[0]
71
+ data = self._recvn(plen) if plen else b""
72
+ obj = msgpack.unpackb(data, raw=False) if data else {}
73
+ return dict(type=rtype, flags=flags, req_id=rid, payload=obj,
74
+ raw_payload=data)
75
+
76
+ def hello(self):
77
+ return self.call(T["HELLO"], {"proto": VER})
78
+
79
+ def ping(self):
80
+ return self.call(T["PING"], {})
81
+
82
+ def inject_tap(self, x, y, wait_finish=False, backend=None):
83
+ req = {"op": "tap", "x": float(x), "y": float(y),
84
+ "wait_finish": bool(wait_finish)}
85
+ if backend:
86
+ req["backend"] = backend
87
+ return self.call(T["INJECT"], req)
88
+
89
+ def inject_swipe(self, x1, y1, x2, y2, duration_ms=300, steps=10,
90
+ backend=None):
91
+ req = {"op": "swipe", "x1": float(x1), "y1": float(y1),
92
+ "x2": float(x2), "y2": float(y2),
93
+ "duration_ms": int(duration_ms), "steps": int(steps)}
94
+ if backend:
95
+ req["backend"] = backend
96
+ return self.call(T["INJECT"], req)
97
+
98
+ def inject_key(self, keycode, meta=0, backend=None):
99
+ req = {"kind": "Key", "keycode": int(keycode),
100
+ "meta": int(meta), "wait_finish": False}
101
+ if backend:
102
+ req["backend"] = backend
103
+ return self.call(T["INJECT"], req)
104
+
105
+ def inject_swipe_pts(self, x1, y1, x2, y2, duration_ms=300, steps=10,
106
+ backend=None):
107
+ pts = []
108
+ for i in range(int(steps) + 1):
109
+ f = i / int(steps)
110
+ pts.append({"action": 0 if i == 0 else (1 if i == int(steps) else 2),
111
+ "x": float(x1) + (float(x2) - float(x1)) * f,
112
+ "y": float(y1) + (float(y2) - float(y1)) * f,
113
+ "t_ms": int(int(duration_ms) * f)})
114
+ req = {"kind": "Swipe", "points": pts, "wait_finish": False}
115
+ if backend:
116
+ req["backend"] = backend
117
+ return self.call(T["INJECT"], req)
118
+
119
+ def inject_multi(self, points, wait_finish=True, backend=None):
120
+ """Multi-pointer INJECT: points=[{action,x,y,t_ms,pid}] — >1 distinct
121
+ pid takes the agent's multi-pointer path (pinch/gesture class)."""
122
+ req = {"kind": "Swipe", "points": points,
123
+ "wait_finish": bool(wait_finish)}
124
+ if backend:
125
+ req["backend"] = backend
126
+ return self.call(T["INJECT"], req)
127
+
128
+ def watch(self, selector, action="click", timeout_ms=10000, poll_ms=None):
129
+ """WATCH op (§4.9): device-side selector->action loop — detection
130
+ latency is one tree-walk, not a host round-trip per poll."""
131
+ req = {"selector": selector, "action": {"type": action},
132
+ "timeout_ms": int(timeout_ms)}
133
+ if poll_ms:
134
+ req["poll_ms"] = int(poll_ms)
135
+ return self.call(T["WATCH"], req)
136
+
137
+ def watch_arm(self, selector, action="click", timeout_ms=0, poll_ms=None):
138
+ """WATCH_ARM (§4.9 async): arms a device-side poll thread — returns
139
+ immediately; hits arrive as WATCH_HIT frames on the media socket
140
+ (media_connect + read_frame, ch=1 type 0x0002)."""
141
+ req = {"selector": selector, "action": {"type": action},
142
+ "timeout_ms": int(timeout_ms)}
143
+ if poll_ms:
144
+ req["poll_ms"] = int(poll_ms)
145
+ return self.call(T["WATCH_ARM"], req)
146
+
147
+ def watch_disarm(self, watch_id):
148
+ return self.call(T["WATCH_DISARM"], {"watch_id": int(watch_id)})
149
+
150
+ def app_info(self):
151
+ """APP_INFO (CAP_APP_INFO): foreground pkg via UiAutomation — ~ms,
152
+ no dumpsys spawn."""
153
+ return self.call(T["APP_INFO"], {})
154
+
155
+ def inject_tap_noack(self, x, y):
156
+ return self.call(T["INJECT"],
157
+ {"kind": "Tap",
158
+ "points": [{"action": 0, "x": float(x),
159
+ "y": float(y), "t_ms": 0},
160
+ {"action": 1, "x": float(x),
161
+ "y": float(y), "t_ms": 75}],
162
+ "wait_finish": False}, flags=F_NOACK)
163
+
164
+ def dump(self):
165
+ return self.call(T["DUMP"], {})
166
+
167
+ def query(self, selector):
168
+ return self.call(T["QUERY"], {"selector": selector})
169
+
170
+ def wait_until(self, selector, timeout_ms=5000, poll_ms=None):
171
+ req = {"selector": selector, "timeout_ms": int(timeout_ms)}
172
+ if poll_ms:
173
+ req["poll_ms"] = int(poll_ms)
174
+ return self.batch([{"wait_until": req}])
175
+
176
+ def batch(self, ops, fail_policy="stop", deadline_ms=None, poll_ms=None):
177
+ req = {"ops": ops, "fail_policy": fail_policy}
178
+ if deadline_ms:
179
+ req["deadline_ms"] = int(deadline_ms)
180
+ if poll_ms:
181
+ req["poll_ms"] = int(poll_ms)
182
+ return self.call(T["BATCH"], req)
183
+
184
+ def text(self, s, clear=False):
185
+ return self.call(T["TEXT"], {"text": str(s), "clear": bool(clear)})
186
+
187
+ def shot(self, quality=80, scale=1.0):
188
+ return self.call(T["SCREENSHOT"],
189
+ {"format": "jpeg", "quality": quality,
190
+ "scale": float(scale)})
191
+
192
+ def stream_start(self, fps=5, scale=0.5, quality=70, fmt="jpeg"):
193
+ return self.call(T["STREAM_CTRL"],
194
+ {"op": "start", "fps": int(fps),
195
+ "scale": float(scale), "quality": int(quality),
196
+ "format": fmt})
197
+
198
+ def stream_stop(self):
199
+ return self.call(T["STREAM_CTRL"], {"op": "stop"})
200
+
201
+ def stop(self):
202
+ return self.call(T["AGENT_STOP"], {})
203
+
204
+
205
+ def media_connect(port):
206
+ """Open the ch=1 media socket (second adb forward)."""
207
+ s = socket.create_connection(("127.0.0.1", port), timeout=10)
208
+ s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
209
+ return s
210
+
211
+
212
+ def read_frame(sock):
213
+ """Read one PD01 frame; returns (ch, type, flags, seq, payload) or None on EOF."""
214
+ def recvn(n):
215
+ buf = b""
216
+ while len(buf) < n:
217
+ d = sock.recv(n - len(buf))
218
+ if not d:
219
+ return None
220
+ buf += d
221
+ return buf
222
+ rh = recvn(18)
223
+ if rh is None:
224
+ return None
225
+ assert rh[:4] == MAGIC, f"bad magic {rh[:4]!r}"
226
+ _ver, ch, rtype, flags, rid = struct.unpack(">BBHHI", rh[4:14])
227
+ plen = struct.unpack(">I", rh[14:18])[0]
228
+ data = recvn(plen) if plen else b""
229
+ return (ch, rtype, flags, rid,
230
+ msgpack.unpackb(data, raw=False) if data else {})
231
+
232
+
233
+ def _timed(fn, n=1):
234
+ """Return (last_result, wall_ms_list, on_device_ms_list).
235
+
236
+ on_device = agent-internal cost_ns from the response payload, so the
237
+ report separates adb-forward transport overhead from real work."""
238
+ res, ts, dev = None, [], []
239
+ for _ in range(n):
240
+ t0 = time.perf_counter()
241
+ res = fn()
242
+ ts.append((time.perf_counter() - t0) * 1000)
243
+ c = res.get("payload", {}).get("cost_ns") if isinstance(res, dict) else None
244
+ dev.append(c / 1e6 if c else 0.0)
245
+ return res, ts, dev
246
+
247
+
248
+ def bench(a, n=30):
249
+ """Run every opcode n times, return latency dict."""
250
+ out = {}
251
+ _, ts, _ = _timed(a.hello, 3)
252
+ out["hello_ms"] = ts
253
+ _, ts, _ = _timed(a.ping, n)
254
+ out["ping_ms"] = ts
255
+ res, ts, dev = _timed(lambda: a.inject_tap(700, 1600), n)
256
+ out["inject_tap_ms"] = ts
257
+ out["inject_tap_dev_ms"] = dev
258
+ out["inject_tap_last"] = res["payload"]
259
+ res, ts, dev = _timed(lambda: a.inject_swipe(700, 2000, 700, 1500, 300), 5)
260
+ out["inject_swipe_ms"] = ts
261
+ out["inject_swipe_dev_ms"] = dev
262
+ out["inject_swipe_last"] = res["payload"]
263
+ res, ts, dev = _timed(a.dump, n)
264
+ out["dump_ms"] = ts
265
+ out["dump_dev_ms"] = dev
266
+ out["dump_bytes"] = len(res["raw_payload"])
267
+ res, ts, _ = _timed(a.shot, 10)
268
+ out["shot_ms"] = ts
269
+ out["shot_bytes"] = len(res["raw_payload"])
270
+ return out
271
+
272
+
273
+ def _pct(ts):
274
+ ts = sorted(ts)
275
+ return {"mean": round(sum(ts) / len(ts), 2),
276
+ "p50": round(ts[len(ts) // 2], 2),
277
+ "p95": round(ts[int(len(ts) * 0.95)], 2),
278
+ "min": round(ts[0], 2), "max": round(ts[-1], 2)}
279
+
280
+
281
+ def main():
282
+ args = sys.argv[1:]
283
+ port = 17932
284
+ if args[:2] == ["--port", args[1] if len(args) > 1 else ""]:
285
+ port = int(args[1]); args = args[2:]
286
+ elif args and args[0] == "--port":
287
+ port = int(args[1]); args = args[2:]
288
+ cmd = args[0] if args else "hello"
289
+ a = Agent(port).connect()
290
+ try:
291
+ if cmd == "hello":
292
+ print(json.dumps(a.hello(), default=str))
293
+ elif cmd == "ping":
294
+ print(json.dumps(a.ping(), default=str))
295
+ elif cmd == "inject-tap": # inject-tap X Y [backend]
296
+ print(json.dumps(a.inject_tap(args[1], args[2],
297
+ backend=args[3] if len(args) > 3 else None), default=str))
298
+ elif cmd == "inject-swipe": # inject-swipe X1 Y1 X2 Y2 MS [backend]
299
+ print(json.dumps(a.inject_swipe(*map(float, args[1:6]),
300
+ backend=args[6] if len(args) > 6 else None), default=str))
301
+ elif cmd == "inject-key": # inject-key KEYCODE [meta] [backend]
302
+ print(json.dumps(a.inject_key(args[1],
303
+ meta=args[2] if len(args) > 2 else 0,
304
+ backend=args[3] if len(args) > 3 else None), default=str))
305
+ elif cmd == "swipe-pts": # swipe-pts X1 Y1 X2 Y2 MS STEPS [backend]
306
+ print(json.dumps(a.inject_swipe_pts(*map(float, args[1:7]),
307
+ backend=args[7] if len(args) > 7 else None), default=str))
308
+ elif cmd == "noack-tap":
309
+ a.inject_tap_noack(args[1], args[2])
310
+ # contract: no frame comes back — a read must time out
311
+ a.sock.settimeout(0.5)
312
+ try:
313
+ a._recvn(18)
314
+ print("VIOLATION: got a response to a NOACK request")
315
+ except socket.timeout:
316
+ print("OK: no response frame (fire-and-forget honored)")
317
+ elif cmd == "dump":
318
+ r = a.dump()
319
+ sys.stdout.write(r["payload"].get("xml") or r["payload"].get("data", ""))
320
+ elif cmd == "query": # query '{"text":"x"}' or '{"id":"...","index":N}'
321
+ print(json.dumps(a.query(json.loads(args[1])), default=str))
322
+ elif cmd == "wait": # wait '{"text":"x"}' [timeout_ms]
323
+ sel = json.loads(args[1])
324
+ print(json.dumps(a.wait_until(sel, int(args[2]) if len(args) > 2 else 5000), default=str))
325
+ elif cmd == "batch": # batch '<ops json array>'
326
+ print(json.dumps(a.batch(json.loads(args[1])), default=str))
327
+ elif cmd == "text":
328
+ print(json.dumps(a.text(args[1], clear=len(args) > 2), default=str))
329
+ elif cmd == "shot": # shot OUT [scale] [quality]
330
+ scale = float(args[2]) if len(args) > 2 else 1.0
331
+ qual = int(args[3]) if len(args) > 3 else 80
332
+ r = a.shot(quality=qual, scale=scale)
333
+ p = r["payload"]
334
+ if "data" not in p:
335
+ # agent answered with an error payload (e.g. FLAG_SECURE
336
+ # window focused — MIUI app-lock/keyguard blocks capture)
337
+ sys.exit(f"shot failed: {p.get('code', '?')} "
338
+ f"{p.get('message', '')} {p.get('error', '')}".strip())
339
+ open(args[1], "wb").write(p["data"])
340
+ print(f"wrote {len(p['data'])}B {p.get('w')}x{p.get('h')} scale={p.get('scale',1)} -> {args[1]}")
341
+ elif cmd == "shot-stat": # shot-stat SCALE QUALITY -> timing+bytes JSON
342
+ r = a.shot(quality=int(args[2]), scale=float(args[1]))
343
+ p = r["payload"]
344
+ p["data"] = f"<{len(p['data'])}B>"
345
+ print(json.dumps(p, default=str))
346
+ elif cmd == "stream-start": # stream-start [fps] [scale] [quality]
347
+ print(json.dumps(a.stream_start(
348
+ fps=args[1] if len(args) > 1 else 5,
349
+ scale=args[2] if len(args) > 2 else 0.5,
350
+ quality=args[3] if len(args) > 3 else 70), default=str))
351
+ elif cmd == "stream-stop":
352
+ print(json.dumps(a.stream_stop(), default=str))
353
+ elif cmd == "stream-recv": # stream-recv MEDIA_PORT [n] [timeout_s]
354
+ import agent_client as _self # noqa: F401
355
+ ms = media_connect(int(args[1]))
356
+ want = int(args[2]) if len(args) > 2 else 5
357
+ ms.settimeout(float(args[3]) if len(args) > 3 else 10)
358
+ t0 = time.time(); frames = []
359
+ while len(frames) < want:
360
+ try:
361
+ f = read_frame(ms)
362
+ except socket.timeout:
363
+ break
364
+ if f is None:
365
+ frames.append({"eof": True}); break
366
+ ch, ty, fl, seq, p = f
367
+ p2 = dict(p)
368
+ if isinstance(p2.get("data"), (bytes, bytearray)):
369
+ p2["jpeg"] = p2["data"][:2] == b"\xff\xd8"
370
+ p2["bytes"] = len(p2["data"]); del p2["data"]
371
+ p2["seq"], p2["ch"], p2["type"], p2["flags"] = seq, ch, ty, fl
372
+ frames.append(p2)
373
+ ms.close()
374
+ print(json.dumps({"n": len(frames), "wall_s": round(time.time() - t0, 2),
375
+ "frames": frames}, default=str))
376
+ elif cmd == "stop":
377
+ print(json.dumps(a.stop(), default=str))
378
+ elif cmd == "bench":
379
+ n = int(args[1]) if len(args) > 1 else 30
380
+ b = bench(a, n)
381
+ print(json.dumps({k: (_pct(v) if k.endswith("_ms") else v)
382
+ for k, v in b.items()}, indent=2))
383
+ else:
384
+ sys.exit(f"unknown cmd {cmd}")
385
+ finally:
386
+ a.close()
387
+
388
+
389
+ if __name__ == "__main__":
390
+ main()
@@ -0,0 +1,148 @@
1
+ """pilotdroid-cli — lazy bootstrap for the Rust CLI binary.
2
+
3
+ The PyPI wheel ships no binary (pure-python whl). On first run this entry
4
+ point downloads the release asset for the current platform from
5
+ github.com/mofanx/pilotdroid/releases, verifies it against the release's
6
+ SHA256SUMS.txt, caches it under ``~/.cache/pilotdroid/<tag>/``, then
7
+ ``os.execv``'s the real binary with argv passthrough — so
8
+ ``pilotdroid-cli setup``, ``pilotdroid-cli serve`` etc. work as if the
9
+ binary were installed directly.
10
+
11
+ Refuses to exec on sha256 mismatch or any download/integrity failure.
12
+ """
13
+
14
+ import hashlib
15
+ import importlib.metadata
16
+ import os
17
+ import platform
18
+ import stat
19
+ import sys
20
+ import urllib.request
21
+
22
+ REPO = "mofanx/pilotdroid"
23
+ TIMEOUT = 60
24
+
25
+ # (platform.system(), normalized machine) -> release asset basename
26
+ _ASSETS = {
27
+ ("Linux", "x86_64"): "pilotdroid-cli-linux-x86_64",
28
+ ("Darwin", "arm64"): "pilotdroid-cli-macos-arm64",
29
+ ("Windows", "amd64"): "pilotdroid-cli-windows-x86_64.exe",
30
+ }
31
+
32
+
33
+ def _machine():
34
+ m = platform.machine().lower()
35
+ return {"aarch64": "arm64", "x64": "x86_64", "amd64": "amd64"}.get(m, m)
36
+
37
+
38
+ def _asset_name():
39
+ sys_name, mach = platform.system(), _machine()
40
+ name = _ASSETS.get((sys_name, mach))
41
+ if name is None:
42
+ supported = ", ".join(sorted(a for a in _ASSETS.values()))
43
+ raise RuntimeError(
44
+ f"no pilotdroid-cli release binary for {sys_name}/{mach} — "
45
+ f"supported assets: {supported}. Build from source instead: "
46
+ "github.com/mofanx/pilotdroid (cargo build -p pilotdroid-cli)")
47
+ return name
48
+
49
+
50
+ def _tag():
51
+ try:
52
+ return "v" + importlib.metadata.version("pilotdroid")
53
+ except importlib.metadata.PackageNotFoundError:
54
+ return "latest" # dev tree without install
55
+
56
+
57
+ def _url(tag, name):
58
+ if tag == "latest":
59
+ return f"https://github.com/{REPO}/releases/latest/download/{name}"
60
+ return f"https://github.com/{REPO}/releases/download/{tag}/{name}"
61
+
62
+
63
+ def _fetch(url):
64
+ with urllib.request.urlopen(url, timeout=TIMEOUT) as r:
65
+ return r.read()
66
+
67
+
68
+ def _expected_sha(sums_text, asset):
69
+ for line in sums_text.splitlines():
70
+ parts = line.split()
71
+ if len(parts) == 2 and parts[1] == asset:
72
+ return parts[0]
73
+ raise RuntimeError(
74
+ f"{asset} not listed in SHA256SUMS.txt — refusing to run an "
75
+ "unverifiable binary")
76
+
77
+
78
+ def _cache_dir(tag):
79
+ return os.path.join(os.path.expanduser("~"), ".cache", "pilotdroid", tag)
80
+
81
+
82
+ def _sums(tag):
83
+ return _fetch(_url(tag, "SHA256SUMS.txt")).decode()
84
+
85
+
86
+ def _write_verified(path, blob, want, asset):
87
+ got = hashlib.sha256(blob).hexdigest()
88
+ if got != want:
89
+ raise RuntimeError(
90
+ f"sha256 mismatch for {asset}: got {got}, want {want} — "
91
+ "refusing to exec an unverified binary")
92
+ tmp = path + ".tmp"
93
+ os.makedirs(os.path.dirname(path), exist_ok=True)
94
+ with open(tmp, "wb") as f:
95
+ f.write(blob)
96
+ os.chmod(tmp, os.stat(tmp).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
97
+ os.replace(tmp, path)
98
+
99
+
100
+ def _ensure_binary():
101
+ asset, tag = _asset_name(), _tag()
102
+ path = os.path.join(_cache_dir(tag), asset)
103
+ if os.path.exists(path):
104
+ # Cache hit still verifies: a re-uploaded/corrupted release asset
105
+ # must not be exec'd. Offline (SUMS unreachable) → run the cache.
106
+ try:
107
+ want = _expected_sha(_sums(tag), asset)
108
+ except Exception:
109
+ return path
110
+ with open(path, "rb") as f:
111
+ if hashlib.sha256(f.read()).hexdigest() == want:
112
+ return path
113
+ os.remove(path) # stale/corrupt cache → fall through to re-download
114
+ try:
115
+ return _finish(path, asset, tag, want)
116
+ except Exception as e:
117
+ raise RuntimeError(
118
+ f"cached {asset} failed sha256 re-check and re-download "
119
+ f"failed: {e}")
120
+ try:
121
+ blob = _fetch(_url(tag, asset))
122
+ want = _expected_sha(_sums(tag), asset)
123
+ except Exception as e:
124
+ raise RuntimeError(
125
+ f"failed to download {asset} ({tag}): {e}. Check network/proxy, "
126
+ "or download manually from "
127
+ f"github.com/{REPO}/releases and put it at {path}")
128
+ _write_verified(path, blob, want, asset)
129
+ return path
130
+
131
+
132
+ def _finish(path, asset, tag, want):
133
+ blob = _fetch(_url(tag, asset))
134
+ _write_verified(path, blob, want, asset)
135
+ return path
136
+
137
+
138
+ def main():
139
+ try:
140
+ path = _ensure_binary()
141
+ except RuntimeError as e:
142
+ sys.exit(f"pilotdroid-cli bootstrap: {e}")
143
+ # Windows argv[0] is cosmetic; execv semantics replace this process.
144
+ os.execv(path, [path] + sys.argv[1:])
145
+
146
+
147
+ if __name__ == "__main__":
148
+ main()