let your agent control your phone
phone-harness v0: iPhone control via iPhone Mirroring
ShawnPana22abed41df1c
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..201ffa5--- /dev/null+++ b/.gitignore@@ -0,0 +1,5 @@+__pycache__/+*.pyc+dist/+*.egg-info/+.venv/diff --git a/README.md b/README.mdnew file mode 100644index 0000000..07c4e74--- /dev/null+++ b/README.md@@ -0,0 +1,82 @@+# Phone Harness π±++Connect an LLM directly to a real iPhone through macOS iPhone Mirroring β a+thin, editable harness in the spirit of+prior work.++No jailbreak, no Xcode, no WebDriverAgent. The Mac's mirroring window is the+transport: `screencapture` + Vision-framework OCR for eyes, HID-level CGEvents+for hands. The agent writes what's missing during execution in+`agent-workspace/agent_helpers.py`.++```+ β agent: wants to open Weather+ β+ β ocr() β "Weather" at (400, 468)+ β+ β tap(400, 468) β wait_stable() β ocr() confirms forecast+ β done+```++## Why this works++iPhone Mirroring renders the phone as a Mac window and forwards real mouse and+keyboard input as touches. That gives an agent everything it needs:++- **See** β capture just the mirroring window (`screencapture -l`), OCR it+ with Apple's Vision framework: every visible string with a tap-ready+ coordinate. The poor man's DOM.+- **Act** β CGEvents posted at the HID tap: taps, long-presses, drags+ (swipes), scroll gestures, unicode typing, and the app's own shortcuts+ (Cmd+1 Home, Cmd+2 App Switcher, Cmd+3 Spotlight).+- **Verify** β screenshot again. No DOM means the capture is the ground truth.++Things that do NOT work, learned the hard way: AppleScript `click at`+(silently ignored β the window is a video stream with no accessibility tree),+and input while the window isn't frontmost (swallowed).++## Setup++Read [install.md](install.md). Short version: pair iPhone Mirroring once,+grant the terminal Accessibility + Screen Recording, then:++```bash+./phone-harness --doctor+```++## Usage++```bash+./phone-harness <<'PY'+open_app("Notes")+tap_text("New Note")+type_text("hello from the harness")+print([o["text"] for o in ocr()][:10])+PY+```++Day-to-day workflow lives in [SKILL.md](SKILL.md) β register it as an agent+skill with `./phone-harness skill`.++## Architecture++- `SKILL.md` β day-to-day usage (the agent-facing product surface)+- `install.md` β permissions bootstrap and troubleshooting+- `src/phone_harness/` β protected core (~500 lines):+ - `mirror.py` β window discovery, focus, capture, CGEvent input+ - `ocr.py` β Vision-framework text recognition β screen-point boxes+ - `helpers.py` β the primitives pre-imported into scripts+ - `admin.py` β `--doctor`+ - `run.py` β the CLI (`exec` stdin with helpers in scope)+- `agent-workspace/agent_helpers.py` β helper code the agent edits; auto-+ loaded into every script's namespace++The mirror transport is stateless (window bounds and captures are re-queried+per call), so there is no daemon β every invocation is self-contained.++## Limits++- One phone, one session; unlocking the physical phone pauses mirroring.+- No multi-touch (no pinch), no camera/Face ID flows, DRM video renders black.+- OCR sees text, not semantics β unlabeled icons need a screenshot + a+ vision-capable model.diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..8b8a4d8--- /dev/null+++ b/SKILL.md@@ -0,0 +1,76 @@+---+name: phone-harness+description: "Control the user's iPhone through the Mac's iPhone Mirroring window: open apps, tap, type, swipe, read the screen."+---++# phone-harness++Direct iPhone control via the iPhone Mirroring app β screenshots + Vision OCR+for eyes, HID-level CGEvents for hands. For task-specific edits, use+`agent-workspace/agent_helpers.py`. For setup or permission problems, read+`install.md`.++## When Not to Use++If the task is doable on the Mac or the web β a website, an API, an app with a+web equivalent β do it there and leave the phone alone. Use phone-harness only+when the task genuinely needs the phone: iOS-only apps, things tied to the+user's phone number or 2FA, testing how something looks on the phone.++## Usage++```bash+phone-harness <<'PY'+print(screen_info())+PY+```++- Invoke as `phone-harness`. Use heredocs for multi-line commands.+- Helpers are pre-imported. All coordinates are global screen points.+- `ensure_mirroring()` launches and focuses the window; input helpers focus it+ automatically before posting events.++## Screen Workflow++- Prefer `ocr()` over eyeballing screenshots: every visible string comes back+ with a tap-ready center point β `[{text, confidence, x, y, w, h}]`. Filter+ in Python before printing.+- Tap by label: `tap_text("Weather")`. On failure it raises with what IS+ visible, so read the exception before retrying.+- Icons without labels: `screenshot()`, view the image, compute the point+ (image px Γ· scale + window origin β `screen_info()` has both sizes), then+ `tap(x, y)`.+- **Verify after every action**: `wait_stable()` then `ocr()`/`screenshot()`.+ There is no DOM to assert against; the capture is the ground truth.+- Navigation: `home()`, `app_switcher()`, `open_app("Notes")` (Spotlight),+ `swipe("up")`, `scroll()`, `type_text("...")`, `press("return")`,+ `long_press(x, y)`.+- Raw Quartz is the escape hatch: `import Quartz` in your script for anything+ the helpers don't cover.++## Consent++This is the user's real phone. Stop and ask before anything outward-facing or+hard to reverse: sending a message, posting, purchasing, deleting, changing+settings. Navigating and reading for the user's own task is fine, but don't+linger in personal content (Messages, Photos, Mail) beyond what the task needs.++## Gotchas++- **Unfocused input is swallowed silently.** The window must be frontmost;+ helpers call `activate()` but if a click steals focus mid-task, re-activate.+- **The window is a video stream.** macOS accessibility sees nothing inside+ it; AppleScript `click at` fails silently. Only HID-level CGEvents work.+- **The window moves.** Never cache coordinates across calls; `ocr()` and+ `swipe()` re-query bounds every time.+- **Unlocking the physical phone pauses the session.** The window then shows a+ resume interstitial β `ocr()` will show its text; tap through it or ask the+ user to lock the phone.+- **`type_text` needs an iOS text field focused first** β tap the field, wait+ for the keyboard, then type.+- **Home-Screen labels are not tap targets.** `tap_text("Weather")` hits the+ label and nothing happens; the icon is ~35 points above it. Use+ `tap_icon("Weather")` (agent helper) on the Home Screen; `tap_text` works+ fine for in-app buttons and list rows.+- Mouse taps map to touches 1:1, but there is no multi-touch: no pinch, no+ two-finger gestures.diff --git a/agent-workspace/agent_helpers.py b/agent-workspace/agent_helpers.pynew file mode 100644index 0000000..9c896f4--- /dev/null+++ b/agent-workspace/agent_helpers.py@@ -0,0 +1,22 @@+"""Agent-editable phone helpers.++Add task-specific primitives here. Core helpers from phone_harness.helpers+load this file at import time; anything defined here is available in+phone-harness scripts alongside the core helpers.+"""+++def tap_icon(label, index=0):+ """Tap a Home-Screen app icon by its label.++ Learned: tapping the label text itself does NOT launch the app in the+ mirrored Home Screen β the tappable icon is ~35 points above the label.+ Verified against Weather (label tap: no-op; icon tap: launches).+ """+ from phone_harness.helpers import find_text, tap+ hits = find_text(label)+ if not hits:+ raise RuntimeError(f"no Home-Screen label matching {label!r}")+ h = hits[index]+ tap(h["x"], h["y"] - 35)+ return hdiff --git a/install.md b/install.mdnew file mode 100644index 0000000..6667159--- /dev/null+++ b/install.md@@ -0,0 +1,49 @@+# phone-harness install++Use once. For phone work, read `SKILL.md`.++## Requirements++- macOS Sequoia+ with iPhone Mirroring paired to the phone (open the app once+ manually to pair β pairing prompts need the physical phone).+- Python 3.12+ with pyobjc (`pip install pyobjc-framework-Quartz+ pyobjc-framework-Vision pyobjc-framework-AppKit`).+- The terminal app needs two permissions in System Settings > Privacy &+ Security. **The toggles require the user:**+ - **Accessibility** β taps and keystrokes. Takes effect immediately.+ - **Screen Recording** β seeing the phone. Takes effect after the terminal+ app restarts.++Open the panes directly:++```bash+open "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"+open "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"+```++## Fast Path++```bash+cd ~/Projects/phone-harness+./phone-harness --doctor+./phone-harness <<'PY'+print(screen_info())+PY+```++If `screen_info()` prints window bounds, you're done.++## If It Fails++`--doctor` walks the ladder in order: pyobjc β Accessibility β Screen+Recording β app installed β app running β window found β capture works β OCR+works. Fix the first FAIL; later checks depend on earlier ones.++Common cases:++- **Capture is blank/black**: Screen Recording was granted but the terminal+ hasn't restarted since.+- **Window not found**: the phone isn't paired, isn't in range, or iPhone+ Mirroring shows a connect screen β open the app manually once.+- **Taps do nothing**: Accessibility missing, or another window stole focus β+ events land only when the mirroring window is frontmost.diff --git a/phone-harness b/phone-harnessnew file mode 100755index 0000000..05f2ae0--- /dev/null+++ b/phone-harness@@ -0,0 +1,4 @@+#!/bin/sh+# Dev launcher: run the working tree without installing.+DIR="$(cd "$(dirname "$0")" && pwd)"+PYTHONPATH="$DIR/src" exec python3 -m phone_harness.run "$@"diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..27a7284--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,21 @@+[project]+name = "phone-harness"+version = "0.1.0"+description = "Control a real iPhone through macOS iPhone Mirroring: OCR eyes, CGEvent hands"+requires-python = ">=3.10"+dependencies = [+ "pyobjc-framework-Quartz",+ "pyobjc-framework-Vision",+ "pyobjc-framework-AppKit",+ "pyobjc-framework-ApplicationServices",+]++[project.scripts]+phone-harness = "phone_harness.run:main"++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["src/phone_harness"]diff --git a/src/phone_harness/__init__.py b/src/phone_harness/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/src/phone_harness/admin.py b/src/phone_harness/admin.pynew file mode 100644index 0000000..2f6ac68--- /dev/null+++ b/src/phone_harness/admin.py@@ -0,0 +1,66 @@+"""Diagnostics: `phone-harness --doctor` walks the permission/session ladder."""+import os, subprocess, sys, tempfile+from pathlib import Path+++def _check(label, ok, hint=""):+ mark = "PASS" if ok else "FAIL"+ print(f" [{mark}] {label}" + (f" β {hint}" if not ok and hint else ""))+ return ok+++def run_doctor():+ print("phone-harness doctor\n")+ ok = True++ try:+ import Quartz, Vision, AppKit # noqa: F401+ ok &= _check("pyobjc frameworks (Quartz, Vision, AppKit)", True)+ except ImportError as e:+ _check("pyobjc frameworks", False,+ f"pip install pyobjc-framework-Quartz pyobjc-framework-Vision ({e})")+ return 1++ from ApplicationServices import AXIsProcessTrusted+ ok &= _check(+ "Accessibility permission (taps & keystrokes)", AXIsProcessTrusted(),+ "System Settings > Privacy & Security > Accessibility: enable your terminal")++ import Quartz as Q+ ok &= _check(+ "Screen Recording permission (seeing the phone)",+ bool(Q.CGPreflightScreenCaptureAccess()),+ "System Settings > Privacy & Security > Screen Recording: enable your terminal")++ from . import mirror+ ok &= _check(f"{mirror.APP_NAME} installed", Path(mirror.APP_PATH).exists(),+ "requires macOS Sequoia+ with a paired iPhone")++ running = mirror.running_app() is not None+ _check(f"{mirror.APP_NAME} running", running,+ "will auto-launch on first use β not fatal")++ win = mirror.find_window()+ _check("mirroring window found", win is not None,+ "open iPhone Mirroring once manually to pair the phone")++ if win:+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ path = f.name+ try:+ subprocess.run(+ ["screencapture", "-x", "-o", "-l", str(win["id"]), path],+ check=True)+ size = os.path.getsize(path)+ ok &= _check(f"window capture works ({size} bytes)", size > 20_000,+ "capture is blank β Screen Recording permission "+ "needs a terminal restart to take effect")+ if size > 20_000:+ from . import ocr+ n = len(ocr.recognize(path, win))+ _check(f"Vision OCR works ({n} text boxes)", True)+ finally:+ os.unlink(path)++ print("\nall clear" if ok else "\nfix the FAILs above, then re-run")+ return 0 if ok else 1diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pynew file mode 100644index 0000000..ff0c82f--- /dev/null+++ b/src/phone_harness/helpers.py@@ -0,0 +1,159 @@+"""Phone control via iPhone Mirroring.++Core helpers live here. Agent-editable helpers live in+PH_AGENT_WORKSPACE/agent_helpers.py (defaults to <repo>/agent-workspace).+Raw Quartz is always available: `import Quartz` in your script for anything+these helpers don't cover.+"""+import hashlib, importlib.util, os, time+from pathlib import Path++from . import mirror, ocr as _ocr+from .mirror import ( # re-exported input primitives+ tap, long_press, drag, press, type_text, activate, find_window,+)++CORE_DIR = Path(__file__).resolve().parent+REPO_ROOT = CORE_DIR.parent.parent+AGENT_WORKSPACE = Path(+ os.environ.get("PH_AGENT_WORKSPACE", REPO_ROOT / "agent-workspace"))+++# --- session / state ---++def ensure_mirroring():+ """Launch + focus iPhone Mirroring; return window bounds {x, y, w, h, id}."""+ win = mirror.ensure_window()+ mirror.activate()+ return win+++def screen_info():+ """{window, frontmost, img_px} β bounds in screen points, capture size in px."""+ path, win = mirror.capture()+ w, h = _ocr.image_size(path)+ return {"window": win, "frontmost": mirror.is_frontmost(), "img_px": [w, h]}+++def screenshot(path=None):+ """Capture the phone window to a PNG and return its path. View it to see+ the phone; combine with ocr() for coordinates."""+ p, _ = mirror.capture(path)+ return p+++# --- reading the screen ---++def ocr(min_confidence=0.3):+ """All visible text with tap-ready screen-point centers:+ [{text, confidence, x, y, w, h}]. This is the element tree β prefer it+ over eyeballing screenshots for anything with a text label."""+ path, win = mirror.capture()+ return [o for o in _ocr.recognize(path, win)+ if o["confidence"] >= min_confidence]+++def find_text(query, exact=False):+ """OCR results matching query (case-insensitive substring by default)."""+ q = query.lower()+ return [o for o in ocr()+ if (o["text"].lower() == q if exact else q in o["text"].lower())]+++def tap_text(query, index=0, exact=False):+ """Find text on screen and tap its center. Raises with what IS visible on+ failure, so the next step is informed."""+ hits = find_text(query, exact=exact)+ if not hits:+ visible = [o["text"] for o in ocr()][:30]+ raise RuntimeError(f"no visible text matches {query!r}; saw: {visible}")+ hit = hits[index]+ tap(hit["x"], hit["y"])+ return hit+++# --- gestures relative to the phone window ---++def _win():+ return mirror.ensure_window()+++def swipe(direction, distance=0.4):+ """swipe('up'|'down'|'left'|'right') β a touch-drag centered in the window.+ Direction is finger motion: swipe('up') moves content up (scrolls down)."""+ w = _win()+ cx, cy = w["x"] + w["w"] / 2, w["y"] + w["h"] / 2+ dx = {"left": -1, "right": 1}.get(direction, 0) * w["w"] * distance+ dy = {"up": -1, "down": 1}.get(direction, 0) * w["h"] * distance+ if not dx and not dy:+ raise ValueError(f"unknown direction {direction!r}")+ mirror.drag(cx - dx / 2, cy - dy / 2, cx + dx / 2, cy + dy / 2)+++def scroll(amount=300):+ """Scroll-gesture at window center. Positive scrolls content down the way+ a trackpad two-finger-up does; use swipe() when momentum matters."""+ w = _win()+ mirror.scroll_wheel(-amount, w["x"] + w["w"] / 2, w["y"] + w["h"] / 2)+++# --- navigation ---++def home():+ """Go to the iPhone Home Screen (Cmd+1)."""+ press("cmd+1")+ time.sleep(0.8)+++def app_switcher():+ press("cmd+2")+ time.sleep(0.8)+++def open_app(name):+ """Open an app via Spotlight (Cmd+3): type name, return, wait for launch."""+ press("cmd+3")+ time.sleep(0.9)+ type_text(name)+ time.sleep(1.2) # let results populate before committing+ press("return")+ wait_stable()+++# --- timing ---++def wait(seconds=1.0):+ time.sleep(seconds)+++def wait_stable(timeout=6.0, interval=0.5, settle=2):+ """Wait until `settle` consecutive captures are identical (animation done).+ The status-bar clock ticks once a minute, so near-misses are rare."""+ prev, same = None, 0+ deadline = time.time() + timeout+ while time.time() < deadline:+ path, _ = mirror.capture()+ digest = hashlib.md5(Path(path).read_bytes()).hexdigest()+ same = same + 1 if digest == prev else 0+ if same >= settle - 1:+ return True+ prev = digest+ time.sleep(interval)+ return False+++def _load_agent_helpers():+ p = AGENT_WORKSPACE / "agent_helpers.py"+ if not p.exists():+ return+ spec = importlib.util.spec_from_file_location("phone_harness_agent_helpers", p)+ if not spec or not spec.loader:+ return+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ for name, value in vars(module).items():+ if not name.startswith("_"):+ globals()[name] = value+++_load_agent_helpers()diff --git a/src/phone_harness/mirror.py b/src/phone_harness/mirror.pynew file mode 100644index 0000000..25b2221--- /dev/null+++ b/src/phone_harness/mirror.py@@ -0,0 +1,206 @@+"""iPhone Mirroring transport: window discovery, focus, capture, input.++All public coordinates are global screen points β the same space+`screencapture -R` and CGEvent use. The mirroring window is a video stream:+macOS accessibility sees nothing inside it, so input is synthesized at the+HID level and the window must be frontmost or events are swallowed.+"""+import subprocess, tempfile, time+from pathlib import Path++import Quartz+from AppKit import NSRunningApplication, NSWorkspace++APP_NAME = "iPhone Mirroring"+BUNDLE_ID = "com.apple.ScreenContinuity"+APP_PATH = "/System/Applications/iPhone Mirroring.app"++TMP = Path(tempfile.gettempdir()) / "phone-harness"+TMP.mkdir(exist_ok=True)+++# --- window / app state ---++def find_window():+ """{x, y, w, h, id} of the mirroring window in screen points, or None."""+ wins = Quartz.CGWindowListCopyWindowInfo(+ Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID) or []+ for w in wins:+ if w.get("kCGWindowOwnerName") == APP_NAME and w.get("kCGWindowLayer", 1) == 0:+ b = w["kCGWindowBounds"]+ if b["Width"] < 100: # ignore panels/toolbars+ continue+ return {"x": b["X"], "y": b["Y"], "w": b["Width"], "h": b["Height"],+ "id": int(w["kCGWindowNumber"])}+ return None+++def running_app():+ apps = NSRunningApplication.runningApplicationsWithBundleIdentifier_(BUNDLE_ID)+ return apps[0] if apps else None+++def is_frontmost():+ front = NSWorkspace.sharedWorkspace().frontmostApplication()+ return bool(front and front.bundleIdentifier() == BUNDLE_ID)+++def activate():+ app = running_app()+ if app is None:+ subprocess.run(["open", "-a", APP_NAME], check=True)+ deadline = time.time() + 15+ while app is None and time.time() < deadline:+ time.sleep(0.5)+ app = running_app()+ if app is None:+ raise RuntimeError(f"{APP_NAME} did not launch")+ if not is_frontmost():+ app.activateWithOptions_(1 << 1) # NSApplicationActivateIgnoringOtherApps+ time.sleep(0.5)+++def ensure_window(timeout=15.0):+ """Launch + focus the mirroring app if needed; return window bounds.++ The window exists even while the session shows a paused/connect+ interstitial β detecting those is the caller's job (OCR the capture).+ """+ win = find_window()+ if win is None:+ activate()+ deadline = time.time() + timeout+ while win is None and time.time() < deadline:+ time.sleep(0.5)+ win = find_window()+ if win is None:+ raise RuntimeError(+ f"{APP_NAME} has no window β is the phone paired and in range?")+ return win+++# --- capture ---++def capture(path=None):+ """Capture just the mirroring window (works even if partly covered).++ Returns (path, window_bounds). -o omits the drop shadow so image pixels+ map linearly onto the window rect.+ """+ win = ensure_window()+ path = str(path or TMP / "window.png")+ subprocess.run(+ ["screencapture", "-x", "-o", "-l", str(win["id"]), path], check=True)+ return path, win+++# --- input primitives ---++def _post_mouse(etype, x, y):+ ev = Quartz.CGEventCreateMouseEvent(+ None, etype, Quartz.CGPointMake(x, y), Quartz.kCGMouseButtonLeft)+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)+++def _focus():+ activate()+++def tap(x, y):+ _focus()+ _post_mouse(Quartz.kCGEventMouseMoved, x, y)+ time.sleep(0.1)+ _post_mouse(Quartz.kCGEventLeftMouseDown, x, y)+ time.sleep(0.06)+ _post_mouse(Quartz.kCGEventLeftMouseUp, x, y)+++def long_press(x, y, duration=0.8):+ _focus()+ _post_mouse(Quartz.kCGEventMouseMoved, x, y)+ time.sleep(0.1)+ _post_mouse(Quartz.kCGEventLeftMouseDown, x, y)+ time.sleep(duration)+ _post_mouse(Quartz.kCGEventLeftMouseUp, x, y)+++def drag(x1, y1, x2, y2, duration=0.35, steps=14):+ """Touch-drag (what iOS sees as a swipe)."""+ _focus()+ _post_mouse(Quartz.kCGEventMouseMoved, x1, y1)+ time.sleep(0.1)+ _post_mouse(Quartz.kCGEventLeftMouseDown, x1, y1)+ for i in range(1, steps + 1):+ t = i / steps+ _post_mouse(Quartz.kCGEventLeftMouseDragged,+ x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)+ time.sleep(duration / steps)+ _post_mouse(Quartz.kCGEventLeftMouseUp, x2, y2)+++def scroll_wheel(dy, x, y, steps=6):+ """Scroll-gesture at (x, y). Positive dy scrolls content up (finger down)."""+ _focus()+ _post_mouse(Quartz.kCGEventMouseMoved, x, y)+ time.sleep(0.1)+ for _ in range(steps):+ ev = Quartz.CGEventCreateScrollWheelEvent(+ None, Quartz.kCGScrollEventUnitPixel, 1, int(dy / steps))+ Quartz.CGEventSetLocation(ev, Quartz.CGPointMake(x, y))+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)+ time.sleep(0.03)+++_KEYCODES = {+ "return": 36, "enter": 36, "tab": 48, "space": 49, "delete": 51,+ "backspace": 51, "escape": 53, "esc": 53,+ "left": 123, "right": 124, "down": 125, "up": 126,+ "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22, "7": 26,+ "8": 28, "9": 25, "0": 29,+ "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8,+ "v": 9, "b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17,+ "o": 31, "u": 32, "i": 34, "p": 35, "l": 37, "j": 38, "k": 40, "n": 45,+ "m": 46,+}+_MODIFIERS = {+ "cmd": Quartz.kCGEventFlagMaskCommand,+ "shift": Quartz.kCGEventFlagMaskShift,+ "alt": Quartz.kCGEventFlagMaskAlternate,+ "option": Quartz.kCGEventFlagMaskAlternate,+ "ctrl": Quartz.kCGEventFlagMaskControl,+}+++def press(combo):+ """press('return'), press('cmd+1'), press('cmd+3')."""+ _focus()+ parts = combo.lower().split("+")+ key, mods = parts[-1], parts[:-1]+ if key not in _KEYCODES:+ raise ValueError(f"unknown key {key!r}")+ flags = 0+ for m in mods:+ flags |= _MODIFIERS[m]+ for down in (True, False):+ ev = Quartz.CGEventCreateKeyboardEvent(None, _KEYCODES[key], down)+ if flags:+ Quartz.CGEventSetFlags(ev, flags)+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)+ time.sleep(0.03)+++def type_text(text):+ """Type arbitrary unicode into the focused iOS field. \n presses return."""+ _focus()+ for i, line in enumerate(text.split("\n")):+ if i:+ press("return")+ for j in range(0, len(line), 20):+ chunk = line[j:j + 20]+ units = len(chunk.encode("utf-16-le")) // 2+ for down in (True, False):+ ev = Quartz.CGEventCreateKeyboardEvent(None, 0, down)+ Quartz.CGEventKeyboardSetUnicodeString(ev, units, chunk)+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)+ time.sleep(0.01)+ time.sleep(0.03)diff --git a/src/phone_harness/ocr.py b/src/phone_harness/ocr.pynew file mode 100644index 0000000..6b5f9ee--- /dev/null+++ b/src/phone_harness/ocr.py@@ -0,0 +1,56 @@+"""Text recognition over window captures via Apple's Vision framework.++This is the mirror backend's element tree: OCR gives every visible string a+bounding box, converted here into global screen points ready for tap().+"""+import Quartz+import Vision+from Foundation import NSURL+++def image_size(path):+ src = Quartz.CGImageSourceCreateWithURL(NSURL.fileURLWithPath_(path), None)+ if src is None:+ raise RuntimeError(f"cannot read image {path}")+ props = Quartz.CGImageSourceCopyPropertiesAtIndex(src, 0, None)+ return int(props["PixelWidth"]), int(props["PixelHeight"])+++def recognize(path, window):+ """OCR a capture of `window` ({x, y, w, h} screen points).++ Returns [{text, confidence, x, y, w, h}] where (x, y) is the box center in+ screen points β pass straight to tap(). Vision's normalized boxes have a+ bottom-left origin; screen points have a top-left origin, hence the flip.+ """+ handler = Vision.VNImageRequestHandler.alloc().initWithURL_options_(+ NSURL.fileURLWithPath_(path), {})+ request = Vision.VNRecognizeTextRequest.alloc().init()+ request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)+ ok, err = handler.performRequests_error_([request], None)+ if not ok:+ raise RuntimeError(f"Vision OCR failed: {err}")++ img_w, img_h = image_size(path)+ sx = window["w"] / img_w # image px -> screen points+ sy = window["h"] / img_h++ out = []+ for obs in request.results() or []:+ cand = obs.topCandidates_(1)+ if not cand:+ continue+ bb = obs.boundingBox()+ px = bb.origin.x * img_w+ py_top = (1.0 - bb.origin.y - bb.size.height) * img_h+ pw = bb.size.width * img_w+ ph = bb.size.height * img_h+ out.append({+ "text": str(cand[0].string()),+ "confidence": round(float(cand[0].confidence()), 3),+ "x": round(window["x"] + (px + pw / 2) * sx, 1),+ "y": round(window["y"] + (py_top + ph / 2) * sy, 1),+ "w": round(pw * sx, 1),+ "h": round(ph * sy, 1),+ })+ return outdiff --git a/src/phone_harness/run.py b/src/phone_harness/run.pynew file mode 100644index 0000000..12c8e7e--- /dev/null+++ b/src/phone_harness/run.py@@ -0,0 +1,40 @@+"""The phone-harness CLI: exec Python from stdin with helpers pre-imported."""+import sys+from pathlib import Path++USAGE = """Usage:+ phone-harness <<'PY'+ print(screen_info())+ PY++Commands:+ phone-harness --doctor diagnose permissions, app, and session state+ phone-harness skill print the phone-harness skill text+"""+++def main():+ args = sys.argv[1:]+ if args and args[0] in {"-h", "--help"}:+ print(USAGE)+ return+ if args and args[0] in {"--doctor", "doctor"}:+ from .admin import run_doctor+ sys.exit(run_doctor())+ if args and args[0] == "skill":+ repo_root = Path(__file__).resolve().parent.parent.parent+ print((repo_root / "SKILL.md").read_text(encoding="utf-8"), end="")+ return+ if args or sys.stdin.isatty():+ sys.exit(USAGE)+ code = sys.stdin.read()+ if not code.strip():+ sys.exit(USAGE)+ from . import helpers+ g = {k: v for k, v in vars(helpers).items() if not k.startswith("_")}+ g["__name__"] = "__main__"+ exec(code, g)+++if __name__ == "__main__":+ main()