phantom-phone 0.1.0__tar.gz
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.
- phantom_phone-0.1.0/LICENSE +21 -0
- phantom_phone-0.1.0/PKG-INFO +16 -0
- phantom_phone-0.1.0/README.md +128 -0
- phantom_phone-0.1.0/phantom_phone/__init__.py +0 -0
- phantom_phone-0.1.0/phantom_phone/agent/__init__.py +0 -0
- phantom_phone-0.1.0/phantom_phone/agent/grounder.py +145 -0
- phantom_phone-0.1.0/phantom_phone/agent/loop.py +133 -0
- phantom_phone-0.1.0/phantom_phone/cli.py +154 -0
- phantom_phone-0.1.0/phantom_phone/doctor.py +199 -0
- phantom_phone-0.1.0/phantom_phone/phone/__init__.py +0 -0
- phantom_phone-0.1.0/phantom_phone/phone/adb.py +206 -0
- phantom_phone-0.1.0/phantom_phone/phone/base.py +41 -0
- phantom_phone-0.1.0/phantom_phone/phone/mock.py +94 -0
- phantom_phone-0.1.0/phantom_phone/protocol.py +142 -0
- phantom_phone-0.1.0/phantom_phone/server/__init__.py +0 -0
- phantom_phone-0.1.0/phantom_phone/server/app.py +239 -0
- phantom_phone-0.1.0/phantom_phone.egg-info/PKG-INFO +16 -0
- phantom_phone-0.1.0/phantom_phone.egg-info/SOURCES.txt +32 -0
- phantom_phone-0.1.0/phantom_phone.egg-info/dependency_links.txt +1 -0
- phantom_phone-0.1.0/phantom_phone.egg-info/entry_points.txt +2 -0
- phantom_phone-0.1.0/phantom_phone.egg-info/requires.txt +11 -0
- phantom_phone-0.1.0/phantom_phone.egg-info/top_level.txt +1 -0
- phantom_phone-0.1.0/pyproject.toml +23 -0
- phantom_phone-0.1.0/setup.cfg +4 -0
- phantom_phone-0.1.0/tests/test_adb_provider.py +107 -0
- phantom_phone-0.1.0/tests/test_cli.py +85 -0
- phantom_phone-0.1.0/tests/test_goal_control.py +154 -0
- phantom_phone-0.1.0/tests/test_grounder.py +72 -0
- phantom_phone-0.1.0/tests/test_loop.py +90 -0
- phantom_phone-0.1.0/tests/test_mock_provider.py +77 -0
- phantom_phone-0.1.0/tests/test_protocol.py +46 -0
- phantom_phone-0.1.0/tests/test_server.py +86 -0
- phantom_phone-0.1.0/tests/test_server_goal.py +101 -0
- phantom_phone-0.1.0/tests/test_setup.py +120 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeezGit21
|
|
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,16 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: phantom-phone
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Protocol-first framework that lets any AI agent see and drive an Android phone
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: httpx>=0.27
|
|
8
|
+
Provides-Extra: server
|
|
9
|
+
Requires-Dist: fastapi>=0.110; extra == "server"
|
|
10
|
+
Requires-Dist: uvicorn>=0.29; extra == "server"
|
|
11
|
+
Requires-Dist: pillow>=10.0; extra == "server"
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
14
|
+
Requires-Dist: fastapi>=0.110; extra == "dev"
|
|
15
|
+
Requires-Dist: uvicorn>=0.29; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# Phantom Phone
|
|
2
|
+
|
|
3
|
+
**Your AI agent, driving a real Android phone — observe, decide, act, verify.**
|
|
4
|
+
|
|
5
|
+
https://github.com/DeezGit21/phantom-phone/assets/demo.mp4
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<img src="media/architecture.png" alt="Phantom Phone architecture: your agent → gateway server → agent runtime → ADB → Android phone" width="100%">
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
An agent sets a goal; Phantom Phone captures the screen (UI tree first, vision
|
|
12
|
+
grounding when needed), decides the next step, taps/types/swipes, verifies the
|
|
13
|
+
result, and reports back — with screenshot proof. No human touches the screen.
|
|
14
|
+
|
|
15
|
+
```text
|
|
16
|
+
$ phantom-phone goal --autonomy autonomous "open YouTube and search for Hermes agent"
|
|
17
|
+
step 1 [ok] {'type': 'launch', 'params': {'package': 'com.google.android.youtube'}} — Launching YouTube.
|
|
18
|
+
step 2 [ok] {'type': 'tap', 'params': {'x': 2188, 'y': 163}} — Tapping the Search button.
|
|
19
|
+
step 3 [ok] {'type': 'text', 'params': {'text': 'Hermes agent'}} — Typing 'Hermes agent'.
|
|
20
|
+
step 4 [ok] {'type': 'tap', 'params': {'x': 1128, 'y': 264}} — Tapping the 'hermes agent' suggestion.
|
|
21
|
+
OK: YouTube has been opened and 'Hermes agent' has been searched successfully.
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
In this recorded run, the agent is told to read an incoming text and draft (not
|
|
25
|
+
send) a reply — it opens Messages, reads the thread, taps the input field, and
|
|
26
|
+
types the draft autonomously while the desktop pane mirrors every step live:
|
|
27
|
+
|
|
28
|
+
<p align="center">
|
|
29
|
+
<img src="media/still-home.png" width="30%" alt="Live phone mirror in the desktop pane">
|
|
30
|
+
<img src="media/still-typing.png" width="30%" alt="Agent typing a draft reply in Messages">
|
|
31
|
+
<img src="media/still-done.png" width="30%" alt="Goal finished: draft typed, not sent">
|
|
32
|
+
</p>
|
|
33
|
+
|
|
34
|
+
## Works with any agent — no framework required
|
|
35
|
+
|
|
36
|
+
The gateway is a plain REST server with bearer auth. Any LLM agent that can
|
|
37
|
+
make HTTP calls can drive your phone — Claude, GPT, n8n, LangGraph, a shell
|
|
38
|
+
script. The bundled perceive-act loop (Mode 1 below) is just the reference
|
|
39
|
+
implementation:
|
|
40
|
+
|
|
41
|
+
1. **Zero code** — `phantom-phone goal "..."` runs the full autonomous loop
|
|
42
|
+
with any OpenRouter vision model.
|
|
43
|
+
2. **Raw REST** — give your agent the `GET /screenshot`, `GET /ui-tree`,
|
|
44
|
+
`POST /action`, `POST /goal` tools; curl examples and an OpenAI-style tool
|
|
45
|
+
schema in [docs/INTEGRATE.md](docs/INTEGRATE.md).
|
|
46
|
+
3. **As a library** — `AgentLoop(provider, grounder)` embeds in your own
|
|
47
|
+
runtime; the loop never touches ADB directly, only the provider interface.
|
|
48
|
+
|
|
49
|
+
## Design principles
|
|
50
|
+
|
|
51
|
+
- **Protocol-first:** the phone↔backend protocol (`docs/PROTOCOL.md`) is the
|
|
52
|
+
core artifact. Any agent backend can implement it. The bundled runtime is
|
|
53
|
+
just the first reference implementation — bring your own LLM/agent.
|
|
54
|
+
- **Phone side is swappable:** v1 talks ADB (dev/enthusiast setup); the v2
|
|
55
|
+
product client is a KMP app. The brain never changes.
|
|
56
|
+
- **Per-flow autonomy:** safe flows run autonomous, risky flows supervised.
|
|
57
|
+
- **Fail-closed gateway:** every server route requires a bearer token
|
|
58
|
+
(`PHANTOM_PHONE_TOKEN`); unset token → all authed routes refuse (403).
|
|
59
|
+
- **Control mid-run:** pause, resume, or cancel a running goal at any step
|
|
60
|
+
boundary; the phone screen auto-wakes if it was asleep.
|
|
61
|
+
|
|
62
|
+
## Quickstart
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
pip install "phantom-phone[server]"
|
|
66
|
+
phantom-phone setup # ONE command: finds your phone, connects, saves, self-tests
|
|
67
|
+
phantom-phone doctor # checks adb, pairing, connectivity
|
|
68
|
+
phantom-phone snap # screenshot of the connected phone
|
|
69
|
+
phantom-phone dump # readable UI tree (labels + tap coordinates)
|
|
70
|
+
phantom-phone goal "open YouTube and search for Hermes agent" # autonomous loop (needs OPENROUTER_API_KEY)
|
|
71
|
+
phantom-phone serve --host 127.0.0.1 --port 8765 # REST gateway for your own agent
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Set `PHANTOM_PHONE_VISION_MODEL` to swap the grounding VLM (default
|
|
75
|
+
`google/gemini-3.5-flash` via OpenRouter).
|
|
76
|
+
|
|
77
|
+
## Setup & pairing
|
|
78
|
+
|
|
79
|
+
**Easiest path** — with Wireless debugging enabled on the phone:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
phantom-phone setup
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`setup` discovers the phone over mDNS, connects, **saves the port-independent
|
|
86
|
+
mDNS endpoint** (so it keeps working across phone reboots, which rotate the
|
|
87
|
+
wireless-debugging port), and self-tests with a status + screenshot round-trip.
|
|
88
|
+
Pass `--connect <ip>:<port>` if discovery can't see the phone.
|
|
89
|
+
|
|
90
|
+
**First-time pairing** (only needed once):
|
|
91
|
+
|
|
92
|
+
1. Enable Developer Options → Wireless debugging.
|
|
93
|
+
2. Tap **Pair device with pairing code**, then run
|
|
94
|
+
`adb pair <phone-ip>:<pairing-port> <code>` from this machine
|
|
95
|
+
(full walkthrough: `docs/PAIRING.md`).
|
|
96
|
+
3. `phantom-phone setup` (or `doctor --connect <phone-ip>:<main-port>`) connects
|
|
97
|
+
and saves the endpoint to `~/.config/phantom-phone/config.json`.
|
|
98
|
+
|
|
99
|
+
## Components
|
|
100
|
+
|
|
101
|
+
| Piece | Path | Role |
|
|
102
|
+
|---|---|---|
|
|
103
|
+
| Protocol models | `phantom_phone/protocol.py` | shared message types |
|
|
104
|
+
| Phone providers | `phantom_phone/phone/` | ADB + mock implementations |
|
|
105
|
+
| Gateway server | `phantom_phone/server/` | HTTP surface for any backend |
|
|
106
|
+
| Agent runtime | `phantom_phone/agent/` | perceive-act loop + VLM grounder |
|
|
107
|
+
| Wire format | `docs/PROTOCOL.md` | the core artifact (v2-compatible) |
|
|
108
|
+
|
|
109
|
+
## Security
|
|
110
|
+
|
|
111
|
+
- Bearer-token auth on every route; fails closed if the token is unset.
|
|
112
|
+
- Bind to a private interface or reverse-proxy it — don't expose the token to
|
|
113
|
+
the open internet as-is.
|
|
114
|
+
- FLAG_SECURE screens (banking, DRM) screenshot black — an Android platform
|
|
115
|
+
restriction, documented in `docs/PAIRING.md`.
|
|
116
|
+
- Supervised mode proposes every action and executes nothing.
|
|
117
|
+
|
|
118
|
+
## Status
|
|
119
|
+
|
|
120
|
+
v1 is live-tested end-to-end on a physical device (screenshot capture, UI-tree
|
|
121
|
+
grounding, taps/typing/keys, autonomous goals with verification, pause/resume/
|
|
122
|
+
cancel). See `docs/specs/` for the design. Roadmap: MCP server wrapper, Docker
|
|
123
|
+
packaging, PyPI release, event-driven triggers via MacroDroid, KMP phone
|
|
124
|
+
client, multi-app sessions.
|
|
125
|
+
|
|
126
|
+
## License
|
|
127
|
+
|
|
128
|
+
MIT — see [LICENSE](LICENSE).
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Grounder: turns observations into the next action decision.
|
|
2
|
+
|
|
3
|
+
Two implementations: FakeGrounder (scripted, for tests/offline) and
|
|
4
|
+
OpenRouterGrounder (vision model via the OpenRouter chat API).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import json
|
|
10
|
+
from abc import ABC, abstractmethod
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from phantom_phone.protocol import Action, UiTree
|
|
16
|
+
|
|
17
|
+
SYSTEM_PROMPT = """You are the decision core of a phone-automation agent.
|
|
18
|
+
You see the phone's current screen (a UI element dump and a screenshot).
|
|
19
|
+
Available actions and params:
|
|
20
|
+
tap {x, y} - tap absolute pixel coordinates
|
|
21
|
+
swipe {x1, y1, x2, y2, ms} - swipe gesture
|
|
22
|
+
text {text} - type text into the focused field
|
|
23
|
+
key {code} - code is BACK, HOME, or ENTER
|
|
24
|
+
launch {package} - launch an app by package name
|
|
25
|
+
Respond with ONLY minified JSON, no markdown:
|
|
26
|
+
{"action": {"type": "...", "params": {...}}, "done": false, "answer": "", "thought": "..."}
|
|
27
|
+
Rules:
|
|
28
|
+
- If the goal names an app, start with a launch action.
|
|
29
|
+
- Prefer tapping elements you can see in the UI dump (use their bounds' center).
|
|
30
|
+
- When the goal is achieved, set done=true and put a short summary in answer.
|
|
31
|
+
- One action per response."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Decision:
|
|
36
|
+
action: Action | None
|
|
37
|
+
done: bool
|
|
38
|
+
answer: str = ""
|
|
39
|
+
thought: str = ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class GrounderError(RuntimeError):
|
|
43
|
+
"""Raised when the vision model is unreachable or returns unusable output."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Grounder(ABC):
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def decide(self, goal: str, history: list[dict], tree: UiTree, screenshot_png: bytes) -> Decision:
|
|
49
|
+
"""Decide the next action given the goal, prior steps, and observation."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class FakeGrounder(Grounder):
|
|
53
|
+
"""Returns scripted decisions in order; raises IndexError when exhausted."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, decisions: list[Decision]):
|
|
56
|
+
self.decisions = list(decisions)
|
|
57
|
+
self.calls: list[dict] = []
|
|
58
|
+
|
|
59
|
+
def decide(self, goal, history, tree, screenshot_png):
|
|
60
|
+
self.calls.append({"goal": goal, "history": list(history), "activity": tree.activity})
|
|
61
|
+
return self.decisions.pop(0)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class OpenRouterGrounder(Grounder):
|
|
65
|
+
def __init__(self, model: str, api_key: str, base_url: str = "https://openrouter.ai/api/v1"):
|
|
66
|
+
self.model = model
|
|
67
|
+
self.api_key = api_key
|
|
68
|
+
self.base_url = base_url.rstrip("/")
|
|
69
|
+
|
|
70
|
+
def _post(self, url: str, headers: dict, payload: dict) -> httpx.Response:
|
|
71
|
+
"""POST helper; `_client` injection point for tests (MockTransport)."""
|
|
72
|
+
client = getattr(self, "_client", None)
|
|
73
|
+
if client is not None:
|
|
74
|
+
return client.post(url, headers=headers, json=payload)
|
|
75
|
+
return httpx.post(url, headers=headers, json=payload, timeout=60)
|
|
76
|
+
|
|
77
|
+
def decide(self, goal, history, tree, screenshot_png):
|
|
78
|
+
b64 = base64.b64encode(screenshot_png).decode()
|
|
79
|
+
messages = [
|
|
80
|
+
{"role": "system", "content": SYSTEM_PROMPT},
|
|
81
|
+
{
|
|
82
|
+
"role": "user",
|
|
83
|
+
"content": [
|
|
84
|
+
{"type": "text", "text": _context_text(goal, history, tree)},
|
|
85
|
+
{
|
|
86
|
+
"type": "image_url",
|
|
87
|
+
"image_url": {"url": f"data:image/png;base64,{b64}"},
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
},
|
|
91
|
+
]
|
|
92
|
+
try:
|
|
93
|
+
resp = self._post(
|
|
94
|
+
f"{self.base_url}/chat/completions",
|
|
95
|
+
{"Authorization": f"Bearer {self.api_key}"},
|
|
96
|
+
{"model": self.model, "messages": messages, "max_tokens": 2000},
|
|
97
|
+
)
|
|
98
|
+
resp.raise_for_status()
|
|
99
|
+
except httpx.HTTPError as exc:
|
|
100
|
+
raise GrounderError(f"vision model unreachable: {exc}") from exc
|
|
101
|
+
try:
|
|
102
|
+
content = resp.json()["choices"][0]["message"]["content"]
|
|
103
|
+
except (KeyError, IndexError, ValueError) as exc:
|
|
104
|
+
raise GrounderError(f"unexpected model response shape: {exc}") from exc
|
|
105
|
+
return _parse_decision(content)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _context_text(goal: str, history: list[dict], tree: UiTree) -> str:
|
|
109
|
+
lines = [f"GOAL: {goal}", "", "PRIOR STEPS:"]
|
|
110
|
+
if history:
|
|
111
|
+
for h in history:
|
|
112
|
+
lines.append(f"- {h}")
|
|
113
|
+
else:
|
|
114
|
+
lines.append("- (none yet)")
|
|
115
|
+
lines += ["", "CURRENT SCREEN UI ELEMENTS:"]
|
|
116
|
+
for e in tree.elements:
|
|
117
|
+
l, t, r, b = e.bounds
|
|
118
|
+
label = e.text or e.content_desc or e.cls
|
|
119
|
+
lines.append(f"- id={e.id} '{label}' clickable={e.clickable} bounds=[{l},{t}][{r},{b}]")
|
|
120
|
+
if tree.activity:
|
|
121
|
+
lines.append(f"Activity: {tree.activity}")
|
|
122
|
+
return "\n".join(lines)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _parse_decision(content: str) -> Decision:
|
|
126
|
+
text = (content or "").strip()
|
|
127
|
+
if text.startswith("```"):
|
|
128
|
+
text = text.strip("`")
|
|
129
|
+
if text.startswith("json"):
|
|
130
|
+
text = text[4:]
|
|
131
|
+
text = text.strip()
|
|
132
|
+
try:
|
|
133
|
+
start, end = text.index("{"), text.rindex("}")
|
|
134
|
+
payload = json.loads(text[start : end + 1])
|
|
135
|
+
except (ValueError, json.JSONDecodeError) as exc:
|
|
136
|
+
raise GrounderError(f"unparseable model output: {content[:200]!r}") from exc
|
|
137
|
+
action = None
|
|
138
|
+
if isinstance(payload.get("action"), dict) and payload["action"].get("type"):
|
|
139
|
+
action = Action.from_dict(payload["action"])
|
|
140
|
+
return Decision(
|
|
141
|
+
action=action,
|
|
142
|
+
done=bool(payload.get("done")),
|
|
143
|
+
answer=str(payload.get("answer", "")),
|
|
144
|
+
thought=str(payload.get("thought", "")),
|
|
145
|
+
)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Perceive-act agent loop.
|
|
2
|
+
|
|
3
|
+
Consumes only the PhoneProvider interface (never adb directly) and a Grounder.
|
|
4
|
+
Every action is followed by a verification observation; repeated failures and
|
|
5
|
+
grounder outages end the goal with ok=False instead of crashing.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
from phantom_phone.agent.grounder import Decision, Grounder, GrounderError
|
|
12
|
+
from phantom_phone.phone.base import PhoneProvider
|
|
13
|
+
from phantom_phone.protocol import Action, ActionResult
|
|
14
|
+
|
|
15
|
+
MAX_CONSECUTIVE_FAILURES = 3
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class StepLog:
|
|
20
|
+
step: int
|
|
21
|
+
action: Action | None
|
|
22
|
+
ok: bool
|
|
23
|
+
thought: str
|
|
24
|
+
activity_before: str
|
|
25
|
+
activity_after: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class GoalResult:
|
|
30
|
+
ok: bool
|
|
31
|
+
answer: str
|
|
32
|
+
steps: list[StepLog] = field(default_factory=list)
|
|
33
|
+
final_screenshot: bytes = b""
|
|
34
|
+
history: list[str] = field(default_factory=list)
|
|
35
|
+
paused: bool = False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AgentLoop:
|
|
39
|
+
def __init__(self, provider: PhoneProvider, grounder: Grounder):
|
|
40
|
+
self.provider = provider
|
|
41
|
+
self.grounder = grounder
|
|
42
|
+
|
|
43
|
+
def run(self, goal: str, max_steps: int = 15, autonomy: str = "autonomous",
|
|
44
|
+
on_step=None, history: list[str] | None = None, steps_done: int = 0,
|
|
45
|
+
control=None) -> GoalResult:
|
|
46
|
+
"""Run the perceive-act loop.
|
|
47
|
+
|
|
48
|
+
``history``/``steps_done`` let a paused goal resume where it left off.
|
|
49
|
+
``control`` is an optional callable polled at each step boundary,
|
|
50
|
+
returning None to continue, "pause" to suspend, or "cancel" to abort.
|
|
51
|
+
"""
|
|
52
|
+
history = list(history or [])
|
|
53
|
+
steps: list[StepLog] = []
|
|
54
|
+
consecutive_failures = 0
|
|
55
|
+
final_screenshot = b""
|
|
56
|
+
|
|
57
|
+
for step in range(steps_done + 1, max_steps + 1):
|
|
58
|
+
if control is not None:
|
|
59
|
+
cmd = control()
|
|
60
|
+
if cmd == "cancel":
|
|
61
|
+
return GoalResult(ok=False, answer=f"cancelled by user after step {step - 1}",
|
|
62
|
+
steps=steps, history=history,
|
|
63
|
+
final_screenshot=self.provider.screenshot())
|
|
64
|
+
if cmd == "pause":
|
|
65
|
+
return GoalResult(ok=False, answer=f"paused after step {step - 1}",
|
|
66
|
+
steps=steps, history=history, paused=True,
|
|
67
|
+
final_screenshot=self.provider.screenshot())
|
|
68
|
+
if self.provider.ensure_awake():
|
|
69
|
+
history.append("step 0: screen was off; device woken before observing")
|
|
70
|
+
tree = self.provider.ui_tree()
|
|
71
|
+
screenshot = self.provider.screenshot()
|
|
72
|
+
activity_before = tree.activity or self.provider.status().get("activity", "")
|
|
73
|
+
try:
|
|
74
|
+
decision = self.grounder.decide(goal, history, tree, screenshot)
|
|
75
|
+
except GrounderError as exc:
|
|
76
|
+
return GoalResult(ok=False, answer=f"grounder failure: {exc}",
|
|
77
|
+
steps=steps, history=history,
|
|
78
|
+
final_screenshot=self.provider.screenshot())
|
|
79
|
+
|
|
80
|
+
if decision.done:
|
|
81
|
+
return GoalResult(ok=True, answer=decision.answer or "goal achieved",
|
|
82
|
+
steps=steps, history=history,
|
|
83
|
+
final_screenshot=screenshot)
|
|
84
|
+
|
|
85
|
+
if decision.action is None:
|
|
86
|
+
return GoalResult(ok=False, answer="model produced no action",
|
|
87
|
+
steps=steps, history=history,
|
|
88
|
+
final_screenshot=screenshot)
|
|
89
|
+
|
|
90
|
+
if autonomy == "supervised":
|
|
91
|
+
steps.append(StepLog(step=step, action=decision.action, ok=False,
|
|
92
|
+
thought="awaiting-approval",
|
|
93
|
+
activity_before=activity_before, activity_after=activity_before))
|
|
94
|
+
return GoalResult(ok=False, answer=f"supervised: approval needed for {decision.action.to_dict()}",
|
|
95
|
+
steps=steps, history=history,
|
|
96
|
+
final_screenshot=screenshot)
|
|
97
|
+
|
|
98
|
+
result = self.provider.execute(decision.action)
|
|
99
|
+
activity_after = self.provider.status().get("activity", "")
|
|
100
|
+
steps.append(StepLog(step=step, action=decision.action, ok=result.ok,
|
|
101
|
+
thought=decision.thought,
|
|
102
|
+
activity_before=activity_before, activity_after=activity_after))
|
|
103
|
+
if on_step:
|
|
104
|
+
on_step(steps[-1])
|
|
105
|
+
history.append(f"step {step}: {decision.action.to_dict()} -> "
|
|
106
|
+
f"{'ok' if result.ok else 'FAILED: ' + result.detail}")
|
|
107
|
+
|
|
108
|
+
if not result.ok:
|
|
109
|
+
consecutive_failures += 1
|
|
110
|
+
if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:
|
|
111
|
+
return GoalResult(
|
|
112
|
+
ok=False,
|
|
113
|
+
answer=f"stuck after {consecutive_failures} consecutive failed actions; "
|
|
114
|
+
f"last failure: {result.detail}",
|
|
115
|
+
steps=steps, history=history,
|
|
116
|
+
final_screenshot=self.provider.screenshot(),
|
|
117
|
+
)
|
|
118
|
+
else:
|
|
119
|
+
consecutive_failures = 0
|
|
120
|
+
|
|
121
|
+
return GoalResult(ok=False, answer=f"step budget exhausted after {max_steps} steps",
|
|
122
|
+
steps=steps, history=history,
|
|
123
|
+
final_screenshot=self.provider.screenshot())
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def run_goal(provider: PhoneProvider, grounder: Grounder, goal: str,
|
|
127
|
+
max_steps: int = 15, autonomy: str = "autonomous", on_step=None) -> GoalResult:
|
|
128
|
+
"""Convenience one-shot entry point."""
|
|
129
|
+
loop = AgentLoop(provider, grounder)
|
|
130
|
+
try:
|
|
131
|
+
return loop.run(goal, max_steps=max_steps, autonomy=autonomy, on_step=on_step)
|
|
132
|
+
finally:
|
|
133
|
+
provider.close()
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Phantom Phone CLI: doctor, snap, dump, tap, text, key, app, goal."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from phantom_phone.doctor import doctor as run_doctor, load_config
|
|
10
|
+
from phantom_phone.phone.adb import AdbProvider
|
|
11
|
+
from phantom_phone.phone.base import PhoneProvider
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def build_provider(args: argparse.Namespace) -> PhoneProvider:
|
|
15
|
+
connect = getattr(args, "connect", None)
|
|
16
|
+
serial = getattr(args, "serial", None) or ""
|
|
17
|
+
if not connect and not serial:
|
|
18
|
+
# fall back to the endpoint saved by `doctor --connect`
|
|
19
|
+
connect = load_config().get("connect")
|
|
20
|
+
return AdbProvider(serial=serial, adb_path=args.adb, connect=connect)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def cmd_doctor(args) -> int:
|
|
24
|
+
return run_doctor(connect=args.connect, adb_path=args.adb)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def cmd_setup(args) -> int:
|
|
28
|
+
from phantom_phone.doctor import setup as run_setup
|
|
29
|
+
return run_setup(connect=args.connect, adb_path=args.adb)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def cmd_snap(args) -> int:
|
|
33
|
+
png = build_provider(args).screenshot()
|
|
34
|
+
path = f"screenshot-{int(time.time())}.png"
|
|
35
|
+
with open(path, "wb") as fh:
|
|
36
|
+
fh.write(png)
|
|
37
|
+
print(path)
|
|
38
|
+
return 0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cmd_dump(args) -> int:
|
|
42
|
+
tree = build_provider(args).ui_tree()
|
|
43
|
+
print(f"activity: {tree.activity}")
|
|
44
|
+
for e in tree.elements:
|
|
45
|
+
l, t, r, b = e.bounds
|
|
46
|
+
label = e.text or e.content_desc or e.cls
|
|
47
|
+
print(f" id={e.id} '{label}' clickable={e.clickable} bounds=[{l},{t}][{r},{b}]")
|
|
48
|
+
return 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def cmd_action(args) -> int:
|
|
52
|
+
from phantom_phone.protocol import Action
|
|
53
|
+
|
|
54
|
+
if args.command == "tap":
|
|
55
|
+
act = Action.tap(args.x, args.y)
|
|
56
|
+
elif args.command == "text":
|
|
57
|
+
act = Action.text(args.value)
|
|
58
|
+
elif args.command == "key":
|
|
59
|
+
act = Action.key(args.value)
|
|
60
|
+
elif args.command == "app":
|
|
61
|
+
act = Action.launch(args.value)
|
|
62
|
+
else:
|
|
63
|
+
print(f"unknown command: {args.command}")
|
|
64
|
+
return 2
|
|
65
|
+
result = build_provider(args).execute(act)
|
|
66
|
+
print(("OK: " if result.ok else "FAIL: ") + result.detail)
|
|
67
|
+
return 0 if result.ok else 1
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cmd_serve(args) -> int:
|
|
71
|
+
import uvicorn
|
|
72
|
+
from phantom_phone.server.app import create_app
|
|
73
|
+
|
|
74
|
+
token = os.environ.get("PHANTOM_PHONE_TOKEN")
|
|
75
|
+
if not token:
|
|
76
|
+
print("FAIL: PHANTOM_PHONE_TOKEN not set — refusing to serve unauthenticated")
|
|
77
|
+
return 1
|
|
78
|
+
provider = build_provider(args)
|
|
79
|
+
app = create_app(provider, token)
|
|
80
|
+
uvicorn.run(app, host=args.host, port=args.port, log_level="warning")
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cmd_goal(args) -> int:
|
|
85
|
+
from phantom_phone.agent.grounder import OpenRouterGrounder
|
|
86
|
+
from phantom_phone.agent.loop import run_goal
|
|
87
|
+
|
|
88
|
+
api_key = os.environ.get("OPENROUTER_API_KEY")
|
|
89
|
+
if not api_key:
|
|
90
|
+
print("FAIL: OPENROUTER_API_KEY not set")
|
|
91
|
+
return 1
|
|
92
|
+
model = os.environ.get("PHONEPILOT_VISION_MODEL", "google/gemini-3.5-flash")
|
|
93
|
+
grounder = OpenRouterGrounder(model=model, api_key=api_key)
|
|
94
|
+
result = run_goal(build_provider(args), grounder, args.goal,
|
|
95
|
+
max_steps=args.max_steps, autonomy=args.autonomy)
|
|
96
|
+
for s in result.steps:
|
|
97
|
+
mark = "ok" if s.ok else "FAIL"
|
|
98
|
+
act = s.action.to_dict() if s.action else "(none)"
|
|
99
|
+
print(f" step {s.step} [{mark}] {act} — {s.thought}")
|
|
100
|
+
if result.final_screenshot:
|
|
101
|
+
path = f"goal-final-{int(time.time())}.png"
|
|
102
|
+
with open(path, "wb") as fh:
|
|
103
|
+
fh.write(result.final_screenshot)
|
|
104
|
+
print(f"final screenshot: {path}")
|
|
105
|
+
print(("OK: " if result.ok else "FAIL: ") + result.answer)
|
|
106
|
+
return 0 if result.ok else 1
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main(argv: list[str] | None = None) -> int:
|
|
110
|
+
parser = argparse.ArgumentParser(prog="phantom-phone", description="Drive an Android phone for AI agents")
|
|
111
|
+
parser.add_argument("--adb", default=os.environ.get("PHONEPILOT_ADB", "adb"))
|
|
112
|
+
parser.add_argument("--connect", default=os.environ.get("PHONEPILOT_CONNECT"))
|
|
113
|
+
parser.add_argument("--serial", default=os.environ.get("PHONEPILOT_SERIAL"))
|
|
114
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
115
|
+
|
|
116
|
+
p_setup = sub.add_parser("setup", help="one-command onboarding: discover, connect, save, self-test")
|
|
117
|
+
p_setup.add_argument("--connect", default=None, help="phone ip:port (otherwise discovered via mDNS)")
|
|
118
|
+
p_setup.set_defaults(func=cmd_setup)
|
|
119
|
+
|
|
120
|
+
sub.add_parser("doctor").set_defaults(func=cmd_doctor)
|
|
121
|
+
sub.add_parser("snap").set_defaults(func=cmd_snap)
|
|
122
|
+
sub.add_parser("dump").set_defaults(func=cmd_dump)
|
|
123
|
+
|
|
124
|
+
p_tap = sub.add_parser("tap")
|
|
125
|
+
p_tap.add_argument("x", type=int)
|
|
126
|
+
p_tap.add_argument("y", type=int)
|
|
127
|
+
p_tap.set_defaults(func=cmd_action)
|
|
128
|
+
|
|
129
|
+
for name, dest in (("text", "value"), ("key", "value"), ("app", "value")):
|
|
130
|
+
p = sub.add_parser(name)
|
|
131
|
+
p.add_argument(dest)
|
|
132
|
+
p.set_defaults(func=cmd_action)
|
|
133
|
+
|
|
134
|
+
p_goal = sub.add_parser("goal")
|
|
135
|
+
p_goal.add_argument("goal")
|
|
136
|
+
p_goal.add_argument("--max-steps", type=int, default=15)
|
|
137
|
+
p_goal.add_argument("--autonomy", choices=["autonomous", "supervised"], default="autonomous")
|
|
138
|
+
p_goal.set_defaults(func=cmd_goal)
|
|
139
|
+
|
|
140
|
+
p_serve = sub.add_parser("serve")
|
|
141
|
+
p_serve.add_argument("--host", default="127.0.0.1")
|
|
142
|
+
p_serve.add_argument("--port", type=int, default=8765)
|
|
143
|
+
p_serve.set_defaults(func=cmd_serve)
|
|
144
|
+
|
|
145
|
+
args = parser.parse_args(argv)
|
|
146
|
+
try:
|
|
147
|
+
return args.func(args)
|
|
148
|
+
except (ConnectionError, RuntimeError) as exc:
|
|
149
|
+
print(f"FAIL: {exc}")
|
|
150
|
+
return 1
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
if __name__ == "__main__":
|
|
154
|
+
sys.exit(main())
|