let your agent control your phone
Hermes can drive the phone: a phone_exec plugin in integrations/hermes (#111)
shawn pana701e16099c57
diff --git a/README.md b/README.mdindex 9abe502..6fb050e 100644--- a/README.md+++ b/README.md@@ -44,6 +44,9 @@ It also offers a cloud Android — the same helpers with nothing to pair, andthe first 100 minutes free — so an iPhone user can test on Android too.`phone-harness --doctor` checks the chain. Details in [install.md](install.md).+**Hermes Agent:** `hermes plugins install ShawnPana/phone-harness/integrations/hermes`+adds a `phone_exec` tool and this skill. See [integrations/hermes](integrations/hermes/README.md).+## Usage```bashdiff --git a/integrations/hermes/README.md b/integrations/hermes/README.mdnew file mode 100644index 0000000..a68bb5a--- /dev/null+++ b/integrations/hermes/README.md@@ -0,0 +1,102 @@+# phone-harness for Hermes Agent++A [Hermes Agent](https://github.com/NousResearch/hermes-agent) plugin that lets+Hermes drive a real phone with one tool, `phone_exec`. The model writes a short+Python script with the phone-harness helpers pre-imported, and the plugin runs+it on the phone and returns what it printed.++```text+phone_exec(code='''+ensure_device()+open_app("Weather")+wait_stable()+print([o["text"] for o in ocr()][:12])+''')+```++When the installed `phone_harness` package contains `SKILL.md`, the plugin+registers that file as the skill `phone-harness:phone-harness`, and passes+Hermes the description and frontmatter from the file (Hermes does not re-read+them for the skill list). If the package does not ship `SKILL.md`, no skill is+registered. The agent reads the helpers from that skill.++## Install++```bash+hermes plugins install ShawnPana/phone-harness/integrations/hermes+```++Hermes installs the `phone-harness` package into its own environment and asks+whether to enable the plugin. Tools load per session, so start a new chat.+Each script runs as `python -m phone_harness.run` on Hermes's interpreter: the+copy Hermes installed, kept apart from a `phone-harness` command on `PATH`.++phone-harness chooses the phone (an attached cloud phone, otherwise its+default). To force the phone on this machine, export `PHONE_HARNESS_PLATFORM`+as `ios` or `android` in the environment Hermes runs in. iPhone control needs+Accessibility and Screen Recording for the app that runs Hermes (the Hermes+desktop app, or your terminal for `hermes` in a shell). Android needs adb; a+cloud phone needs `phone-harness cloud login`. [install.md](../../install.md)+covers each.++## Settings++This plugin has no settings of its own.++- Telemetry follows phone-harness's own config.+- `PHONE_HARNESS_PLATFORM`, when you have exported it, is passed through.+- The agent workspace is one folder, `agent-workspace`, in Hermes's plugin+ data directory. If `PH_AGENT_WORKSPACE` is already set, that path is used+ instead. Each script receives it as `PH_AGENT_WORKSPACE`.++## How it works++1. The model calls `phone_exec(code, timeout_s=300)`.+2. A `pre_tool_call` hook reads the script. Phone helpers and plain data+ handling go straight through. A script that reaches past the phone goes to+ Hermes's approval prompt first (see below).+3. Subagents in this process take turns on the phone, via an in-process lock.+ After 120 s the tool reports the phone as busy.+4. The plugin pipes the script on stdin to the phone-harness Hermes installed,+ with `PH_AGENT_WORKSPACE` and `PH_CLIENT=hermes`. It does not set a platform+ and does not turn telemetry off.+5. The result is what the script printed, plus the exit code, the tail of+ stderr, and any screenshot paths it printed (the agent opens those with+ `vision_analyze`). A script past its timeout is killed with everything it+ started.++## Approvals++phone-harness scripts are Python, so they can do anything Python can on this+computer. The hook sends a script to Hermes's approval prompt when it:++- imports anything beyond `phone_harness` and a small set of data modules+ (`json`, `re`, `time`, `math`, `datetime`, `collections`, ...);+- calls `open`, `exec`, `eval`, `compile`, `__import__`, `breakpoint` or `input`;+- touches dunder names (`__builtins__`, `__globals__`, `"__self__"`, ...);+- runs an adb `shell()` command on the phone.++Denial, timeout or no one to ask (cron, the messaging gateway) fails closed.+This is a heuristic gate, not a sandbox. Taps, typing and app launches never+ask: what to do on the phone is the skill's consent rule, which tells the agent+to ask before sending, posting, buying, deleting or changing settings.++## What it touches++- Runs model-written Python locally through the phone-harness Hermes installed.+- Taps and types into your real phone, with your apps and accounts.+- Screenshots are PNG files in the system temp folder.+- A cloud phone streams its screen to Phone Harness Cloud, bills by the minute,+ and uses phone-harness's own cloud sign-in.+- Hermes adds the plugin's toolset to every platform that has a saved tool+ selection, messaging platforms included. Turn it off there with+ `hermes tools` unless you want people who can message your bot to drive your+ phone.++## Limits++- Screenshots are not attached to the model's context automatically; the+ agent views them with `vision_analyze`.+- No password-vault integration: the agent never types passwords, PINs or 2FA+ codes. Hand the phone back to the user for those.+- `back()` is Android-only; on an iPhone the agent taps the app's back arrow.diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.pynew file mode 100644index 0000000..bd7941a--- /dev/null+++ b/integrations/hermes/__init__.py@@ -0,0 +1,311 @@+"""phone-harness for Hermes Agent: one ``phone_exec`` tool.++The model writes a Python script. The plugin pipes it on stdin to the phone-harness Hermes+installed from this plugin's python_dependencies, which runs it with the phone helpers+pre-imported against the user's phone and hands stdout back as the tool result. Each call is+a fresh interpreter; the phone and the agent workspace persist.++Safety, in order of what it protects:+- A ``pre_tool_call`` hook sends any script that reaches past the phone (imports beyond a small set+ of data modules, file and eval builtins, dunder introspection, adb ``shell()``) to Hermes's+ approval prompt. It is a heuristic gate, not a sandbox.+- One script drives the phone at a time, across subagents in this process.+"""+from __future__ import annotations++import ast+import contextlib+import importlib.util+import json+import os+import re+import signal+import subprocess+import sys+import threading+from pathlib import Path+from typing import Any++PLUGIN = "phone-harness"+DEFAULT_TIMEOUT_S, MIN_TIMEOUT_S, MAX_TIMEOUT_S = 300, 5, 1800+LOCK_WAIT_S = 120+OUTPUT_CAP, STDERR_CAP = 50_000, 4_000++_THREAD_LOCK = threading.Lock() # subagents in this process take turns on the phone++DESCRIPTION = (+ "Drive the user's real phone with phone-harness: their iPhone through the Mac's iPhone Mirroring "+ "window, an Android over adb, or a Phone Harness Cloud phone. `code` runs as Python with the phone "+ "helpers pre-imported; print() whatever you need back. Each call is a fresh interpreter (variables "+ "do not persist); the phone keeps its state. Start with ensure_device(). Ask the user before "+ "anything outward-facing or hard to undo (sending, posting, buying, deleting, changing settings). "+ "Never type passwords, PINs or 2FA codes. Read the skill phone-harness:phone-harness for the helpers."+)++SCHEMA = {+ "name": "phone_exec",+ "description": DESCRIPTION,+ "parameters": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": "Python using the pre-imported phone-harness helpers. print() what you need back.",+ },+ "timeout_s": {+ "type": "integer",+ "default": DEFAULT_TIMEOUT_S,+ "description": f"Max seconds for the script (default {DEFAULT_TIMEOUT_S}, max {MAX_TIMEOUT_S}).",+ },+ },+ "required": ["code"],+ },+}++# ---------------------------------------------------------------------------------------------+# Approval gate: what a phone script may do without asking.++# Modules a phone script can import without touching the computer beyond the phone.+SAFE_MODULES = frozenset({+ "phone_harness", "json", "re", "time", "math", "random", "string", "datetime", "itertools",+ "functools", "collections", "statistics", "textwrap", "difflib", "typing", "dataclasses", "enum",+ "decimal", "fractions", "pprint", "unicodedata", "operator", "heapq", "bisect", "copy",+})+# Builtins that read or write files, run arbitrary code, or wait on a terminal; shell() is+# phone-harness's adb shell.+RISKY_CALLS = frozenset({"open", "exec", "eval", "compile", "__import__", "breakpoint", "input", "shell"})+_DUNDER = re.compile(r"^__\w+__$")+_FM_END = re.compile(r"\n---\s*(?:\n|$)")+++def approval_reason(code: str) -> str | None:+ """Why this script needs the user's OK before it runs, or None when it only drives the phone.++ Phone helpers and plain data handling pass. Host access (imports outside SAFE_MODULES, file and+ eval builtins, dunder introspection) and raw adb shell commands do not. A heuristic, not a sandbox.+ """+ try:+ tree = ast.parse(code)+ except SyntaxError:+ return None # it cannot run; the SyntaxError comes back as the result+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.name.split(".")[0] not in SAFE_MODULES:+ return f"imports {alias.name}"+ elif isinstance(node, ast.ImportFrom):+ if node.level or (node.module or "").split(".")[0] not in SAFE_MODULES:+ return f"imports from {node.module or '.'}"+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in RISKY_CALLS:+ return f"calls {node.func.id}()"+ elif isinstance(node, ast.Attribute) and _DUNDER.match(node.attr):+ return f"uses {node.attr}"+ elif isinstance(node, ast.Name) and _DUNDER.match(node.id):+ return f"uses {node.id}"+ elif isinstance(node, ast.Constant) and isinstance(node.value, str) and _DUNDER.match(node.value):+ return f"references {node.value}"+ return None+++def _on_pre_tool_call(tool_name: str = "", args: dict | None = None, task_id: str = "", **kwargs):+ if tool_name != "phone_exec":+ return None+ reason = approval_reason(str((args or {}).get("code") or ""))+ if reason is None:+ return None+ return {"action": "approve",+ "message": f"phone_exec wants to run a script that {reason}, which reaches past the phone "+ "onto this computer."}++# ---------------------------------------------------------------------------------------------+# The copy Hermes installed, and where its scripts keep notes.+++def _data_dir() -> Path:+ """Hermes's data folder for this plugin: follows the active profile, survives plugin updates."""+ try:+ from plugins.plugin_storage import plugin_data_dir+ return Path(plugin_data_dir(PLUGIN))+ except Exception: # outside Hermes (unit tests)+ return Path.home() / ".hermes" / "plugin-data" / PLUGIN+++def _package_dir() -> Path | None:+ """Directory of the phone_harness Hermes installed, or None when it cannot be imported."""+ spec = importlib.util.find_spec("phone_harness")+ if spec is None or not spec.origin:+ return None+ return Path(spec.origin).resolve().parent+++def _command() -> list[str] | None:+ """argv for the phone-harness Hermes installed, on Hermes's own interpreter."""+ if _package_dir() is None:+ return None+ return [sys.executable, "-m", "phone_harness.run"]+++def _available() -> bool:+ return _command() is not None+++def _workspace() -> Path:+ """Where notes live. An inherited PH_AGENT_WORKSPACE, else one folder in Hermes's plugin data."""+ inherited = os.environ.get("PH_AGENT_WORKSPACE", "").strip()+ if inherited:+ return Path(inherited).expanduser()+ return _data_dir() / "agent-workspace"+++def _env(workspace: Path) -> dict:+ """The script inherits Hermes's environment. Platform and telemetry stay phone-harness's own+ config: an exported PHONE_HARNESS_PLATFORM is left as it is, and this plugin does not set one."""+ env = dict(os.environ)+ env["PH_AGENT_WORKSPACE"] = str(workspace)+ env["PH_CLIENT"] = "hermes"+ return env++# ---------------------------------------------------------------------------------------------+# One script on the phone at a time (subagents in this process).+++class PhoneBusy(Exception):+ pass+++def _phone_lock(wait_s: float):+ """Subagents take turns. Raises PhoneBusy after wait_s."""+ if not _THREAD_LOCK.acquire(timeout=max(wait_s, 0.1)):+ raise PhoneBusy+ try:+ yield+ finally:+ _THREAD_LOCK.release()++# ---------------------------------------------------------------------------------------------+# The tool.+++def _kill_group(proc: subprocess.Popen) -> None:+ """Kill the runner and everything it spawned (it runs in its own process group)."""+ if os.name == "nt":+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True, check=False)+ return+ with contextlib.suppress(ProcessLookupError, PermissionError):+ os.killpg(proc.pid, signal.SIGKILL)+++def _result(success: bool, **fields) -> str:+ return json.dumps({"success": success, **{k: v for k, v in fields.items() if v not in (None, "", [])}},+ ensure_ascii=False)+++def _timeout(value) -> int:+ try:+ return max(MIN_TIMEOUT_S, min(int(value or DEFAULT_TIMEOUT_S), MAX_TIMEOUT_S))+ except (TypeError, ValueError):+ return DEFAULT_TIMEOUT_S+++_PNG = re.compile(r"(/[^\s'\"]+\.png)\b")+++def phone_exec(args: dict, **kwargs) -> str:+ code = str((args or {}).get("code") or "")+ if not code.strip():+ return _result(False, error="No code provided. Start with: ensure_device(); print(screen_info())")+ cmd = _command()+ if cmd is None:+ return _result(False, error="phone-harness is not installed in Hermes's environment. "+ "Reinstall this plugin so Hermes installs it.")+ timeout = _timeout((args or {}).get("timeout_s"))+ workspace = _workspace()+ group: dict[str, Any] = ({"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)}+ if os.name == "nt" else {"start_new_session": True})+ try:+ workspace.mkdir(parents=True, exist_ok=True)+ with _phone_lock(LOCK_WAIT_S):+ proc = subprocess.Popen(+ cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ text=True, encoding="utf-8", errors="replace",+ env=_env(workspace), cwd=str(workspace), **group,+ )+ try:+ out, err = proc.communicate(input=code, timeout=timeout)+ except subprocess.TimeoutExpired:+ _kill_group(proc)+ with contextlib.suppress(subprocess.TimeoutExpired):+ proc.communicate(timeout=10)+ return _result(False, workspace=str(workspace),+ error=f"phone_exec timed out after {timeout}s. Split the work into smaller "+ f"scripts or raise timeout_s (max {MAX_TIMEOUT_S}).")+ except PhoneBusy:+ return _result(False, error=f"The phone is busy with another phone_exec script (waited {LOCK_WAIT_S}s). "+ "Try again when it finishes.")+ except OSError as e:+ return _result(False, error=f"Failed to launch phone-harness: {e}")++ out = out or ""+ shots = [p for p in dict.fromkeys(_PNG.findall(out)) if os.path.isfile(p)]+ return _result(proc.returncode == 0, exit_code=proc.returncode, output=out[-OUTPUT_CAP:],+ stderr=(err or "").strip()[-STDERR_CAP:], screenshots=shots, workspace=str(workspace))++# ---------------------------------------------------------------------------------------------+# Registration.+++def _parse_frontmatter(text: str) -> dict[str, str]:+ """Flat YAML scalars at the top of a SKILL.md, or {} when there is no frontmatter.++ Hermes stores the description and frontmatter ``register_skill`` is given and does not+ re-read the file for the skill list, so leaving them off shows an empty skill.+ """+ text = text.lstrip("\ufeff")+ if not text.startswith("---"):+ return {}+ end = _FM_END.search(text[3:])+ if not end:+ return {}+ data: dict[str, str] = {}+ for line in text[3:end.start() + 3].splitlines():+ stripped = line.strip()+ if not stripped or stripped.startswith("#") or ":" not in stripped:+ continue+ key, value = stripped.split(":", 1)+ value = value.strip()+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":+ value = value[1:-1]+ data[key.strip()] = value+ return data+++def _packaged_skill() -> tuple[Path, str, dict[str, str]] | None:+ """SKILL.md inside the installed phone_harness package, read once. None if it does not ship one."""+ root = _package_dir()+ if root is None:+ return None+ path = root / "SKILL.md"+ if not path.is_file():+ return None+ frontmatter = _parse_frontmatter(path.read_text(encoding="utf-8"))+ return path, frontmatter.get("description", ""), frontmatter+++def _register_skill(ctx) -> None:+ skill = _packaged_skill()+ if skill is None:+ return+ path, description, frontmatter = skill+ try:+ ctx.register_skill(PLUGIN, path, description=description, frontmatter=frontmatter)+ except TypeError: # Hermes builds that take a path and a description, and not frontmatter+ ctx.register_skill(PLUGIN, path, description=description)+++def register(ctx) -> None:+ ctx.register_tool(name="phone_exec", toolset=PLUGIN, schema=SCHEMA, handler=phone_exec,+ check_fn=_available, emoji="📱")+ ctx.register_hook("pre_tool_call", _on_pre_tool_call)+ with contextlib.suppress(Exception):+ _register_skill(ctx)diff --git a/integrations/hermes/plugin.yaml b/integrations/hermes/plugin.yamlnew file mode 100644index 0000000..b790c3c--- /dev/null+++ b/integrations/hermes/plugin.yaml@@ -0,0 +1,14 @@+name: phone-harness+version: 0.1.0+manifest_version: 2+description: Drive a real phone from Hermes with one phone_exec tool (iPhone via iPhone Mirroring, Android over adb, or a cloud phone)+author: Shawn Pana+license: MIT+homepage: https://phone-harness.com+tags: [phone, iphone, android, automation]+provides_tools:+ - phone_exec+provides_hooks:+ - pre_tool_call+python_dependencies:+ - "phone-harness>=0.3,<0.4"diff --git a/tests/test_hermes_plugin.py b/tests/test_hermes_plugin.pynew file mode 100644index 0000000..79fb8bd--- /dev/null+++ b/tests/test_hermes_plugin.py@@ -0,0 +1,276 @@+"""The Hermes plugin in integrations/hermes, tested without Hermes or a phone.++It loads integrations/hermes/__init__.py by path, points its data folder at a temp+dir and swaps the phone-harness command for a plain Python that runs the script it+is given, so what is checked is the plumbing around a script: the approval gate,+the environment the script runs in, one script on the phone at a time, timeouts,+and what register() hands Hermes.++ python -m unittest discover tests+"""+import importlib.util+import json+import os+import sys+import tempfile+import time+import unittest+from pathlib import Path+from typing import Any++PLUGIN_INIT = Path(__file__).resolve().parents[1] / "integrations" / "hermes" / "__init__.py"+REPO_SKILL = Path(__file__).resolve().parents[1] / "SKILL.md"+++def load_plugin() -> Any:+ spec = importlib.util.spec_from_file_location("phone_harness_hermes_plugin", PLUGIN_INIT)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++class FakeCtx:+ """The slice of Hermes's PluginContext the plugin uses."""++ def __init__(self):+ self.tools, self.hooks, self.skills = {}, {}, {}++ def register_tool(self, name, toolset, schema, handler, **kw):+ self.tools[name] = dict(toolset=toolset, schema=schema, handler=handler, **kw)++ def register_hook(self, name, callback):+ self.hooks[name] = callback++ def register_skill(self, name, path, description="", frontmatter=None):+ self.skills[name] = {"path": path, "description": description, "frontmatter": dict(frontmatter or {})}+++class Base(unittest.TestCase):+ def setUp(self):+ self.plugin = load_plugin()+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.data = Path(tmp.name)+ self.plugin._data_dir = lambda: self.data+ self.plugin._workspace = lambda: self.data / "agent-workspace"+ # The installed module, here a Python that runs whatever script arrives on stdin.+ self.plugin._command = lambda: [sys.executable, "-c", "import sys; exec(sys.stdin.read())"]+ self.plugin._packaged_skill = lambda: None+ self.ctx = FakeCtx()+ self.plugin.register(self.ctx)++ def run_tool(self, code, **args):+ return json.loads(self.plugin.phone_exec({"code": code, **args}))+++class Registration(Base):+ def test_one_tool_and_the_approval_hook(self):+ tool = self.ctx.tools["phone_exec"]+ self.assertEqual(tool["toolset"], "phone-harness")+ self.assertEqual(tool["schema"]["name"], "phone_exec")+ self.assertTrue(tool["check_fn"]())+ self.assertIn("pre_tool_call", self.ctx.hooks)++ def test_the_tool_description_points_at_the_skill(self):+ description = self.ctx.tools["phone_exec"]["schema"]["description"]+ self.assertIn("ensure_device()", description)+ self.assertIn("phone-harness:phone-harness", description)+ self.assertIn("passwords", description)+ self.assertNotIn("scroll_until", description)+++class ApprovalGate(Base):+ PHONE_ONLY = [+ 'ensure_device()\nprint([o["text"] for o in ocr()][:10])',+ 'import json, re, time\nprint(json.dumps(screen_info()))',+ 'from phone_harness import helpers\nhelpers.tap_text("Weather")',+ 'from collections import Counter\nprint(Counter(o["text"] for o in ocr()))',+ 'def (', # a SyntaxError cannot run, so there is nothing to approve+ ]+ PAST_THE_PHONE = [+ "import os", "import subprocess", "import os.path", "from os import path", "import Quartz",+ "from . import agent_helpers", 'open("notes.txt", "w").write("x")', '__import__("os")',+ 'eval("1")', "print.__self__", 'getattr(print, "__self__")', 'shell("pm list packages")',+ ]++ def hook(self, code, tool="phone_exec"):+ return self.ctx.hooks["pre_tool_call"](tool_name=tool, args={"code": code}, task_id="t")++ def test_phone_scripts_run_without_asking(self):+ for code in self.PHONE_ONLY:+ with self.subTest(code=code):+ self.assertIsNone(self.plugin.approval_reason(code))+ self.assertIsNone(self.hook(code))++ def test_scripts_that_reach_past_the_phone_ask_first(self):+ for code in self.PAST_THE_PHONE:+ with self.subTest(code=code):+ self.assertIsNotNone(self.plugin.approval_reason(code))+ directive = self.hook(code)+ self.assertEqual(directive["action"], "approve")+ self.assertIn("phone_exec", directive["message"])++ def test_other_tools_are_left_alone(self):+ self.assertIsNone(self.hook("import os", tool="terminal"))+++class Environment(Base):+ def test_inherited_env_passes_through_with_workspace_and_client(self):+ saved = dict(os.environ)+ self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))+ os.environ["PYTHONHOME"] = "/somewhere"+ os.environ["PYTHONPATH"] = "/hermes"+ os.environ["PHONE_HARNESS_PLATFORM"] = "ios"+ os.environ["PHONE_HARNESS_TELEMETRY"] = "1"+ env = self.plugin._env(self.data / "ws")+ self.assertEqual(env["PH_AGENT_WORKSPACE"], str(self.data / "ws"))+ self.assertEqual(env["PH_CLIENT"], "hermes")+ self.assertEqual(env["PYTHONHOME"], "/somewhere")+ self.assertEqual(env["PYTHONPATH"], "/hermes")+ self.assertEqual(env["PHONE_HARNESS_PLATFORM"], "ios")+ self.assertEqual(env["PHONE_HARNESS_TELEMETRY"], "1")++ def test_the_plugin_does_not_invent_platform_or_telemetry(self):+ saved = dict(os.environ)+ self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))+ os.environ.pop("PHONE_HARNESS_PLATFORM", None)+ os.environ.pop("PHONE_HARNESS_TELEMETRY", None)+ env = self.plugin._env(self.data / "ws")+ self.assertNotIn("PHONE_HARNESS_PLATFORM", env)+ self.assertNotIn("PHONE_HARNESS_TELEMETRY", env)+++class Workspace(unittest.TestCase):+ def setUp(self):+ self.plugin = load_plugin()+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.data = Path(tmp.name)+ self.plugin._data_dir = lambda: self.data+ self.saved = os.environ.get("PH_AGENT_WORKSPACE")+ os.environ.pop("PH_AGENT_WORKSPACE", None)+ self.addCleanup(self.restore)++ def restore(self):+ if self.saved is None:+ os.environ.pop("PH_AGENT_WORKSPACE", None)+ else:+ os.environ["PH_AGENT_WORKSPACE"] = self.saved++ def test_default_is_one_folder_in_the_plugin_data_dir(self):+ self.assertEqual(self.plugin._workspace(), self.data / "agent-workspace")++ def test_an_inherited_workspace_is_honored(self):+ os.environ["PH_AGENT_WORKSPACE"] = str(self.data / "custom")+ self.assertEqual(self.plugin._workspace(), self.data / "custom")++ def test_a_blank_inherited_workspace_is_ignored(self):+ os.environ["PH_AGENT_WORKSPACE"] = " "+ self.assertEqual(self.plugin._workspace(), self.data / "agent-workspace")+++class Command(unittest.TestCase):+ def test_runs_the_installed_module_on_hermes_interpreter(self):+ plugin = load_plugin()+ plugin._package_dir = lambda: Path("/opt/hermes/phone_harness")+ self.assertEqual(plugin._command(), [sys.executable, "-m", "phone_harness.run"])++ def test_a_missing_package_is_unavailable(self):+ plugin = load_plugin()+ plugin._package_dir = lambda: None+ self.assertIsNone(plugin._command())+ self.assertFalse(plugin._available())+++class Skill(unittest.TestCase):+ def setUp(self):+ self.plugin = load_plugin()+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.root = Path(tmp.name)++ def test_the_real_skill_frontmatter_has_a_description(self):+ frontmatter = self.plugin._parse_frontmatter(REPO_SKILL.read_text(encoding="utf-8"))+ self.assertEqual(frontmatter["name"], "phone-harness")+ self.assertTrue(frontmatter["description"].startswith("Control the user's phone"))++ def test_a_package_without_skill_md_registers_nothing(self):+ self.plugin._package_dir = lambda: self.root+ ctx = FakeCtx()+ self.plugin.register(ctx)+ self.assertEqual(ctx.skills, {})++ def test_the_packaged_file_is_registered_with_its_frontmatter(self):+ path = self.root / "SKILL.md"+ path.write_text(+ '---\nname: phone-harness\ndescription: "Drive the phone."\n---\n\n# phone-harness\n',+ encoding="utf-8",+ )+ self.plugin._package_dir = lambda: self.root+ self.plugin._command = lambda: [sys.executable, "-c", ""]+ ctx = FakeCtx()+ self.plugin.register(ctx)+ self.assertEqual(ctx.skills["phone-harness"]["path"], path)+ self.assertEqual(ctx.skills["phone-harness"]["description"], "Drive the phone.")+ self.assertEqual(ctx.skills["phone-harness"]["frontmatter"], {+ "name": "phone-harness",+ "description": "Drive the phone.",+ })+++class Running(Base):+ def test_prints_come_back_as_output(self):+ result = self.run_tool("print(6 * 7)")+ self.assertTrue(result["success"])+ self.assertEqual(result["output"], "42\n")+ self.assertEqual(result["workspace"], str(self.data / "agent-workspace"))++ def test_the_script_runs_in_the_workspace_with_the_plugin_environment(self):+ saved = dict(os.environ)+ self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))+ os.environ["PHONE_HARNESS_PLATFORM"] = "ios"+ result = self.run_tool(+ "import os\nprint(os.getcwd())\nprint(os.environ['PH_CLIENT'])\n"+ "print(os.environ['PHONE_HARNESS_PLATFORM'])"+ )+ cwd, client, platform = result["output"].split()+ self.assertEqual(Path(cwd).resolve(), (self.data / "agent-workspace").resolve())+ self.assertEqual(client, "hermes")+ self.assertEqual(platform, "ios")++ def test_a_failing_script_reports_exit_code_and_stderr(self):+ result = self.run_tool('raise SystemExit("iPhone in Use")')+ self.assertFalse(result["success"])+ self.assertEqual(result["exit_code"], 1)+ self.assertIn("iPhone in Use", result["stderr"])++ def test_screenshot_paths_in_the_output_are_listed(self):+ shot = self.data / "shot.png"+ shot.write_bytes(b"\x89PNG")+ result = self.run_tool(f"print('saved {shot}')")+ self.assertEqual(result["screenshots"], [str(shot)])++ def test_empty_code_and_a_missing_module_are_errors_not_crashes(self):+ self.assertFalse(self.run_tool(" ")["success"])+ self.plugin._command = lambda: None+ self.assertIn("not installed", self.run_tool("print(1)")["error"])++ def test_a_script_past_its_timeout_is_killed(self):+ self.plugin.MIN_TIMEOUT_S = 1+ started = time.monotonic()+ result = self.run_tool("import time\ntime.sleep(30)", timeout_s=1)+ self.assertFalse(result["success"])+ self.assertIn("timed out after 1s", result["error"])+ self.assertLess(time.monotonic() - started, 15)++ def test_one_script_on_the_phone_at_a_time(self):+ self.plugin.LOCK_WAIT_S = 0.5+ self.assertTrue(self.plugin._THREAD_LOCK.acquire(timeout=1))+ try:+ busy = self.run_tool("print('should not run')")+ finally:+ self.plugin._THREAD_LOCK.release()+ self.assertFalse(busy["success"])+ self.assertIn("busy", busy["error"])+ self.assertTrue(self.run_tool("print('after')")["success"]) # the lock was released