phantom-phone 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.
- phantom_phone/__init__.py +0 -0
- phantom_phone/agent/__init__.py +0 -0
- phantom_phone/agent/grounder.py +145 -0
- phantom_phone/agent/loop.py +133 -0
- phantom_phone/cli.py +154 -0
- phantom_phone/doctor.py +199 -0
- phantom_phone/phone/__init__.py +0 -0
- phantom_phone/phone/adb.py +206 -0
- phantom_phone/phone/base.py +41 -0
- phantom_phone/phone/mock.py +94 -0
- phantom_phone/protocol.py +142 -0
- phantom_phone/server/__init__.py +0 -0
- phantom_phone/server/app.py +239 -0
- phantom_phone-0.1.0.dist-info/METADATA +16 -0
- phantom_phone-0.1.0.dist-info/RECORD +19 -0
- phantom_phone-0.1.0.dist-info/WHEEL +5 -0
- phantom_phone-0.1.0.dist-info/entry_points.txt +2 -0
- phantom_phone-0.1.0.dist-info/licenses/LICENSE +21 -0
- phantom_phone-0.1.0.dist-info/top_level.txt +1 -0
|
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()
|
phantom_phone/cli.py
ADDED
|
@@ -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())
|
phantom_phone/doctor.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Doctor: check adb, pairing state, and device reachability."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
CONFIG_PATH = Path.home() / ".config" / "phantom-phone" / "config.json"
|
|
10
|
+
_LEGACY_CONFIG_PATH = Path.home() / ".config" / "phonepilot" / "config.json"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_config() -> dict:
|
|
14
|
+
# read the renamed phantom-phone config first, fall back to the
|
|
15
|
+
# pre-rename phonepilot location so old installs keep working
|
|
16
|
+
for path in (CONFIG_PATH, _LEGACY_CONFIG_PATH):
|
|
17
|
+
try:
|
|
18
|
+
return json.loads(path.read_text())
|
|
19
|
+
except ValueError:
|
|
20
|
+
return {}
|
|
21
|
+
except OSError:
|
|
22
|
+
continue
|
|
23
|
+
return {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def save_config(cfg: dict) -> None:
|
|
27
|
+
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
CONFIG_PATH.write_text(json.dumps(cfg, indent=2))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
PAIRING_INSTRUCTIONS = """
|
|
32
|
+
No paired device found. One-time setup:
|
|
33
|
+
1. On the phone: Settings > Developer options > Wireless debugging > Enable
|
|
34
|
+
2. On the phone: tap "Pair device with pairing code" (note the code + port)
|
|
35
|
+
3. From this machine: adb pair <phone-ip>:<pairing-port> (enter the code)
|
|
36
|
+
4. On the phone: back on the Wireless debugging screen (note the main port)
|
|
37
|
+
5. Run: phantom-phone doctor --connect <phone-ip>:<main-port>
|
|
38
|
+
(it saves the endpoint to ~/.config/phantom-phone/config.json)
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def find_adb() -> str | None:
|
|
43
|
+
candidate = os.environ.get("PHONEPILOT_ADB")
|
|
44
|
+
if candidate and Path(candidate).exists():
|
|
45
|
+
return candidate
|
|
46
|
+
which = subprocess.run(["which", "adb"], capture_output=True, text=True)
|
|
47
|
+
if which.returncode == 0:
|
|
48
|
+
return which.stdout.strip()
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def doctor(connect: str | None = None, adb_path: str | None = None) -> int:
|
|
53
|
+
"""Run connectivity checks; returns shell exit code (0 = device ready)."""
|
|
54
|
+
adb = adb_path or find_adb()
|
|
55
|
+
if not adb:
|
|
56
|
+
print("FAIL: adb binary not found (install android platform-tools, or set PHONEPILOT_ADB)")
|
|
57
|
+
print(PAIRING_INSTRUCTIONS)
|
|
58
|
+
return 1
|
|
59
|
+
|
|
60
|
+
print(f"adb: {adb}")
|
|
61
|
+
proc = subprocess.run([adb, "devices"], capture_output=True, text=True, timeout=30)
|
|
62
|
+
devices = [ln.split()[0] for ln in proc.stdout.strip().splitlines()[1:] if ln.strip()]
|
|
63
|
+
cfg = load_config()
|
|
64
|
+
endpoint = connect or cfg.get("connect")
|
|
65
|
+
|
|
66
|
+
if not devices and endpoint:
|
|
67
|
+
print(f"trying adb connect {endpoint} ...")
|
|
68
|
+
proc2 = subprocess.run([adb, "connect", endpoint], capture_output=True, text=True, timeout=30)
|
|
69
|
+
print(proc2.stdout.strip() or proc2.stderr.strip())
|
|
70
|
+
proc = subprocess.run([adb, "devices"], capture_output=True, text=True, timeout=30)
|
|
71
|
+
devices = [ln.split()[0] for ln in proc.stdout.strip().splitlines()[1:] if ln.strip()]
|
|
72
|
+
|
|
73
|
+
if devices:
|
|
74
|
+
print(f"device(s): {', '.join(devices)}")
|
|
75
|
+
if connect:
|
|
76
|
+
cfg["connect"] = connect
|
|
77
|
+
save_config(cfg)
|
|
78
|
+
print(f"saved endpoint to {CONFIG_PATH}")
|
|
79
|
+
return 0
|
|
80
|
+
|
|
81
|
+
print("FAIL: no adb device connected")
|
|
82
|
+
print(PAIRING_INSTRUCTIONS)
|
|
83
|
+
return 1
|
|
84
|
+
|
|
85
|
+
def _list_devices(adb: str) -> list[str]:
|
|
86
|
+
proc = subprocess.run([adb, "devices"], capture_output=True, text=True, timeout=30)
|
|
87
|
+
return [ln.split()[0] for ln in proc.stdout.strip().splitlines()[1:] if ln.strip()]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def discover_mdns(adb: str) -> list[tuple[str, str]]:
|
|
91
|
+
"""Advertised wireless-debugging endpoints as (mDNS name, ip:port).
|
|
92
|
+
|
|
93
|
+
The mDNS name (adb-XXXX._adb-tls-connect._tcp) is port-independent and
|
|
94
|
+
survives phone reboots, which rotate the wireless-debugging port; adb
|
|
95
|
+
resolves the name itself, so it is the endpoint worth saving.
|
|
96
|
+
"""
|
|
97
|
+
try:
|
|
98
|
+
proc = subprocess.run([adb, "mdns", "services"], capture_output=True, text=True, timeout=30)
|
|
99
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
100
|
+
return []
|
|
101
|
+
found: list[tuple[str, str]] = []
|
|
102
|
+
for ln in (proc.stdout or "").splitlines():
|
|
103
|
+
if "_adb-tls-connect" not in ln:
|
|
104
|
+
continue
|
|
105
|
+
parts = ln.split()
|
|
106
|
+
if len(parts) >= 3:
|
|
107
|
+
found.append((parts[-2].rstrip("."), parts[-1]))
|
|
108
|
+
return found
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _try_connect(adb: str, endpoint: str) -> str:
|
|
112
|
+
"""`adb connect` and return its output; empty string means 'already connected'."""
|
|
113
|
+
proc = subprocess.run([adb, "connect", endpoint], capture_output=True, text=True, timeout=30)
|
|
114
|
+
return (proc.stdout or "") + (proc.stderr or "")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def setup(connect: str | None = None, adb_path: str | None = None) -> int:
|
|
118
|
+
"""One-command onboarding: find adb, discover the phone over mDNS,
|
|
119
|
+
connect (preferring the reboot-proof mDNS name), save the endpoint,
|
|
120
|
+
and self-test with a status + screenshot round-trip."""
|
|
121
|
+
adb = adb_path or find_adb()
|
|
122
|
+
if not adb:
|
|
123
|
+
print("FAIL: adb binary not found (install android platform-tools, or set PHONEPILOT_ADB)")
|
|
124
|
+
print(PAIRING_INSTRUCTIONS)
|
|
125
|
+
return 1
|
|
126
|
+
print(f"adb: {adb}")
|
|
127
|
+
|
|
128
|
+
endpoint = connect
|
|
129
|
+
devices = _list_devices(adb)
|
|
130
|
+
services = discover_mdns(adb)
|
|
131
|
+
|
|
132
|
+
if not devices:
|
|
133
|
+
tried = False
|
|
134
|
+
if services:
|
|
135
|
+
print(f"mDNS: {len(services)} wireless-debugging endpoint(s) advertised")
|
|
136
|
+
for name, addr in services:
|
|
137
|
+
out = _try_connect(adb, name).strip()
|
|
138
|
+
print(f"adb connect {name}: {out or 'already connected'}")
|
|
139
|
+
if not out or "connected" in out.lower():
|
|
140
|
+
endpoint = name
|
|
141
|
+
tried = True
|
|
142
|
+
break
|
|
143
|
+
out = _try_connect(adb, addr).strip()
|
|
144
|
+
print(f"adb connect {addr}: {out}")
|
|
145
|
+
if "connected" in out.lower():
|
|
146
|
+
endpoint = addr
|
|
147
|
+
tried = True
|
|
148
|
+
break
|
|
149
|
+
if not tried and endpoint:
|
|
150
|
+
out = _try_connect(adb, endpoint).strip()
|
|
151
|
+
print(f"adb connect {endpoint}: {out or 'already connected'}")
|
|
152
|
+
if out and "connected" not in out.lower():
|
|
153
|
+
endpoint = None
|
|
154
|
+
devices = _list_devices(adb)
|
|
155
|
+
elif not endpoint and services:
|
|
156
|
+
# already paired/connected (e.g. USB or an old saved endpoint):
|
|
157
|
+
# still capture the reboot-proof mDNS name for the config
|
|
158
|
+
for name, addr in services:
|
|
159
|
+
out = _try_connect(adb, name).strip()
|
|
160
|
+
if not out or "connected" in out.lower():
|
|
161
|
+
endpoint = name
|
|
162
|
+
print(f"mDNS: saved port-independent name {name}")
|
|
163
|
+
break
|
|
164
|
+
|
|
165
|
+
if not devices:
|
|
166
|
+
print("FAIL: no adb device connected")
|
|
167
|
+
print("Wireless debugging is on but nothing answered? Then pair first:")
|
|
168
|
+
print(PAIRING_INSTRUCTIONS)
|
|
169
|
+
return 1
|
|
170
|
+
print(f"device(s): {', '.join(devices)}")
|
|
171
|
+
|
|
172
|
+
cfg = load_config()
|
|
173
|
+
if endpoint:
|
|
174
|
+
cfg["connect"] = endpoint
|
|
175
|
+
save_config(cfg)
|
|
176
|
+
kind = ("port-independent mDNS name (survives phone reboots)"
|
|
177
|
+
if "._adb-tls" in endpoint else "ip:port endpoint")
|
|
178
|
+
print(f"saved {kind} -> {CONFIG_PATH}")
|
|
179
|
+
|
|
180
|
+
# self-test: status + screenshot through the real provider path
|
|
181
|
+
from phantom_phone.phone.adb import AdbProvider
|
|
182
|
+
provider = AdbProvider(serial="", adb_path=adb, connect=endpoint)
|
|
183
|
+
st = provider.status()
|
|
184
|
+
if not st.get("ok", False):
|
|
185
|
+
print(f"WARN: status check incomplete: {st.get('error') or st}")
|
|
186
|
+
else:
|
|
187
|
+
print(f"self-test: status ok (device={st.get('device')}, battery={st.get('battery_pct')}%)")
|
|
188
|
+
try:
|
|
189
|
+
png = provider.screenshot()
|
|
190
|
+
print(f"self-test: screenshot ok ({len(png)} bytes)")
|
|
191
|
+
except Exception as exc: # noqa: BLE001 — setup reports, it doesn't crash
|
|
192
|
+
print(f"WARN: screenshot self-test failed: {exc}")
|
|
193
|
+
|
|
194
|
+
print("\nSetup complete. Next steps:")
|
|
195
|
+
print(" phantom-phone snap # take a screenshot")
|
|
196
|
+
print(' phantom-phone goal "open YouTube" # autonomous loop (needs OPENROUTER_API_KEY)')
|
|
197
|
+
print(" PHANTOM_PHONE_TOKEN=<token> phantom-phone serve --host 127.0.0.1 --port 8765")
|
|
198
|
+
print(" # run the gateway as a service if you want it always-on (see docs/)")
|
|
199
|
+
return 0
|
|
File without changes
|