let your agent control your phone
Ask before every Hermes phone script and scrub the child env (#125)
shawn pana927aca021619
diff --git a/SKILL.md b/SKILL.mdindex 1007cb8..686db85 100644--- a/SKILL.md+++ b/SKILL.md@@ -17,7 +17,7 @@ of you.- `ensure_device()` - Screen bounds once the device is usable, or raises with what the user has to do.- `screen(min_confidence=0.3)` - Visible text as `{text, confidence, source, x, y, w, h}` boxes. On Android the boxes come from the accessibility tree; on iPhone Mirroring they come from recognizing text.-- `screenshot(path=None)` - Capture the screen to a PNG and return its path.+- `screenshot(path=None)` - Capture the screen to a PNG, print its path, and return it.- `find_text(query, exact=False)` - Visible text boxes matching `query`.- `tap_text(query, index=0, exact=False)` - Tap the center of visible text matching `query`.- `tap(x, y)` - Tap one point.diff --git a/integrations/hermes/README.md b/integrations/hermes/README.mdindex 90c6177..e7c12dc 100644--- a/integrations/hermes/README.md+++ b/integrations/hermes/README.md@@ -42,8 +42,14 @@ covers each.## Settings-This plugin has no settings of its own.-+- Every `phone_exec` call asks before it runs. See [Approvals](#approvals).+- Classifier auto-run is off unless you opt in. With it on, a script the+ classifier judges to be phone-only skips the prompt. The classifier is a+ heuristic and can be bypassed, so a script may still reach this computer.+ Leave it off unless you accept that.+ - Plugin setting `classifier_auto_run` (boolean, default false).+ - Or export `PHONE_HARNESS_CLASSIFIER_AUTO_RUN=1` in the environment Hermes+ runs in. When that variable is set, it wins over the plugin setting.- Telemetry is off for Hermes runs unless you opt in with `phone-harness config set telemetry true`.- `PHONE_HARNESS_PLATFORM`, when you have exported it, is passed through.- The agent workspace is one folder, `agent-workspace`, in Hermes's plugin@@ -55,34 +61,41 @@ This plugin has no settings of its own.## How it works1. 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).+2. A `pre_tool_call` hook asks you to approve every script before it runs.+ Hermes shows a short description of the script. One answer for the session,+ or always, covers later calls. With classifier auto-run opted in, a script+ that only drives the phone runs without asking, and anything else still asks.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.Telemetry is off for Hermes runs unless you opt in with `phone-harness config set telemetry true`.-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.+5. The result is what the script printed, plus the exit code and the tail of+ stderr. `screenshot()` prints the path it saved. The last absolute PNG,+ JPEG, or WebP path in that output that exists and was written during the+ call is attached to the tool result when the model can view images. A+ large image is reduced first. If the model cannot view images, or+ attaching fails, the result stays plain text and the path is in+ `screenshots` (open it 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:+Every `phone_exec` call asks you before it runs. Hermes shows a short+description of the script. Allow it once, for the session, or always; one+session or always answer covers later calls. If nobody can answer (a scheduled+job, or a chat with no one there), the script does not run.-- 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.+Classifier auto-run is off unless you opt in (see [Settings](#settings)). With+it on, scripts that only use the phone helpers run immediately. The check is a+heuristic and can be bypassed: a script can still reach this computer. Leave+it off unless you accept that.-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.+While auto-run is on, a script still asks when it imports anything other than+the phone helpers, reads or writes files, runs or evaluates code, uses Python+internals, runs an adb shell command, or calls `send("raw", ...)`. What to do+on the phone itself — sending, posting, buying, deleting, changing settings —+is still the skill's consent rule: the agent asks you before those.## What it touches@@ -98,8 +111,8 @@ to ask before sending, posting, buying, deleting or changing settings.## Limits-- Screenshots are not attached to the model's context automatically; the- agent views them with `vision_analyze`.+- A screenshot saved during the call is attached when the model can view+ images. Otherwise the path is in the text result for `vision_analyze`.- No password-vault integration: the agent never types passwords, PINs or 2FAcodes. 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__.pyindex ffeaf19..dc0cbb9 100644--- a/integrations/hermes/__init__.py+++ b/integrations/hermes/__init__.py@@ -2,13 +2,17 @@The model writes a Python script. The plugin pipes it on stdin to the phone-harness Hermesinstalled 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+pre-imported against the user's phone and hands stdout back as the tool result. A screenshot+saved during the call is attached to that result when the model can view images. Each call isa 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.+- Every ``phone_exec`` call asks the user first. The ``pre_tool_call`` hook returns an approve+ directive with ``rule_key`` ``phone_exec``, so one session or always answer covers later calls.+- Classifier-only auto-run is an explicit opt-in (plugin setting ``classifier_auto_run`` or+ ``PHONE_HARNESS_CLASSIFIER_AUTO_RUN``). That check is a heuristic and can be bypassed.+- The child environment comes from Hermes's scrubbed subprocess env when that is importable,+ otherwise the process env minus ``*_API_KEY`` / ``*_TOKEN`` / ``*_SECRET``.- One script drives the phone at a time, across subagents in this process."""from __future__ import annotations@@ -24,6 +28,7 @@ import signalimport subprocessimport sysimport threading+import timefrom pathlib import Pathfrom typing import Any@@ -41,8 +46,10 @@ DESCRIPTION = ("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(); it covers iPhone "- "Mirroring, Android, and a cloud phone. Read what is on screen with screen(). Ask the user before "- "anything outward-facing or hard to undo (sending, posting, buying, deleting, changing settings). "+ "Mirroring, Android, and a cloud phone. Read what is on screen with screen(). screenshot() prints "+ "the image path it saved, and that image is attached to this result when you can view images. "+ "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.")@@ -67,42 +74,194 @@ SCHEMA = {}# ----------------------------------------------------------------------------------------------# Approval gate: what a phone script may do without asking.+# Approval gate.-# 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",-})+# Opt-in for skipping the prompt when a classifier thinks the script only drives the phone.+# The check is a heuristic and can be bypassed. Off unless the user turns it on.+CLASSIFIER_AUTO_RUN = "classifier_auto_run"+CLASSIFIER_AUTO_RUN_ENV = "PHONE_HARNESS_CLASSIFIER_AUTO_RUN"++# The only import the classifier treats as phone-only. Anything else asks.+SAFE_MODULES = frozenset({"phone_harness.helpers"})# 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"})+# Names helpers.py imports for itself. A script that pulls them in can reach this computer+# (importlib.import_module, Path.home().read_text, the transport module).+_HOST_NAMES = frozenset({+ "hashlib", "importlib", "time", "Path", "transport",+ "CORE_DIR", "REPO_ROOT", "AGENT_WORKSPACE",+})_DUNDER = re.compile(r"^__\w+__$")_FM_END = re.compile(r"\n---\s*(?:\n|$)")+_SUMMARY_LIMIT = 140++_plugin_ctx = None+++def _helpers_import(module: str) -> bool:+ return module == "phone_harness.helpers"+++def _assign_bindings(targets, value) -> list[tuple[list[str], ast.AST]]:+ """Simple name bindings in one assignment, including ``a, b = open, eval``."""+ found = []+ for target in targets:+ if isinstance(target, ast.Name):+ found.append(([target.id], value))+ continue+ if not isinstance(target, (ast.Tuple, ast.List)):+ continue+ if not all(isinstance(elt, ast.Name) for elt in target.elts):+ continue+ names = [elt.id for elt in target.elts]+ if isinstance(value, (ast.Tuple, ast.List)) and len(value.elts) == len(names):+ for name, elt in zip(names, value.elts):+ found.append(([name], elt))+ return found+++def _name_kinds(tree: ast.AST) -> tuple[set[str], set[str], set[str]]:+ """Risky-call names, send names, and names bound to the string ``raw``.++ Covers ``f = open``, ``s = send``, ``op = "raw"``, chains of those, and+ ``from phone_harness.helpers import shell as sh``.+ """+ risky = set(RISKY_CALLS)+ send_names = {"send"}+ raw_names: set[str] = set()+ pending: list[tuple[list[str], ast.AST]] = []+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom) and not node.level and node.module:+ if node.module == "phone_harness":+ imported = [alias for alias in node.names if alias.name == "helpers"]+ elif _helpers_import(node.module):+ imported = [alias for alias in node.names if alias.name != "*"]+ else:+ imported = []+ for alias in imported:+ if alias.name in RISKY_CALLS or alias.name == "send":+ bound = alias.asname or alias.name+ pending.append(([bound], ast.Name(id=alias.name, ctx=ast.Load())))+ elif isinstance(node, ast.Assign):+ pending.extend(_assign_bindings(node.targets, node.value))+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:+ pending.append(([node.target.id], node.value))+ elif isinstance(node, ast.NamedExpr) and isinstance(node.target, ast.Name):+ pending.append(([node.target.id], node.value))++ def kind_of(value: ast.AST) -> str | None:+ # A name that is already a risky call stays risky even if it is also+ # called send. Otherwise ``send = open`` would hide later aliases.+ if isinstance(value, ast.Name):+ if value.id in risky:+ return "risky"+ if value.id in send_names:+ return "send"+ if value.id in raw_names:+ return "raw"+ return None+ if isinstance(value, ast.Constant) and value.value == "raw":+ return "raw"+ if isinstance(value, ast.Attribute):+ if value.attr in RISKY_CALLS:+ return "risky"+ if value.attr == "send":+ return "send"+ return None++ changed = True+ while changed:+ changed = False+ for names, value in pending:+ kind = kind_of(value)+ if kind == "raw":+ bucket = raw_names+ elif kind == "send":+ bucket = send_names+ elif kind == "risky":+ bucket = risky+ else:+ continue+ for name in names:+ if name not in bucket:+ bucket.add(name)+ changed = True+ return risky, send_names, raw_names+++def _risky_callee(func: ast.AST, risky: set[str]) -> str | None:+ if isinstance(func, ast.Name) and func.id in risky:+ return func.id+ if isinstance(func, ast.Attribute) and func.attr in RISKY_CALLS:+ return func.attr+ if isinstance(func, ast.NamedExpr):+ return _risky_callee(func.value, risky)+ return None+++def _is_send_call(func: ast.AST, send_names: set[str]) -> bool:+ if isinstance(func, ast.Name):+ return func.id in send_names+ if isinstance(func, ast.Attribute):+ return func.attr == "send"+ if isinstance(func, ast.NamedExpr):+ return _is_send_call(func.value, send_names)+ return False+++def _passes_raw(node: ast.Call, raw_names: set[str]) -> bool:+ """True when the op argument is the string ``raw`` or a name bound to it."""+ candidates = [node.args[0]] if node.args else []+ candidates.extend(kw.value for kw in node.keywords if kw.arg == "op")+ for arg in candidates:+ if isinstance(arg, ast.Constant) and arg.value == "raw":+ return True+ if isinstance(arg, ast.Name) and arg.id in raw_names:+ return True+ return Falsedef 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.+ """Why this script reaches past the phone, 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.+ Only ``phone_harness.helpers`` imports pass. Host objects that module carries+ (``Path``, ``importlib``, the transport), file and eval builtins and aliases of+ those calls, ``send("raw", ...)``, and dunder introspection do not. A heuristic,+ not a sandbox: it can be bypassed."""try:tree = ast.parse(code)except SyntaxError:return None # it cannot run; the SyntaxError comes back as the result+ risky, send_names, raw_names = _name_kinds(tree)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:+ if not _helpers_import(alias.name):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):+ if node.level or not node.module:+ return f"imports from {'.' * (node.level or 1)}{node.module or ''}"+ if node.module == "phone_harness":+ for alias in node.names:+ if alias.name != "helpers":+ return f"imports {alias.name} from phone_harness"+ continue+ if not _helpers_import(node.module):+ return f"imports from {node.module}"+ for alias in node.names:+ if alias.name == "*" or alias.name in _HOST_NAMES:+ return f"imports {alias.name} from {node.module}"+ elif isinstance(node, ast.Call):+ callee = _risky_callee(node.func, risky)+ if callee is not None:+ if callee in RISKY_CALLS:+ return f"calls {callee}()"+ return f"calls {callee}(), an alias of a risky call"+ if _is_send_call(node.func, send_names) and _passes_raw(node, raw_names):+ return 'calls send("raw", ...)'+ elif isinstance(node, ast.Attribute) and (_DUNDER.match(node.attr) or node.attr in _HOST_NAMES):return f"uses {node.attr}"elif isinstance(node, ast.Name) and _DUNDER.match(node.id):return f"uses {node.id}"@@ -111,15 +270,52 @@ def approval_reason(code: str) -> str | None:return None+def _script_summary(code: str) -> str:+ """Short text Hermes can show on the approval prompt."""+ compact = " ".join(code.split())+ if not compact:+ compact = "(empty)"+ elif len(compact) > _SUMMARY_LIMIT:+ compact = compact[:_SUMMARY_LIMIT - 3].rstrip() + "..."+ return f"phone_exec: {compact}"+++def _classifier_auto_run() -> bool:+ """True only when the user opted in to classifier-only auto-run.++ ``PHONE_HARNESS_CLASSIFIER_AUTO_RUN``, when set, wins over the plugin setting+ so one process can force the gate on or off. The default is off.+ """+ raw = os.environ.get(CLASSIFIER_AUTO_RUN_ENV)+ if raw is not None:+ return _truthy(raw)+ ctx = _plugin_ctx+ if ctx is None:+ return False+ try:+ value = ctx.get_config(CLASSIFIER_AUTO_RUN, False)+ except Exception:+ return False+ return _truthy(value)+++def _approve(message: str) -> dict:+ return {"action": "approve", "message": message, "rule_key": "phone_exec"}++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."}+ code = str((args or {}).get("code") or "")+ if _classifier_auto_run():+ reason = approval_reason(code)+ if reason is None:+ return None+ return _approve(+ f"phone_exec wants to run a script that {reason}, which reaches past the phone "+ "onto this computer. Classifier auto-run is a heuristic and can be bypassed."+ )+ return _approve(_script_summary(code))# ---------------------------------------------------------------------------------------------# The copy Hermes installed, and where its scripts keep notes.@@ -225,10 +421,51 @@ def _telemetry_opted_in() -> bool:return _truthy(data["telemetry"])+_SECRET_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET")+++def _scrub_secrets(base: dict) -> dict:+ """Copy ``base`` without ``*_API_KEY`` / ``*_TOKEN`` / ``*_SECRET``.++ PATH, HOME, ANDROID_* and everything else stay, so adb, iPhone Mirroring+ and a cloud phone still find the tools and accounts they need.+ """+ scrubbed = {}+ for key, value in base.items():+ if key.upper().endswith(_SECRET_SUFFIXES):+ continue+ scrubbed[key] = value+ return scrubbed+++def _base_child_env() -> dict:+ """Hermes's scrubbed subprocess env, or the suffix scrub when that is not importable.++ A failure inside Hermes's helper is raised: the phone tool should not silently+ fall back to an environment full of provider keys.+ """+ try:+ from tools.environments.local import hermes_subprocess_env+ except ImportError:+ return _scrub_secrets(dict(os.environ))+ env = hermes_subprocess_env()+ if not isinstance(env, dict):+ raise TypeError("hermes_subprocess_env() did not return a dict")+ return dict(env)++def _env(workspace: Path) -> dict:- """The script inherits Hermes's environment. An exported PHONE_HARNESS_PLATFORM is left- as it is. Telemetry is off unless the user explicitly opted in."""- env = dict(os.environ)+ """Environment for the phone-harness child.++ Starts from Hermes's scrubbed subprocess env when that module imports, otherwise+ from the process env minus ``*_API_KEY`` / ``*_TOKEN`` / ``*_SECRET``. Then sets+ the workspace and client, and puts back any ``PHONE_HARNESS_*`` the user exported.+ Telemetry stays off unless the user explicitly opted in.+ """+ env = _base_child_env()+ for key, value in os.environ.items():+ if key.startswith("PHONE_HARNESS_"):+ env[key] = valueenv["PH_AGENT_WORKSPACE"] = str(workspace)env["PH_CLIENT"] = "hermes"if not _telemetry_opted_in():@@ -266,9 +503,12 @@ def _kill_group(proc: subprocess.Popen) -> None:os.killpg(proc.pid, signal.SIGKILL)+def _payload(success: bool, **fields) -> dict:+ return {"success": success, **{k: v for k, v in fields.items() if v not in (None, "", [])}}++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)+ return json.dumps(_payload(success, **fields), ensure_ascii=False)def _timeout(value) -> int:@@ -278,10 +518,82 @@ def _timeout(value) -> int:return DEFAULT_TIMEOUT_S-_PNG = re.compile(r"(/[^\s'\"]+\.png)\b")+# Absolute PNG / JPEG / WebP paths. A relative path, or a suffix of one, does not count.+_IMAGE_PATH = re.compile(+ r"(?<![\w.])((?:[A-Za-z]:[\\/]|/)[^\s\"']+?\.(?:png|jpe?g|webp))(?![\w.])",+ re.IGNORECASE,+)+_IMAGE_MIME = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".webp": "image/webp",+}+++def _absolute_image(path: str) -> bool:+ if path.startswith(("/", "\\")):+ return True+ return len(path) >= 3 and path[0].isalpha() and path[1] == ":" and path[2] in "/\\"+++def _find_screenshot(stdout: str, since: float) -> str | None:+ """Last absolute image path in stdout that exists and was modified during this call.++ A one-second slack covers filesystems that store timestamps in whole seconds.+ """+ for path in reversed(_IMAGE_PATH.findall(stdout or "")):+ if not _absolute_image(path):+ continue+ try:+ if os.path.isfile(path) and os.path.getmtime(path) >= since - 1:+ return path+ except OSError:+ continue+ return None+++def _attach_screenshot(result: dict, path: str) -> dict | None:+ """Image tool result for a model that can view it, or None to keep the text result.++ A large image is reduced before it is attached. Any failure keeps the text result.+ """+ try:+ from tools.vision_tools import (+ _EMBED_MAX_DIMENSION,+ _resize_image_for_vision,+ _should_use_native_vision_fast_path,+ )+ from tools.vision_tools_history_budget import resolve_embed_target_bytes+ if not _should_use_native_vision_fast_path():+ return None+ mime = _IMAGE_MIME.get(Path(path).suffix.lower(), "image/png")+ data_url = _resize_image_for_vision(+ Path(path),+ mime_type=mime,+ max_base64_bytes=resolve_embed_target_bytes(),+ max_dimension=_EMBED_MAX_DIMENSION,+ force_jpeg=True,+ )+ if not isinstance(data_url, str) or not data_url.startswith("data:"):+ return None+ text = json.dumps(result, ensure_ascii=False)+ attached = text + "\n\nThe screenshot from this call is attached — inspect it with your native vision."+ return {+ "_multimodal": True,+ "text_summary": text,+ "meta": {"screenshot_path": path, "native_vision": True},+ "content": [+ {"type": "text", "text": attached},+ {"type": "image_url", "image_url": {"url": data_url}},+ ],+ }+ except Exception as exc:+ log.debug("screenshot attach failed, returning text: %s", exc)+ return None-def phone_exec(args: dict, **kwargs) -> str:+def phone_exec(args: dict, **kwargs) -> str | dict: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())")@@ -296,6 +608,7 @@ def phone_exec(args: dict, **kwargs) -> str:try:_seed_workspace(workspace)with _phone_lock(LOCK_WAIT_S):+ started = time.time()proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,text=True, encoding="utf-8", errors="replace",@@ -317,9 +630,15 @@ def phone_exec(args: dict, **kwargs) -> str: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))+ shot = _find_screenshot(out, started)+ payload = _payload(proc.returncode == 0, exit_code=proc.returncode, output=out[-OUTPUT_CAP:],+ stderr=(err or "").strip()[-STDERR_CAP:],+ screenshots=[shot] if shot else [], workspace=str(workspace))+ if shot:+ attached = _attach_screenshot(payload, shot)+ if attached is not None:+ return attached+ return json.dumps(payload, ensure_ascii=False)# ---------------------------------------------------------------------------------------------# Registration.@@ -374,6 +693,8 @@ def _register_skill(ctx) -> None:def register(ctx) -> None:+ global _plugin_ctx+ _plugin_ctx = ctxctx.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)diff --git a/integrations/hermes/plugin.yaml b/integrations/hermes/plugin.yamlindex 63f1175..bd71573 100644--- a/integrations/hermes/plugin.yaml+++ b/integrations/hermes/plugin.yaml@@ -11,4 +11,14 @@ provides_tools:provides_hooks:- pre_tool_callpython_dependencies:- - "phone-harness>=0.3.1,<0.4"+ - "phone-harness==0.3.1"+config_schema:+ classifier_auto_run:+ type: bool+ default: false+ description: >-+ Skip the approval prompt for scripts a classifier judges to be phone-only.+ The classifier is a heuristic and can be bypassed, so a script may still+ reach this computer. Leave this off unless you accept that. Off by default,+ every phone_exec call asks, and one session or always answer covers later+ calls in the session.diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pyindex 7748561..891a716 100644--- a/src/phone_harness/helpers.py+++ b/src/phone_harness/helpers.py@@ -118,13 +118,15 @@ def screen_info():def screenshot(path=None):- """Capture the screen to a PNG and return its path. View it to see the- phone; combine with screen() for coordinates.+ """Capture the screen to a PNG, print its path, and return it. View it+ to see the phone; combine with screen() for coordinates.- On iPhone Mirroring this still works when connection_state() is not- 'ready', as long as the mirroring window exists. Looking does not- press Connect."""+ The printed path is how a caller that only sees stdout can hand the+ image back. On iPhone Mirroring this still works when+ connection_state() is not 'ready', as long as the mirroring window+ exists. Looking does not press Connect."""p, _ = send("screen.capture", path=path)+ print(p)return pdiff --git a/src/phone_harness/remote.py b/src/phone_harness/remote.pyindex 2aeaee8..168c934 100644--- a/src/phone_harness/remote.py+++ b/src/phone_harness/remote.py@@ -12,6 +12,7 @@ Unsupported here, exactly as a local backend would."""import base64import json+import osimport tempfileimport urllib.errorimport urllib.request@@ -19,7 +20,6 @@ from pathlib import Pathfrom .transport import Backend, Unsupported-TMP = Path(tempfile.gettempdir()) / "phone-harness"USER_AGENT = "phone-harness-cli"@@ -152,8 +152,10 @@ class Remote(Backend):def _screen_capture(self, path=None):r = self._op("screen.capture", timeout=60)- TMP.mkdir(exist_ok=True)- path = Path(path or TMP / "remote.png")+ if path is None:+ fd, path = tempfile.mkstemp(prefix="phone-remote-", suffix=".png")+ os.close(fd)+ path = Path(path)path.write_bytes(base64.b64decode(r["png_b64"]))return str(path), r["bounds"]diff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex 100a97f..c4b063d 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -5,6 +5,7 @@ import ioimport osimport sysimport time+import typesfrom pathlib import Pathfrom . import telemetry@@ -364,22 +365,53 @@ def _dispatch_owned(name, rest):sys.exit(cli(rest))-def _exec_script():- global _phone_name- code = sys.stdin.read()- if not code.strip():- sys.exit(USAGE)- from . import helpers- _phone_name = getattr(helpers.phone, "name", None)+def _host_reaching(value):+ """Module and class objects a Hermes script must not receive already imported.++ helpers.py imports importlib, Path, the transport module and other host+ objects, and the script globals are a copy of that module. Under+ PH_CLIENT=hermes those are left out, so ``importlib.import_module("os")``+ and ``Path.home()`` are not sitting in the script. Path instances are left+ out too: ``Path.home`` works on them, and ``read_text`` reads this computer.+ Unsupported stays. It is the phone error scripts catch, not a way off the phone.+ """+ if isinstance(value, types.ModuleType):+ return True+ if isinstance(value, type):+ return not (value.__module__ == "phone_harness.transport" and value.__name__ == "Unsupported")+ if isinstance(value, Path):+ return True+ return False+++def _bind_globals(namespace):+ hermes = os.environ.get("PH_CLIENT") == "hermes"g = {}- for k, v in vars(helpers).items():+ for k, v in namespace.items():if k.startswith("_"):continue+ if hermes and _host_reaching(v):+ continueif callable(v) and not isinstance(v, type) and not getattr(v, "__ph_traced__", False):v = _traced(k, v)g[k] = vg["__name__"] = "__main__"- exec(code, g)+ return g+++def _script_globals():+ from . import helpers+ return _bind_globals(vars(helpers))+++def _exec_script():+ global _phone_name+ code = sys.stdin.read()+ if not code.strip():+ sys.exit(USAGE)+ from . import helpers+ _phone_name = getattr(helpers.phone, "name", None)+ exec(code, _script_globals())def _run(args):diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 1a51b2c..1f22d6c 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -184,6 +184,33 @@ class HelpAndFlags(unittest.TestCase):self.assertIn("42", got.stdout)self.assertNotIn("unrecognized arguments", got.stderr)+ def test_hermes_scripts_do_not_receive_host_modules_or_path(self):+ home = Path("/tmp") / "ph-hermes-globals"+ script = (+ "names = set(globals())\n"+ "for key in ('Path', 'importlib', 'transport', 'hashlib', 'time',\n"+ " 'AGENT_WORKSPACE', 'CORE_DIR', 'screen', 'send', 'Unsupported'):\n"+ " print(key, key in names)\n"+ )+ common = {+ "PHONE_HARNESS_HOME": str(home),+ "PH_AGENT_WORKSPACE": str(home / "ws"),+ "PHONE_HARNESS_PLATFORM": "android",+ }+ hermes = _run(stdin=script, env={**common, "PH_CLIENT": "hermes"})+ self.assertEqual(hermes.returncode, 0, hermes.stderr)+ got = dict(line.split() for line in hermes.stdout.splitlines() if line.strip())+ for key in ("Path", "importlib", "transport", "hashlib", "time", "AGENT_WORKSPACE", "CORE_DIR"):+ self.assertEqual(got[key], "False", key)+ for key in ("screen", "send", "Unsupported"):+ self.assertEqual(got[key], "True", key)++ plain = _run(stdin=script, env={**common, "PH_CLIENT": ""})+ self.assertEqual(plain.returncode, 0, plain.stderr)+ plain_got = dict(line.split() for line in plain.stdout.splitlines() if line.strip())+ for key in ("Path", "importlib", "transport", "AGENT_WORKSPACE"):+ self.assertEqual(plain_got[key], "True", key)+class _stderr:"""Patch sys.stderr for one cloud.cli call."""diff --git a/tests/test_hermes_plugin.py b/tests/test_hermes_plugin.pyindex 38b6744..6b4fdb2 100644--- a/tests/test_hermes_plugin.py+++ b/tests/test_hermes_plugin.py@@ -15,6 +15,7 @@ import subprocessimport sysimport tempfileimport time+import typesimport unittestfrom pathlib import Pathfrom typing import Any@@ -39,6 +40,7 @@ class FakeCtx:def __init__(self):self.tools, self.hooks, self.skills = {}, {}, {}+ self.settings = {}def register_tool(self, name, toolset, schema, handler, **kw):self.tools[name] = dict(toolset=toolset, schema=schema, handler=handler, **kw)@@ -49,6 +51,9 @@ class FakeCtx:def register_skill(self, name, path, description="", frontmatter=None):self.skills[name] = {"path": path, "description": description, "frontmatter": dict(frontmatter or {})}+ def get_config(self, key, default=None):+ return self.settings.get(key, default)+class Base(unittest.TestCase):def setUp(self):@@ -63,9 +68,71 @@ class Base(unittest.TestCase):self.plugin._packaged_skill = lambda: Noneself.ctx = FakeCtx()self.plugin.register(self.ctx)+ # The suffix scrub, not a Hermes install that may or may not be on this machine.+ self._saved_modules = {name: sys.modules.get(name) for name in (+ "tools", "tools.environments", "tools.environments.local",+ "tools.vision_tools", "tools.vision_tools_history_budget",+ )}+ tools = types.ModuleType("tools")+ tools.__path__ = []+ environments = types.ModuleType("tools.environments")+ environments.__path__ = []+ local = types.ModuleType("tools.environments.local")+ tools.environments = environments+ environments.local = local+ sys.modules["tools"] = tools+ sys.modules["tools.environments"] = environments+ sys.modules["tools.environments.local"] = local+ sys.modules.pop("tools.vision_tools", None)+ sys.modules.pop("tools.vision_tools_history_budget", None)+ self.addCleanup(self._restore_modules)++ def _restore_modules(self):+ for name, module in self._saved_modules.items():+ if module is None:+ sys.modules.pop(name, None)+ else:+ sys.modules[name] = moduledef run_tool(self, code, **args):- return json.loads(self.plugin.phone_exec({"code": code, **args}))+ result = self.plugin.phone_exec({"code": code, **args})+ if isinstance(result, dict) and result.get("_multimodal"):+ result = result["text_summary"]+ return json.loads(result)++ def save_code(self, path: Path) -> str:+ return (+ "from pathlib import Path\n"+ f"p = Path({str(path)!r})\n"+ "p.write_bytes(b'img')\n"+ "print(p)\n"+ )++ def install_vision(self, *, native=True, resize=None, embed_bytes=256_000, max_dimension=1568):+ tools = sys.modules["tools"]+ vision = types.ModuleType("tools.vision_tools")+ budget = types.ModuleType("tools.vision_tools_history_budget")+ calls = []++ def default_resize(path, mime_type=None, max_base64_bytes=None, max_dimension=None, force_jpeg=False):+ calls.append({+ "path": Path(path),+ "mime_type": mime_type,+ "max_base64_bytes": max_base64_bytes,+ "max_dimension": max_dimension,+ "force_jpeg": force_jpeg,+ })+ return "data:image/jpeg;base64,qq"++ vision._EMBED_MAX_DIMENSION = max_dimension+ vision._should_use_native_vision_fast_path = lambda: native+ vision._resize_image_for_vision = resize or default_resize+ budget.resolve_embed_target_bytes = lambda: embed_bytes+ tools.vision_tools = vision+ tools.vision_tools_history_budget = budget+ sys.modules["tools.vision_tools"] = vision+ sys.modules["tools.vision_tools_history_budget"] = budget+ return callsclass Registration(Base):@@ -80,6 +147,8 @@ class Registration(Base):description = self.ctx.tools["phone_exec"]["schema"]["description"]self.assertIn("ensure_device()", description)self.assertIn("screen()", description)+ self.assertIn("screenshot()", description)+ self.assertIn("attached", description)self.assertIn("phone-harness:phone-harness", description)self.assertIn("passwords", description)self.assertNotIn("scroll_until", description)@@ -88,33 +157,90 @@ class Registration(Base):class ApprovalGate(Base):PHONE_ONLY = ['ensure_device()\nprint([o["text"] for o in screen()][:10])',- 'import json, re, time\nprint(json.dumps(screen_info()))',+ 'from phone_harness.helpers import screen\nprint(screen())','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+ 'import phone_harness.helpers as helpers\nprint(helpers.screen_info())',+ 'send("screen.text")',+ 'send("input.tap", x=1, y=2)',+ 'send("input.text", s="raw")',+ 's = send\ns("screen.capture")',+ 'def (', # a SyntaxError cannot run, so the classifier has 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")',+ "import os", "import json", "import subprocess", "import os.path", "from os import path",+ "from collections import Counter",+ "import Quartz", "import phone_harness", "import phone_harness.transport",+ "from phone_harness import transport", "from phone_harness.helpers import Path",+ "from phone_harness.helpers import importlib", "from . import agent_helpers",+ 'open("notes.txt", "w").write("x")', '__import__("os")', 'eval("1")',+ "print.__self__", 'getattr(print, "__self__")', 'shell("pm list packages")',+ 'send("raw", cmd="id")', 'send(op="raw")', 'op = "raw"\nsend(op)',+ 'f = open\nf("/etc/passwd")', 's = send\ns("raw", cmd="id")',+ 'phone.send("raw", cmd="id")',+ 'from phone_harness.helpers import shell as sh\nsh("id")',+ 'a = open\nb = a\nb("x")',+ 'import phone_harness.helpers as helpers\nprint(helpers.Path.home())',]+ def setUp(self):+ super().setUp()+ self._saved_auto = os.environ.pop(self.plugin.CLASSIFIER_AUTO_RUN_ENV, None)+ self.addCleanup(self._restore_auto)++ def _restore_auto(self):+ if self._saved_auto is None:+ os.environ.pop(self.plugin.CLASSIFIER_AUTO_RUN_ENV, None)+ else:+ os.environ[self.plugin.CLASSIFIER_AUTO_RUN_ENV] = self._saved_auto+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):+ def test_every_phone_exec_asks_by_default(self):+ for code in self.PHONE_ONLY + self.PAST_THE_PHONE:+ with self.subTest(code=code):+ directive = self.hook(code)+ self.assertEqual(directive["action"], "approve")+ self.assertEqual(directive["rule_key"], "phone_exec")+ self.assertIn("phone_exec", directive["message"])+ self.assertLessEqual(len(directive["message"]), 180)++ def test_the_default_message_describes_the_script(self):+ directive = self.hook('ensure_device()\nprint(screen())')+ self.assertIn("ensure_device()", directive["message"])+ self.assertIn("print(screen())", directive["message"])++ def test_phone_only_scripts_are_quiet_only_after_opt_in(self):+ os.environ[self.plugin.CLASSIFIER_AUTO_RUN_ENV] = "1"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):+ def test_opt_in_still_asks_for_scripts_that_reach_past_the_phone(self):+ os.environ[self.plugin.CLASSIFIER_AUTO_RUN_ENV] = "1"for code in self.PAST_THE_PHONE:with self.subTest(code=code):- self.assertIsNotNone(self.plugin.approval_reason(code))+ self.assertIsNotNone(self.plugin.approval_reason(code), code)directive = self.hook(code)self.assertEqual(directive["action"], "approve")+ self.assertEqual(directive["rule_key"], "phone_exec")self.assertIn("phone_exec", directive["message"])+ self.assertIn("heuristic", directive["message"])++ def test_the_plugin_setting_opts_into_auto_run_when_the_env_var_is_unset(self):+ self.ctx.settings[self.plugin.CLASSIFIER_AUTO_RUN] = True+ self.assertIsNone(self.hook("print(screen())"))+ asked = self.hook('send("raw", cmd="id")')+ self.assertEqual(asked["rule_key"], "phone_exec")+ self.assertEqual(asked["action"], "approve")++ def test_an_explicit_env_var_off_beats_the_plugin_setting(self):+ self.ctx.settings[self.plugin.CLASSIFIER_AUTO_RUN] = True+ os.environ[self.plugin.CLASSIFIER_AUTO_RUN_ENV] = "0"+ directive = self.hook("print(screen())")+ self.assertEqual(directive["action"], "approve")+ self.assertEqual(directive["rule_key"], "phone_exec")def test_other_tools_are_left_alone(self):self.assertIsNone(self.hook("import os", tool="terminal"))@@ -146,6 +272,64 @@ class Environment(Base):self.assertNotIn("PHONE_HARNESS_PLATFORM", env)self.assertEqual(env["PHONE_HARNESS_TELEMETRY"], "0")+ def test_secret_suffixes_are_removed_and_phone_harness_vars_stay(self):+ saved = dict(os.environ)+ self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))+ os.environ["OPENAI_API_KEY"] = "sk-test"+ os.environ["GH_TOKEN"] = "ghp-test"+ os.environ["DB_SECRET"] = "s3cret"+ os.environ["openai_api_key"] = "sk-lower"+ os.environ["PHONE_HARNESS_PLATFORM"] = "android"+ os.environ["PHONE_HARNESS_CUSTOM"] = "kept"+ os.environ["PHONE_HARNESS_API_KEY"] = "ph-key"+ os.environ["PATH"] = "/usr/bin:/bin"+ os.environ["HOME"] = "/home/me"+ os.environ["ANDROID_HOME"] = "/opt/android"+ os.environ["ANDROID_SERIAL"] = "emulator-5554"+ env = self.plugin._env(self.data / "ws")+ for gone in ("OPENAI_API_KEY", "GH_TOKEN", "DB_SECRET", "openai_api_key"):+ self.assertNotIn(gone, env)+ self.assertEqual(env["PHONE_HARNESS_PLATFORM"], "android")+ self.assertEqual(env["PHONE_HARNESS_CUSTOM"], "kept")+ self.assertEqual(env["PHONE_HARNESS_API_KEY"], "ph-key")+ self.assertEqual(env["PATH"], "/usr/bin:/bin")+ self.assertEqual(env["HOME"], "/home/me")+ self.assertEqual(env["ANDROID_HOME"], "/opt/android")+ self.assertEqual(env["ANDROID_SERIAL"], "emulator-5554")+ self.assertEqual(env["PH_CLIENT"], "hermes")+ self.assertEqual(env["PH_AGENT_WORKSPACE"], str(self.data / "ws"))++ def test_hermes_subprocess_env_is_used_when_it_imports(self):+ saved = dict(os.environ)+ self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))+ os.environ["OPENAI_API_KEY"] = "sk-test"+ os.environ["PHONE_HARNESS_PLATFORM"] = "ios"+ os.environ["PHONE_HARNESS_CUSTOM"] = "kept"+ os.environ["PHONE_HARNESS_API_KEY"] = "ph-key"+ os.environ.pop("PHONE_HARNESS_TELEMETRY", None)+ os.environ["PHONE_HARNESS_HOME"] = str(self.data)++ def hermes_subprocess_env():+ return {"PATH": "/from-hermes", "HOME": "/home/hermes", "ANDROID_SERIAL": "emulator-5554",+ "LANG": "C"}++ sys.modules["tools.environments.local"].hermes_subprocess_env = hermes_subprocess_env+ env = self.plugin._env(self.data / "ws")+ self.assertEqual(env["PATH"], "/from-hermes")+ self.assertEqual(env["HOME"], "/home/hermes")+ self.assertEqual(env["ANDROID_SERIAL"], "emulator-5554")+ self.assertNotIn("OPENAI_API_KEY", env)+ self.assertEqual(env["PHONE_HARNESS_PLATFORM"], "ios")+ self.assertEqual(env["PHONE_HARNESS_CUSTOM"], "kept")+ self.assertEqual(env["PHONE_HARNESS_API_KEY"], "ph-key")+ self.assertEqual(env["PH_CLIENT"], "hermes")+ self.assertEqual(env["PHONE_HARNESS_TELEMETRY"], "0")++ def test_a_bad_hermes_subprocess_env_fails_loudly(self):+ sys.modules["tools.environments.local"].hermes_subprocess_env = lambda: ["not", "a", "dict"]+ with self.assertRaises(TypeError):+ self.plugin._env(self.data / "ws")+class Workspace(unittest.TestCase):def setUp(self):@@ -375,11 +559,156 @@ class Running(Base):self.assertEqual(result["exit_code"], 1)self.assertIn("iPhone in Use", result["stderr"])- def test_screenshot_paths_in_the_output_are_listed(self):+ def test_a_screenshot_written_during_the_call_is_listed(self):shot = self.data / "shot.png"- shot.write_bytes(b"\x89PNG")- result = self.run_tool(f"print('saved {shot}')")+ result = self.run_tool(self.save_code(shot))self.assertEqual(result["screenshots"], [str(shot)])+ self.assertTrue(shot.is_file())++ def test_an_image_path_on_stderr_is_not_attached(self):+ calls = self.install_vision()+ shot = self.data / "err.png"+ code = (+ "import sys\n"+ "from pathlib import Path\n"+ f"p = Path({str(shot)!r})\n"+ "p.write_bytes(b'img')\n"+ "sys.stderr.write(str(p) + '\\n')\n"+ "print('done')\n"+ )+ raw = self.plugin.phone_exec({"code": code})+ self.assertIsInstance(raw, str)+ self.assertNotIn("screenshots", json.loads(raw))+ self.assertEqual(calls, [])++ def test_an_older_image_path_is_not_this_call(self):+ shot = self.data / "old.png"+ shot.write_bytes(b"png")+ old = time.time() - 30+ os.utime(shot, (old, old))+ result = self.run_tool(f"print({str(shot)!r})")+ self.assertNotIn("screenshots", result)++ def test_only_an_absolute_image_from_this_call_counts(self):+ missing = "/no/such/phone-harness-shot.png"+ code = (+ "print('shot.png')\n"+ "print('./nested.jpg')\n"+ f"print({missing!r})\n"+ "print('https://cdn.example/a.png')\n"+ "print('/tmp/notes.png.bak')\n"+ )+ result = self.run_tool(code)+ self.assertNotIn("screenshots", result)+ found = self.plugin._IMAGE_PATH.findall(+ r"C:\shots\a.JPEG /tmp/b.webp shot.png ./c.jpg '/tmp/e.png' /tmp/a.png.bak"+ )+ self.assertIn(r"C:\shots\a.JPEG", found)+ self.assertIn("/tmp/b.webp", found)+ self.assertIn("/tmp/e.png", found)+ self.assertNotIn("shot.png", found)+ self.assertNotIn("./c.jpg", found)+ self.assertFalse(any(item.endswith("c.jpg") or item.endswith(".bak") for item in found))++ def test_the_last_fresh_image_is_the_one_kept(self):+ first = self.data / "first.png"+ second = self.data / "second.jpg"+ stale = self.data / "stale.webp"+ stale.write_bytes(b"old")+ os.utime(stale, (time.time() - 30, time.time() - 30))+ code = self.save_code(first) + self.save_code(second) + f"print({str(stale)!r})\n"+ result = self.run_tool(code)+ self.assertEqual(result["screenshots"], [str(second)])++ def test_a_screenshot_is_attached_when_the_model_can_view_images(self):+ cases = (+ ("live.png", "image/png"),+ ("live.jpg", "image/jpeg"),+ ("live.jpeg", "image/jpeg"),+ ("live.webp", "image/webp"),+ ("live.PNG", "image/png"),+ )+ for name, mime in cases:+ with self.subTest(name=name):+ calls = self.install_vision(embed_bytes=1234, max_dimension=1568)+ shot = self.data / name+ raw = self.plugin.phone_exec({"code": self.save_code(shot)})+ self.assertIsInstance(raw, dict)+ self.assertTrue(raw["_multimodal"])+ self.assertEqual(raw["meta"], {"screenshot_path": str(shot), "native_vision": True})+ self.assertEqual(raw["content"][0]["type"], "text")+ self.assertIn("inspect it with your native vision", raw["content"][0]["text"])+ self.assertEqual(raw["content"][1], {+ "type": "image_url",+ "image_url": {"url": "data:image/jpeg;base64,qq"},+ })+ summary = json.loads(raw["text_summary"])+ self.assertEqual(summary["screenshots"], [str(shot)])+ self.assertTrue(summary["success"])+ self.assertEqual(calls, [{+ "path": shot,+ "mime_type": mime,+ "max_base64_bytes": 1234,+ "max_dimension": 1568,+ "force_jpeg": True,+ }])++ def test_a_failed_script_still_attaches_the_screenshot_it_saved(self):+ calls = self.install_vision()+ shot = self.data / "then-fail.png"+ raw = self.plugin.phone_exec({"code": self.save_code(shot) + "raise SystemExit(2)\n"})+ self.assertIsInstance(raw, dict)+ summary = json.loads(raw["text_summary"])+ self.assertFalse(summary["success"])+ self.assertEqual(summary["exit_code"], 2)+ self.assertEqual(summary["screenshots"], [str(shot)])+ self.assertEqual(calls[0]["path"], shot)++ def test_attach_falls_back_to_text_when_the_model_cannot_view_images(self):+ calls = self.install_vision(native=False)+ shot = self.data / "text-only.png"+ raw = self.plugin.phone_exec({"code": self.save_code(shot)})+ self.assertIsInstance(raw, str)+ payload = json.loads(raw)+ self.assertEqual(payload["screenshots"], [str(shot)])+ self.assertNotIn("_multimodal", payload)+ self.assertEqual(calls, [])++ def test_attach_falls_back_to_text_when_resizing_fails(self):+ def boom(*args, **kwargs):+ raise RuntimeError("cannot read image")++ self.install_vision(resize=boom)+ shot = self.data / "broken.png"+ raw = self.plugin.phone_exec({"code": self.save_code(shot)})+ self.assertIsInstance(raw, str)+ payload = json.loads(raw)+ self.assertEqual(payload["screenshots"], [str(shot)])+ self.assertNotIn("data:image", raw)++ def test_attach_falls_back_to_text_when_the_image_data_is_unusable(self):+ self.install_vision(resize=lambda *args, **kwargs: "")+ shot = self.data / "empty.png"+ raw = self.plugin.phone_exec({"code": self.save_code(shot)})+ self.assertIsInstance(raw, str)+ self.assertEqual(json.loads(raw)["screenshots"], [str(shot)])++ def test_attach_falls_back_to_text_when_vision_support_is_missing(self):+ shot = self.data / "plain.png"+ raw = self.plugin.phone_exec({"code": self.save_code(shot)})+ self.assertIsInstance(raw, str)+ self.assertEqual(json.loads(raw)["screenshots"], [str(shot)])++ def test_a_file_modified_within_the_timestamp_slack_counts(self):+ shot = self.data / "edge.png"+ shot.write_bytes(b"x")+ # Whole-second filesystems can store the mtime a second early. A file+ # written just before the check stays inside that slack; one from+ # several seconds ago does not.+ self.assertEqual(self.plugin._find_screenshot(str(shot), time.time()), str(shot))+ old = time.time() - 10+ os.utime(shot, (old, old))+ self.assertIsNone(self.plugin._find_screenshot(str(shot), time.time()))def test_empty_code_and_a_missing_module_are_errors_not_crashes(self):self.assertFalse(self.run_tool(" ")["success"])@@ -404,3 +733,26 @@ class Running(Base):self.assertFalse(busy["success"])self.assertIn("busy", busy["error"])self.assertTrue(self.run_tool("print('after')")["success"]) # the lock was released+++class PluginManifest(unittest.TestCase):+ def test_the_package_pin_is_exact_and_the_plugin_version_stays(self):+ text = (PLUGIN_INIT.parent / "plugin.yaml").read_text(encoding="utf-8")+ self.assertIn("\nversion: 0.1.0\n", text)+ self.assertIn("phone-harness==0.3.1", text)+ self.assertNotIn(">=", text)+ self.assertIn("classifier_auto_run:", text)+ self.assertIn("heuristic", text)+ self.assertIn("bypass", text)++ def test_the_readme_says_every_run_asks_and_describes_the_opt_in(self):+ text = (PLUGIN_INIT.parent / "README.md").read_text(encoding="utf-8")+ self.assertIn("Every `phone_exec` call asks", text)+ self.assertIn("classifier_auto_run", text)+ self.assertIn("PHONE_HARNESS_CLASSIFIER_AUTO_RUN", text)+ self.assertIn("heuristic", text)+ self.assertIn("bypassed", text)+ self.assertNotIn("never ask", text)+ self.assertIn("attached to the tool result", text)+ self.assertIn("screenshots", text)+ self.assertIn("`screenshot()` prints the path", text)diff --git a/tests/test_remote.py b/tests/test_remote.pynew file mode 100644index 0000000..5c86154--- /dev/null+++ b/tests/test_remote.py@@ -0,0 +1,51 @@+"""Cloud-phone screenshots use a private temp file, not a fixed path."""+import base64+import os+import sys+import tempfile+import unittest+from pathlib import Path++SRC = Path(__file__).resolve().parents[1] / "src"+if str(SRC) not in sys.path:+ sys.path.insert(0, str(SRC))++from phone_harness.remote import Remote # noqa: E402+++class RemoteCapture(unittest.TestCase):+ def setUp(self):+ self.remote = Remote("https://example.invalid", "token")+ self.png = b"\x89PNG-test"+ self.remote._op = lambda *args, **kwargs: {+ "png_b64": base64.b64encode(self.png).decode("ascii"),+ "bounds": {"x": 0, "y": 0, "w": 2, "h": 3},+ }+ self.made = []++ def tearDown(self):+ for path in self.made:+ try:+ os.unlink(path)+ except OSError:+ pass++ def test_screenshot_uses_mkstemp_not_a_fixed_name(self):+ fixed = Path(tempfile.gettempdir()) / "phone-harness" / "remote.png"+ first, bounds = self.remote._screen_capture()+ second, _ = self.remote._screen_capture()+ self.made.extend((first, second))+ self.assertEqual(bounds, {"x": 0, "y": 0, "w": 2, "h": 3})+ for path in (first, second):+ self.assertTrue(path.endswith(".png"))+ self.assertIn("phone-remote-", Path(path).name)+ self.assertNotEqual(Path(path).resolve(), fixed.resolve())+ self.assertEqual(Path(path).read_bytes(), self.png)+ self.assertNotEqual(first, second)++ def test_an_explicit_path_is_honored(self):+ dest = Path(tempfile.mkdtemp()) / "chosen.png"+ self.addCleanup(lambda: (dest.unlink(missing_ok=True), dest.parent.rmdir()))+ path, _ = self.remote._screen_capture(path=dest)+ self.assertEqual(Path(path), dest)+ self.assertEqual(dest.read_bytes(), self.png)diff --git a/tests/test_skill.py b/tests/test_skill.pyindex 44be738..a4b853f 100644--- a/tests/test_skill.py+++ b/tests/test_skill.py@@ -63,9 +63,25 @@ class SkillOutput(unittest.TestCase):self.assertIn("The main helpers are listed in [Helpers](#helpers).", text)self.assertIn("\n## Helpers\n", text)self.assertIn("`screen(min_confidence=0.3)`", text)+ self.assertIn("`screenshot(path=None)` - Capture the screen to a PNG, print its path, and return it.", text)self.assertIn("`screen_info()`", text)self.assertNotIn("ocr()", text)+ def test_screenshot_prints_the_path_it_returns(self):+ import contextlib++ from phone_harness import helpers++ path = "/tmp/phone-harness-example.png"+ saved = helpers.send+ helpers.send = lambda op, **kw: (path, {"w": 1})+ self.addCleanup(setattr, helpers, "send", saved)+ buf = io.StringIO()+ with contextlib.redirect_stdout(buf):+ returned = helpers.screenshot()+ self.assertEqual(returned, path)+ self.assertEqual(buf.getvalue().strip(), path)+def test_screen_is_the_name_of_ocr(self):from phone_harness.helpers import ocr, screenself.assertIs(ocr, screen)