android-device-control 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.
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env python3
2
+ """Append and inspect a local social account status ledger."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import fcntl
7
+ from datetime import datetime, timezone
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import sys
13
+ from typing import Any
14
+
15
+ STATES = ("planned", "in-progress", "submitted-uncertain", "created", "verified", "blocked")
16
+ HANDLE_STATES = ("unknown", "proposed", "unverified", "verified", "not-applicable")
17
+ SECRET_PATTERNS = (
18
+ re.compile(r"(?i)\b(?:password|passcode|token|secret|otp|verification code)\s*[:=]\s*\S+"),
19
+ re.compile(r"\b\d{6,8}\b"),
20
+ re.compile(r"(?i)\b(?:bearer\s+)[A-Za-z0-9._~+/-]{12,}"),
21
+ )
22
+
23
+
24
+ class ReceiptError(ValueError):
25
+ """Invalid or unsafe receipt operation."""
26
+
27
+
28
+ def default_ledger() -> Path:
29
+ base = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local" / "state"))
30
+ return base / "android-control" / "social-accounts.jsonl"
31
+
32
+
33
+ def clean_text(value: str, field: str, *, limit: int = 500) -> str:
34
+ value = value.strip()
35
+ if len(value) > limit or "\n" in value or "\r" in value or "\0" in value:
36
+ raise ReceiptError(f"{field} must be one line and at most {limit} characters")
37
+ if any(pattern.search(value) for pattern in SECRET_PATTERNS):
38
+ raise ReceiptError(f"{field} appears to contain a secret or verification code")
39
+ return value
40
+
41
+
42
+ def parse_ledger(contents: str) -> list[dict[str, Any]]:
43
+ records = []
44
+ for number, line in enumerate(contents.splitlines(), 1):
45
+ if not line.strip():
46
+ continue
47
+ try:
48
+ item = json.loads(line)
49
+ except json.JSONDecodeError as exc:
50
+ raise ReceiptError(f"ledger line {number} is invalid JSON") from exc
51
+ required = {"brand", "platform", "state", "recorded_at"}
52
+ if not isinstance(item, dict) or not required <= item.keys():
53
+ raise ReceiptError(f"ledger line {number} has an invalid record shape")
54
+ if (not isinstance(item["brand"], str) or not item["brand"].strip()
55
+ or not isinstance(item["platform"], str) or not item["platform"].strip()
56
+ or item["state"] not in STATES
57
+ or not isinstance(item["recorded_at"], str) or not item["recorded_at"].strip()):
58
+ raise ReceiptError(f"ledger line {number} has invalid brand, platform, state, or timestamp")
59
+ if "handle_state" in item and item["handle_state"] not in HANDLE_STATES:
60
+ raise ReceiptError(f"ledger line {number} has invalid handle state")
61
+ for field in ("display_name", "handle", "evidence", "note", "next_check"):
62
+ if field in item and item[field] is not None and not isinstance(item[field], str):
63
+ raise ReceiptError(f"ledger line {number} has an invalid {field}")
64
+ if item["state"] == "verified" and not item.get("evidence"):
65
+ raise ReceiptError(f"ledger line {number} marks verified without identity evidence")
66
+ if item.get("handle_state") == "verified" and not item.get("handle"):
67
+ raise ReceiptError(f"ledger line {number} marks a handle verified without a handle")
68
+ if item["state"] == "submitted-uncertain" and not item.get("next_check"):
69
+ raise ReceiptError(f"ledger line {number} marks an uncertain submission without a next check")
70
+ records.append(item)
71
+ return records
72
+
73
+
74
+ def latest_records(records: list[dict[str, Any]]) -> dict[tuple[str, str], dict[str, Any]]:
75
+ latest: dict[tuple[str, str], dict[str, Any]] = {}
76
+ for record in records:
77
+ key = (record["brand"].casefold(), record["platform"].casefold())
78
+ latest[key] = record
79
+ return latest
80
+
81
+
82
+ def make_record(*, brand: str, platform: str, state: str, note: str = "",
83
+ evidence: str = "", display_name: str = "", handle: str = "",
84
+ handle_state: str = "unknown", next_check: str = "",
85
+ existing: list[dict[str, Any]] | None = None,
86
+ reconcile: bool = False, now: datetime | None = None) -> dict[str, Any]:
87
+ brand = clean_text(brand, "brand", limit=100)
88
+ platform = clean_text(platform, "platform", limit=60)
89
+ if not brand or not platform:
90
+ raise ReceiptError("brand and platform are required")
91
+ if state not in STATES:
92
+ raise ReceiptError(f"state must be one of: {', '.join(STATES)}")
93
+ if handle_state not in HANDLE_STATES:
94
+ raise ReceiptError(f"handle state must be one of: {', '.join(HANDLE_STATES)}")
95
+ note = clean_text(note, "note")
96
+ evidence = clean_text(evidence, "evidence", limit=300)
97
+ display_name = clean_text(display_name, "display name", limit=100)
98
+ handle = clean_text(handle, "handle", limit=120)
99
+ next_check = clean_text(next_check, "next check", limit=300)
100
+ current = latest_records(existing or []).get((brand.casefold(), platform.casefold()))
101
+ if (current and current["state"] == "submitted-uncertain"
102
+ and state in ("planned", "in-progress", "created", "verified")
103
+ and not reconcile):
104
+ raise ReceiptError("an uncertain submission must be reconciled before this transition; use --reconcile with new evidence")
105
+ if current and current["state"] == "verified" and state in ("created", "verified") and not reconcile:
106
+ raise ReceiptError("this brand/platform is already verified; use --reconcile only for a documented follow-up")
107
+ if state == "verified" and not evidence:
108
+ raise ReceiptError("verified status requires --evidence describing the identity readback")
109
+ if state == "submitted-uncertain" and not next_check:
110
+ raise ReceiptError("submitted-uncertain requires --next-check describing the reconciliation step")
111
+ if handle_state == "verified" and not handle:
112
+ raise ReceiptError("a verified handle must include the visible handle")
113
+ stamp = (now or datetime.now(timezone.utc)).astimezone(timezone.utc).isoformat(timespec="seconds")
114
+ return {
115
+ "recorded_at": stamp,
116
+ "brand": brand,
117
+ "platform": platform,
118
+ "state": state,
119
+ "display_name": display_name or None,
120
+ "handle": handle or None,
121
+ "handle_state": handle_state,
122
+ "evidence": evidence or None,
123
+ "note": note or None,
124
+ "next_check": next_check or None,
125
+ }
126
+
127
+
128
+ def open_ledger(path: Path) -> int:
129
+ path.parent.mkdir(parents=True, exist_ok=True)
130
+ # Lock the ledger inode itself so concurrent commands cannot race, and
131
+ # avoid a separate lock file or any truncating open mode.
132
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
133
+ os.fchmod(fd, 0o600)
134
+ return fd
135
+
136
+
137
+ def read_fd(fd: int) -> str:
138
+ os.lseek(fd, 0, os.SEEK_SET)
139
+ chunks = []
140
+ while True:
141
+ chunk = os.read(fd, 65536)
142
+ if not chunk:
143
+ break
144
+ chunks.append(chunk)
145
+ try:
146
+ return b"".join(chunks).decode("utf-8")
147
+ except UnicodeDecodeError as exc:
148
+ raise ReceiptError("ledger contains invalid UTF-8") from exc
149
+
150
+
151
+ def write_all(fd: int, payload: bytes) -> None:
152
+ view = memoryview(payload)
153
+ while view:
154
+ written = os.write(fd, view)
155
+ if written <= 0:
156
+ raise OSError("ledger append made no progress")
157
+ view = view[written:]
158
+
159
+
160
+ def record_receipt(path: Path, **fields: Any) -> dict[str, Any]:
161
+ fd = open_ledger(path)
162
+ try:
163
+ fcntl.flock(fd, fcntl.LOCK_EX)
164
+ records = parse_ledger(read_fd(fd))
165
+ record = make_record(existing=records, **fields)
166
+ payload = (json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n").encode()
167
+ os.lseek(fd, 0, os.SEEK_END)
168
+ write_all(fd, payload)
169
+ os.fsync(fd)
170
+ return record
171
+ finally:
172
+ # Closing releases flock even if validation or the append fails.
173
+ os.close(fd)
174
+
175
+
176
+ def read_records(path: Path) -> list[dict[str, Any]]:
177
+ try:
178
+ fd = os.open(path, os.O_RDONLY)
179
+ except FileNotFoundError:
180
+ return []
181
+ try:
182
+ fcntl.flock(fd, fcntl.LOCK_SH)
183
+ return parse_ledger(read_fd(fd))
184
+ finally:
185
+ os.close(fd)
186
+
187
+
188
+ def main(argv: list[str] | None = None) -> int:
189
+ parser = argparse.ArgumentParser(description=__doc__)
190
+ parser.add_argument("--ledger", type=Path, default=default_ledger(), help="ledger path (default: private user state directory)")
191
+ sub = parser.add_subparsers(dest="command", required=True)
192
+ add = sub.add_parser("add", help="append one status receipt")
193
+ add.add_argument("--brand", required=True)
194
+ add.add_argument("--platform", required=True)
195
+ add.add_argument("--state", required=True, choices=STATES)
196
+ add.add_argument("--display-name", default="")
197
+ add.add_argument("--handle", default="")
198
+ add.add_argument("--handle-state", default="unknown", choices=HANDLE_STATES)
199
+ add.add_argument("--evidence", default="", help="brief evidence description; do not include secrets")
200
+ add.add_argument("--note", default="", help="brief note; do not include secrets")
201
+ add.add_argument("--next-check", default="", help="required when state is submitted-uncertain")
202
+ add.add_argument("--reconcile", action="store_true", help="document new evidence resolving an uncertain submission or following a verified record")
203
+ sub.add_parser("list", help="show the latest status per brand and platform")
204
+ args = parser.parse_args(argv)
205
+ try:
206
+ if args.command == "list":
207
+ records = read_records(args.ledger)
208
+ for (brand, platform), record in sorted(latest_records(records).items()):
209
+ print(f"{brand}\t{platform}\t{record['state']}\thandle={record.get('handle') or '-'} ({record.get('handle_state', 'unknown')})")
210
+ return 0
211
+ item = record_receipt(args.ledger, brand=args.brand, platform=args.platform, state=args.state,
212
+ note=args.note, evidence=args.evidence,
213
+ display_name=args.display_name, handle=args.handle,
214
+ handle_state=args.handle_state, next_check=args.next_check,
215
+ reconcile=args.reconcile)
216
+ print(f"recorded {item['brand']} / {item['platform']}: {item['state']}")
217
+ return 0
218
+ except (ReceiptError, OSError) as exc:
219
+ print(str(exc), file=sys.stderr)
220
+ return 2
221
+
222
+
223
+ if __name__ == "__main__":
224
+ raise SystemExit(main())
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: android-device-control
3
+ Version: 0.1.0
4
+ Summary: Inspect and operate authorized Android devices through ADB.
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/lisn0/android-device-control
7
+ Project-URL: Issues, https://github.com/lisn0/android-device-control/issues
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: mcp
12
+ Requires-Dist: mcp<2,>=1.28; extra == "mcp"
13
+ Dynamic: license-file
14
+
15
+ # Android Control
16
+
17
+ A local command-line tool for inspecting and operating an authorized Android
18
+ device through ADB. Inspect the current app, select visible controls, and verify
19
+ the result after each action. The repository includes read-only device and SMS
20
+ diagnostics and a guide for manually setting up social accounts.
21
+
22
+ ## Install
23
+
24
+ Python 3.10 or newer is required. Install `adb` from
25
+ [Android SDK Platform-Tools](https://developer.android.com/tools/releases/platform-tools)
26
+ and put it on your PATH. In your Python environment, install the CLI.
27
+
28
+ ```sh
29
+ python -m pip install android-device-control
30
+ ```
31
+
32
+ The CLI uses the Python standard library. If you are working from a clone, you
33
+ can run the scripts directly with `python3 -B phone.py`, `device_info.py`,
34
+ `messages.py`, and `receipts.py`.
35
+
36
+ ## Get started
37
+
38
+ 1. Connect your test device over USB, enable USB debugging, and approve your
39
+ computer on the device. See Google's [ADB setup guide](https://developer.android.com/tools/adb)
40
+ for USB troubleshooting and wireless pairing.
41
+ 2. List devices and run a read-only check. Replace
42
+ `DEVICE_SERIAL` with the serial shown for your authorized device.
43
+
44
+ ```sh
45
+ android-control devices
46
+ android-control-device-info --device DEVICE_SERIAL
47
+ android-control foreground --device DEVICE_SERIAL
48
+ ```
49
+
50
+ Open an ordinary test screen on the device to read its accessibility tree.
51
+
52
+ ```sh
53
+ android-control snapshot --device DEVICE_SERIAL
54
+ android-control --help
55
+ ```
56
+
57
+ Use `android-control-sms --help` for SMS diagnostics and
58
+ `android-control-receipts --help` for the local setup receipt ledger.
59
+
60
+ ## Optional MCP server
61
+
62
+ An MCP client can launch Android Control locally over stdio. The server only
63
+ needs the optional MCP SDK and access to `adb` on its PATH.
64
+
65
+ ```sh
66
+ python -m pip install 'android-device-control[mcp]'
67
+ ```
68
+
69
+ For a client that uses `mcpServers` JSON, use the installed command on its PATH
70
+ or set `command` to the full path to the executable.
71
+
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "android-control": {
76
+ "command": "android-control-mcp"
77
+ }
78
+ }
79
+ }
80
+ ```
81
+
82
+ With `uvx` on the client's PATH, use `"command": "uvx"` and
83
+ `"args": ["--from", "android-device-control[mcp]", "android-control-mcp"]`.
84
+
85
+ ### Run from a checkout
86
+
87
+ Create a Python environment with the MCP SDK.
88
+
89
+ ```sh
90
+ python3 -m venv .venv
91
+ .venv/bin/python -m pip install -r requirements-mcp.txt
92
+ ```
93
+
94
+ Replace the example paths with the absolute paths to the environment's Python
95
+ executable and `android_mcp.py`.
96
+
97
+ ```json
98
+ {
99
+ "mcpServers": {
100
+ "android-control": {
101
+ "command": "/absolute/path/to/android-control/.venv/bin/python",
102
+ "args": ["/absolute/path/to/android-control/android_mcp.py"]
103
+ }
104
+ }
105
+ }
106
+ ```
107
+
108
+ ### Scope tools to a device
109
+
110
+ The default tools are `list_devices` (authorized serials and ADB states),
111
+ `foreground` (focused package and activity), and `snapshot` (guarded UI summary).
112
+ Supply the target `serial` to `foreground` and `snapshot`. To scope every tool
113
+ to one phone, append `"--device", "DEVICE_SERIAL"` to `args`, using the serial
114
+ shown by `android-control devices` or `python3 -B phone.py devices`. The scoped
115
+ read tools can then omit `serial`.
116
+
117
+ To enable `tap_label`, append `"--allow-input"` after the device arguments. The
118
+ tool acts only on that configured phone and requires a single enabled clickable
119
+ match for the exact accessibility label. Inspect the screen again after a tap
120
+ to verify its effect.
121
+
122
+ Use a trusted local client and a test screen. Snapshots can contain private app
123
+ content. Handle sensitive prompts manually and keep login, messaging, and
124
+ payment screens out of the MCP workflow.
125
+
126
+ ## Workflows
127
+
128
+ - [App navigation and UI interaction](https://github.com/lisn0/android-device-control/blob/main/docs/workflows.md)
129
+ - [Device diagnostics and SMS inspection](https://github.com/lisn0/android-device-control/blob/main/docs/device-information.md)
130
+ - [Manual social-account setup and receipts](https://github.com/lisn0/android-device-control/blob/main/docs/social-account-setup.md)
131
+ - [Design references](https://github.com/lisn0/android-device-control/blob/main/docs/research.md)
132
+
133
+ The authentication guard uses English accessibility labels and password-field
134
+ metadata. It can miss unlabeled or non-English screens. Handle passwords,
135
+ verification codes, recovery, identity, and payment prompts directly on the device.
136
+ Keep secrets out of command arguments and receipts.
137
+
138
+ ## Tests and bug reports
139
+
140
+ ```sh
141
+ python3 -B -m unittest discover -s tests -v
142
+ ```
143
+
144
+ The tests use mock ADB responses. For a bug report, provide the command, Android
145
+ and ADB versions, and a sanitized error or synthetic reproduction. Device lists,
146
+ snapshots, screenshots, and SMS output can contain serials, account identifiers,
147
+ private messages, or codes. Remove those details before sharing.
148
+
149
+ ## License
150
+
151
+ [MIT](https://github.com/lisn0/android-device-control/blob/main/LICENSE)
@@ -0,0 +1,12 @@
1
+ android_device_control/__init__.py,sha256=gBAuwYhpUtiMU1hVS_cCd1_rDUEXaPhOXEVevDIoyf0,74
2
+ android_device_control/android_mcp.py,sha256=lw-OzZn0aL5xlw3XyHd5rQkXQlTb4JFQXWao1bPYy74,4069
3
+ android_device_control/device_info.py,sha256=zWMgonWNVsKTHYy21Udrzv4A8M7_ChJqgy0mc2kgLdU,7607
4
+ android_device_control/messages.py,sha256=cpHrLuGPz8dAfReFTve7uTjRJqlkhFa8-_LithKk6BE,6660
5
+ android_device_control/phone.py,sha256=i44R12-I3JTop71bILAHJeBoW5B2IfIJGJK3saauP4w,25607
6
+ android_device_control/receipts.py,sha256=ak2MSQoVBqHkgSFcPXKPGvkljQPsX-_3EEFIh7nfxLs,10295
7
+ android_device_control-0.1.0.dist-info/licenses/LICENSE,sha256=ARF6Qhqe0I4t9XJszxd5j2SXzlQYO4GEaci-FH-qDnQ,1062
8
+ android_device_control-0.1.0.dist-info/METADATA,sha256=F-du_vQMTAti0mtXtdnWObF3K9cMSJeBQ8PcSiRqiKw,5328
9
+ android_device_control-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ android_device_control-0.1.0.dist-info/entry_points.txt,sha256=2jKCGjCDbf6LxN2O5_SihbzkbFjleA6NE-mVfZMBQrA,325
11
+ android_device_control-0.1.0.dist-info/top_level.txt,sha256=-lTfkH9tLBsHMRt2DwrXOeApha1jkYPyWTeSOwq33I0,23
12
+ android_device_control-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,6 @@
1
+ [console_scripts]
2
+ android-control = android_device_control.phone:main
3
+ android-control-device-info = android_device_control.device_info:main
4
+ android-control-mcp = android_device_control.android_mcp:main
5
+ android-control-receipts = android_device_control.receipts:main
6
+ android-control-sms = android_device_control.messages:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lisn0
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ android_device_control