Skip to content

let your agent control your phone

OpenClaw plugin 0.1.1: whole-script approval, full stop on timeout, new summary (PHO-99, PHO-90) (#174)

shawn pana61bffa04fd95
diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.md
index 7312441..d45023b 100644
--- a/integrations/openclaw/README.md
+++ b/integrations/openclaw/README.md
@@ -31,17 +31,13 @@ again with `--accept-capabilities` once you have reviewed the plugin. A running
Gateway picks the plugin up straight away, so there is nothing to restart. The
first script fetches Phone Harness through uv, which takes a moment once.
-Phone Harness sends usage telemetry by default, including your script text and
-what scripts print. [Telemetry](#telemetry) says what is sent and how to turn it
-off.
-
To install from a checkout instead:
```bash
git clone https://github.com/phone-harness/phone-harness
cd phone-harness/integrations/openclaw
npm install --ignore-scripts && npm pack
-openclaw plugins install npm-pack:./phone-harness-0.1.0.tgz
+openclaw plugins install npm-pack:./phone-harness-0.1.1.tgz
```
To use a cloud phone, sign in once on the Gateway machine:
@@ -67,8 +63,9 @@ needs adb. [install.md](../../install.md) covers each.
## Approvals
-Every `phone_exec` call asks you before it runs. You see the script, or both ends
-of it if it is long, and choose:
+Every `phone_exec` call asks you before it runs. The prompt shows the whole
+script, with each run of spaces and line breaks shown as one space and any
+invisible character spelled out, and you choose:
- **Allow once** runs this script.
- **Always allow** runs this script and every later script in the same session.
@@ -80,6 +77,11 @@ Approve from the Control UI, or in a chat with `/approve`. If nobody can answer,
the script does not run. That includes `openclaw agent` from a terminal and
scheduled jobs. A prompt nobody answers expires after five minutes.
+OpenClaw holds 512 characters in a prompt, so a script longer than 500 as shown
+is not offered for approval at all. The agent is told to split it into shorter
+scripts, and the phone keeps its state between them. With classifier auto-run on,
+the reason takes part of the prompt, so a script that asks has less room.
+
Only the owner can drive the phone. OpenClaw lets a chat answer its own approval
prompts, so a sender it knows is not the owner is refused before any prompt.
@@ -99,7 +101,6 @@ prompts, so a sender it knows is not the owner is refused before any prompt.
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 first.
-- Telemetry is on by default. See [Telemetry](#telemetry).
- `PHONE_HARNESS_PLATFORM`, when you have exported it, is passed through.
- The agent workspace is `phone-harness/agent-workspace` in OpenClaw's state
directory, or `PH_AGENT_WORKSPACE` if that is set.
@@ -107,7 +108,8 @@ prompts, so a sender it knows is not the owner is refused before any prompt.
## How it works
1. The model calls `phone_exec(code, timeout_s=300)`. The limit is 1800 seconds.
-2. A `before_tool_call` hook asks you to approve the script.
+2. A `before_tool_call` hook shows you the whole script and asks you to approve
+ it, or refuses a script too long to show whole.
3. Subagents take turns on the phone. After 120 s the tool reports it as busy.
4. The plugin pipes the script to the pinned Phone Harness through `uvx`, with
`PH_AGENT_WORKSPACE` and `PH_CLIENT=openclaw`. The script's environment leaves
@@ -115,9 +117,17 @@ prompts, so a sender it knows is not the owner is refused before any prompt.
secrets, passwords), but keeps any `PHONE_HARNESS_*` you exported.
5. The result is what the script printed, plus the exit code and the tail of
stderr. A screenshot saved during the call is attached for the model to see.
- If the file is not a real image, the result says so and nothing is attached. A
- script past its timeout, or a cancelled call, is killed with everything it
- started.
+ If the file is not a real image, the result says so and nothing is attached.
+6. A script past its timeout, or a cancelled call, is stopped with every process
+ it started. Each run tags its processes with an environment variable, and the
+ plugin notes which processes it sees under the script. Stopping kills the
+ script's process tree, including processes in their own session or process
+ group, every process that carries the tag or was noted, even after its parent
+ exits, and their process groups, and repeats until none is left, for up to five
+ seconds. The phone is free again only then. On Windows, the process tree is
+ killed. A process that detaches before the plugin notes it can outlive the call
+ if it drops the tag, or on macOS if it is one of Apple's own programs, whose
+ environment macOS hides.
## What it touches
@@ -127,42 +137,6 @@ prompts, so a sender it knows is not the owner is refused before any prompt.
- A cloud phone streams its screen to Phone Harness Cloud and uses Phone Harness's
own cloud sign-in. A rented cloud Android bills by the minute.
-## Telemetry
-
-Telemetry is on by default. Phone Harness sends usage telemetry to PostHog
-(`us.i.posthog.com`). One event goes out after each `phone_exec` call and each
-`phone-harness` command. It holds:
-
-- The script text, up to 20,000 characters, including its `# task:` and `# step:` comments.
-- What the script printed, up to the last 20,000 characters. If a script prints
- text from the phone's screen, that text is sent.
-- Each helper call and its arguments, up to 500 calls. Text a script types on the
- phone is one of those arguments.
-- The command line, errors, exit code and run time.
-- A random install id, the Phone Harness, Python and OS versions, the kind of phone,
- and the client (`openclaw`).
-- Once you sign in to Phone Harness Cloud: your account id and the cloud session id.
- Calls to Phone Harness Cloud also carry the Phone Harness version and the client.
-
-Screenshots are not sent.
-
-To turn it off, use either of these on the machine that runs the Gateway:
-
-- `phone-harness config set telemetry false`. If `phone-harness` is not on your
- PATH, run `uvx phone-harness config set telemetry false`. The setting is per
- user, so run it as the user the Gateway runs as.
-- `DO_NOT_TRACK=1` in the Gateway's own environment. `PHONE_HARNESS_TELEMETRY=0`
- does the same. A Gateway running as a service needs it set in the service, not
- in your shell.
-
-With either one, Phone Harness sends no event and adds nothing to its calls to the
-cloud.
-
-A cloud phone is the one exception. Phone Harness Cloud keeps its own activity log
-of cloud sessions, tied to your account: each action and what it was asked to do,
-such as the text typed, the app or the URL. These settings do not change that log.
-Local phones are not in it.
-
## Limits
- The approval covers `phone_exec`. An agent that also has OpenClaw's `exec` tool
@@ -184,3 +158,7 @@ npm test
The Phone Harness release is pinned on one line: `PHONE_HARNESS_VERSION` at the
top of `src/phone-exec.ts`. `classifier.py` is the Hermes plugin's classifier, and
`tests/test_openclaw_plugin.py` keeps the two identical.
+
+Phone Harness sends usage data, including scripts and what they print, to PostHog.
+To turn it off, set `DO_NOT_TRACK=1` in the Gateway's environment, or run
+`uvx phone-harness config set telemetry false` as the user the Gateway runs as.
diff --git a/integrations/openclaw/package-lock.json b/integrations/openclaw/package-lock.json
index 308102d..f8da4e8 100644
--- a/integrations/openclaw/package-lock.json
+++ b/integrations/openclaw/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "phone-harness",
- "version": "0.1.0",
+ "version": "0.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "phone-harness",
- "version": "0.1.0",
+ "version": "0.1.1",
"license": "MIT",
"dependencies": {
"typebox": "1.3.37"
diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json
index 0d4f440..58b83e2 100644
--- a/integrations/openclaw/package.json
+++ b/integrations/openclaw/package.json
@@ -1,7 +1,7 @@
{
"name": "phone-harness",
- "version": "0.1.0",
- "description": "Drive a real phone from OpenClaw with one phone_exec tool. Sends usage telemetry, including script text and output, by default; DO_NOT_TRACK=1 turns it off.",
+ "version": "0.1.1",
+ "description": "Lets OpenClaw use a real phone: scroll, tap, type, and read the screen, with no jailbreak and nothing installed on the phone.",
"type": "module",
"license": "MIT",
"homepage": "https://phone-harness.com",
diff --git a/integrations/openclaw/src/approval.test.ts b/integrations/openclaw/src/approval.test.ts
index 5711db9..ef7f92e 100644
--- a/integrations/openclaw/src/approval.test.ts
+++ b/integrations/openclaw/src/approval.test.ts
@@ -7,8 +7,11 @@ import {
CLASSIFIER_AUTO_RUN_ENV,
classifierAutoRun,
classifyWithPython,
+ approvalDescription,
createApprovalGate,
- scriptSummary,
+ DESCRIPTION_LIMIT,
+ MAX_SHOWN_CHARS,
+ shownScript,
} from "./approval.ts";
const OWNER = { sessionId: "s1", sessionKey: "agent:main:main", requester: { senderIsOwner: true } };
@@ -52,17 +55,42 @@ describe("the prompt", () => {
assert.ok(prompt.timeoutMs <= 600_000);
});
- it("keeps both ends of a long script, so padding cannot hide how it ends", async () => {
- const code = `ensure_device() # ${"x".repeat(5000)}\nopen('/etc/passwd')`;
+ it("shows the whole of the longest script that fits", async () => {
+ const code = `print(${"1".repeat(MAX_SHOWN_CHARS - 7)})`;
+ assert.equal(code.length, MAX_SHOWN_CHARS);
const prompt = approval(await gate()({ ...CALL, params: { code } }, OWNER));
- assert.ok(prompt.description.length <= 512);
- assert.ok(prompt.description.startsWith("phone_exec: ensure_device()"));
- assert.ok(prompt.description.endsWith("open('/etc/passwd')"));
- assert.match(prompt.description, /\d+ characters hidden/);
+ assert.equal(prompt.description, `phone_exec: ${code}`);
+ assert.equal(prompt.description.length, DESCRIPTION_LIMIT);
+ });
+
+ it("refuses a script too long to show whole, and never shows part of one", async () => {
+ // Padding in the middle used to drop out of a cut-down prompt. Now nothing is cut.
+ const code = `ensure_device()\n# ${"x".repeat(5000)}\nopen('/etc/passwd')`;
+ const result = await gate()({ ...CALL, params: { code } }, OWNER);
+ assert.ok(result && "block" in result, "expected a refusal, not a prompt");
+ assert.match(result.blockReason, new RegExp(`is ${shownScript(code).length} characters`));
+ assert.match(result.blockReason, new RegExp(`holds ${MAX_SHOWN_CHARS}\\b`));
+ assert.match(result.blockReason, /Split the work into shorter phone_exec calls/);
+ assert.equal(approvalDescription(code), null);
+ });
+
+ it("counts a run of whitespace as one character", async () => {
+ const code = `print(1)${" \n\t".repeat(10_000)}print(2)`;
+ const prompt = approval(await gate()({ ...CALL, params: { code } }, OWNER));
+ assert.equal(prompt.description, "phone_exec: print(1) print(2)");
+ });
+
+ it("spells out control and invisible characters instead of hiding them", async () => {
+ // A right-to-left override, a zero-width space, an escape and a line separator.
+ const code = "print('ok') #\u202e evil\u200b\u001b\u2028x";
+ const prompt = approval(await gate()({ ...CALL, params: { code } }, OWNER));
+ assert.equal(prompt.description, "phone_exec: print('ok') #\\u{202e} evil\\u{200b}\\u{1b}\\u{2028}x");
+ assert.doesNotMatch(prompt.description, /[\u202e\u200b\u001b\u2028]/);
});
it("has something to show for an empty or malformed call", () => {
- assert.equal(scriptSummary(""), "phone_exec: (empty)");
+ assert.equal(shownScript(""), "(empty)");
+ assert.equal(approvalDescription(""), "phone_exec: (empty)");
});
});
@@ -143,6 +171,15 @@ describe("classifier auto-run", () => {
assert.ok(prompt.description.length <= 512);
});
+ it("refuses a flagged script too long to show beside the reason", async () => {
+ const code = `import os\n${"print(1)\n".repeat(48)}`;
+ assert.ok(shownScript(code).length < MAX_SHOWN_CHARS, "short enough for a plain prompt");
+ const before = gate({ autoRun: () => true, classify: async () => "imports os" });
+ const result = await before({ ...CALL, params: { code } }, OWNER);
+ assert.ok(result && "block" in result);
+ assert.match(result.blockReason, /Split the work/);
+ });
+
it("asks when the classifier fails", async () => {
const before = gate({
autoRun: () => true,
diff --git a/integrations/openclaw/src/approval.ts b/integrations/openclaw/src/approval.ts
index c796ce4..7179a40 100644
--- a/integrations/openclaw/src/approval.ts
+++ b/integrations/openclaw/src/approval.ts
@@ -3,6 +3,8 @@
*
* - Every call asks the user first, through OpenClaw's plugin approvals. Nobody to answer means
* the script does not run.
+ * - The prompt shows the whole script. One too long for the prompt is refused, never cut, so no
+ * one approves code they could not read.
* - A sender OpenClaw knows is not the owner is refused. Chats can answer their own approvals,
* so the prompt alone would let them drive the owner's phone.
* - "Allow always" covers later calls in the same session. OpenClaw leaves that memory to the
@@ -17,7 +19,11 @@ export const CLASSIFIER_AUTO_RUN_ENV = "PHONE_HARNESS_CLASSIFIER_AUTO_RUN";
export const OWNER_ONLY = "Only the owner of this OpenClaw can drive the phone.";
const APPROVAL_TIMEOUT_MS = 300_000;
-const DESCRIPTION_LIMIT = 512;
+/** OpenClaw's cap on a plugin approval's description (PLUGIN_APPROVAL_DESCRIPTION_MAX_LENGTH). */
+export const DESCRIPTION_LIMIT = 512;
+const PREFIX = "phone_exec: ";
+/** The longest script, as the prompt shows it, that fits a prompt whole. */
+export const MAX_SHOWN_CHARS = DESCRIPTION_LIMIT - PREFIX.length;
const CLASSIFIER_TIMEOUT_MS = 20_000;
/** Above CLASSIFIER_TIMEOUT_MS, so a slow classifier ends in a prompt and not a blocked call. */
export const HOOK_TIMEOUT_MS = 30_000;
@@ -57,17 +63,29 @@ export function classifierAutoRun(env: Env, setting: unknown): boolean {
}
/**
- * The script as the approver reads it, cut to fit the Gateway's description limit. A long script
- * keeps both ends, so padding cannot push what it really does out of the approver's sight.
+ * The whole script as the approver reads it. Runs of spaces, tabs and newlines show as one space,
+ * and control and invisible formatting characters are spelled out, so nothing that runs is hidden.
*/
-export function scriptSummary(code: string, prefix = "phone_exec: "): string {
- const body = code.split(/\s+/).filter(Boolean).join(" ") || "(empty)";
- const room = DESCRIPTION_LIMIT - prefix.length;
- if (body.length <= room) return prefix + body;
- const gap = (hidden: number) => ` ...[${hidden} characters hidden]... `;
- const keep = room - gap(body.length).length;
- const tail = Math.floor(keep / 2);
- return prefix + body.slice(0, keep - tail) + gap(body.length - keep) + body.slice(-tail);
+export function shownScript(code: string): string {
+ const body = code.split(/[ \t\n\r\f\v]+/).filter(Boolean).join(" ");
+ const spelled = body.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (char) => `\\u{${(char.codePointAt(0) ?? 0).toString(16)}}`);
+ return spelled || "(empty)";
+}
+
+/** The prompt with the whole script, or null when it does not fit. A script is never cut. */
+export function approvalDescription(code: string, prefix = PREFIX): string | null {
+ const description = prefix + shownScript(code);
+ return description.length <= DESCRIPTION_LIMIT ? description : null;
+}
+
+/** What the model hears when a script is too long for anyone to read it in the prompt. */
+export function tooLongToShow(code: string, prefix = PREFIX): string {
+ return (
+ `This script is ${shownScript(code).length} characters as the approval prompt shows it, and the ` +
+ `prompt holds ${DESCRIPTION_LIMIT - prefix.length}. phone_exec only runs a script the user could ` +
+ "read in full, so it did not run. Split the work into shorter phone_exec calls; the phone keeps " +
+ "its state between them."
+ );
}
export function createApprovalGate(options: { autoRun: () => boolean; classify: Classify }) {
@@ -81,7 +99,7 @@ export function createApprovalGate(options: { autoRun: () => boolean; classify:
if (session !== undefined && trustedSessions.has(session)) return undefined;
const code = typeof event.params.code === "string" ? event.params.code : "";
- let description = scriptSummary(code);
+ let prefix = PREFIX;
if (options.autoRun()) {
let reason: string | null;
try {
@@ -90,12 +108,12 @@ export function createApprovalGate(options: { autoRun: () => boolean; classify:
reason = "the classifier could not check";
}
if (reason === null) return undefined;
- description = scriptSummary(
- code,
+ prefix =
`This script ${reason}, which reaches past the phone onto this computer. Classifier auto-run ` +
- "is a heuristic and can be bypassed. phone_exec: ",
- );
+ `is a heuristic and can be bypassed. ${PREFIX}`;
}
+ const description = approvalDescription(code, prefix);
+ if (description === null) return { block: true, blockReason: tooLongToShow(code, prefix) };
return {
requireApproval: {
title: "Run a script on the phone",
diff --git a/integrations/openclaw/src/index.ts b/integrations/openclaw/src/index.ts
index 85a9e0a..5176a70 100644
--- a/integrations/openclaw/src/index.ts
+++ b/integrations/openclaw/src/index.ts
@@ -15,6 +15,7 @@ import {
classifyWithPython,
createApprovalGate,
HOOK_TIMEOUT_MS,
+ MAX_SHOWN_CHARS,
OWNER_ONLY,
TOOL_NAME,
} from "./approval.ts";
@@ -36,7 +37,9 @@ const DESCRIPTION =
"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. 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 phone-harness skill for the helpers.";
+ "type passwords, PINs or 2FA codes. The user reads the whole script before approving it, so keep " +
+ `each one under ${MAX_SHOWN_CHARS} characters (runs of whitespace count as one) and split longer ` +
+ "work into several calls. Read the phone-harness skill for the helpers.";
const PARAMETERS = Type.Object(
{
diff --git a/integrations/openclaw/src/phone-exec.test.ts b/integrations/openclaw/src/phone-exec.test.ts
index 4f9466b..4754c2b 100644
--- a/integrations/openclaw/src/phone-exec.test.ts
+++ b/integrations/openclaw/src/phone-exec.test.ts
@@ -1,6 +1,7 @@
// The plumbing around a script, tested without OpenClaw or a phone. `node -` stands in for
// phone-harness: like it, node runs whatever script arrives on stdin.
import assert from "node:assert/strict";
+import { execFileSync, spawn } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -44,10 +45,78 @@ function payload(result: ToolResult): Record<string, unknown> {
function alive(pid: number): boolean {
try {
process.kill(pid, 0);
- return true;
} catch {
return false;
}
+ // A killed process can sit as a zombie until its new parent reaps it. It is not running.
+ try {
+ return !execFileSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }).trim().startsWith("Z");
+ } catch {
+ return false;
+ }
+}
+
+async function waitFor(check: () => boolean, ms: number): Promise<boolean> {
+ const deadline = Date.now() + ms;
+ while (Date.now() < deadline) {
+ if (check()) return true;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ return check();
+}
+
+function parentOf(pid: number): number {
+ return Number(execFileSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8" }).trim());
+}
+
+/**
+ * A script that starts a process of every kind that can outlive a process-group kill: one in the
+ * script's own group, one in its own session, and one orphaned at once by a launcher that exits.
+ * With `seenFirst`, the orphan is a system binary whose launcher waits before exiting, so the
+ * plugin sees it under the script before it is orphaned. Every pid goes to a file.
+ */
+function escapingScript(seenFirst = false) {
+ const pids = join(dir, "pids");
+ const forever = join(dir, "forever.js");
+ const launcher = join(dir, "launcher.js");
+ writeFileSync(forever, "setInterval(() => {}, 1000);\n");
+ const orphan = seenFirst
+ ? `spawn("/bin/sleep", ["60"], { stdio: "ignore", detached: true })`
+ : `spawn(process.execPath, [${JSON.stringify(forever)}], { stdio: "ignore", detached: true })`;
+ writeFileSync(
+ launcher,
+ `const { spawn } = require("node:child_process");
+ const fs = require("node:fs");
+ const child = ${orphan};
+ fs.appendFileSync(${JSON.stringify(pids)}, "orphan " + child.pid + "\\nlauncher " + process.pid + "\\n");
+ setTimeout(() => process.exit(0), ${seenFirst ? 1500 : 0});\n`,
+ );
+ const script = `
+ const { spawn } = require("node:child_process");
+ const fs = require("node:fs");
+ const note = (name, pid) => fs.appendFileSync(${JSON.stringify(pids)}, name + " " + pid + "\\n");
+ note("same-group", spawn(process.execPath, [${JSON.stringify(forever)}], { stdio: "ignore" }).pid);
+ note("own-session", spawn(process.execPath, [${JSON.stringify(forever)}], { stdio: "ignore", detached: true }).pid);
+ spawn(process.execPath, [${JSON.stringify(launcher)}], { stdio: "ignore", detached: true });
+ setInterval(() => {}, 1000);
+ `;
+ const read = (): Record<string, number> => {
+ const text = existsSync(pids) ? readFileSync(pids, "utf8") : "";
+ return Object.fromEntries(text.trim().split("\n").filter(Boolean).map((line) => {
+ const [name, pid] = line.split(" ");
+ return [name, Number(pid)];
+ }));
+ };
+ return { script, read, forever };
+}
+
+/** Wait until the script's processes exist and the orphan has lost its launcher. */
+async function untilOrphaned(read: () => Record<string, number>): Promise<Record<string, number>> {
+ assert.ok(await waitFor(() => Object.keys(read()).length === 4, 10_000), "the script started its processes");
+ const pids = read();
+ assert.ok(await waitFor(() => !alive(pids.launcher as number), 10_000), "the launcher exited");
+ assert.notEqual(parentOf(pids.orphan as number), pids.launcher, "the orphan lost its parent");
+ return pids;
}
describe("the pinned command", () => {
@@ -110,21 +179,19 @@ describe("a script", () => {
});
});
+const POSIX = process.platform !== "win32";
+const NOT_POSIX = !POSIX && "sessions and process groups are POSIX";
+
describe("a script past its timeout", () => {
- it("is killed with everything it started", { timeout: 30_000 }, async () => {
- const pidFile = join(dir, "pid");
- const script = `
- const { spawn } = require("node:child_process");
- const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
- require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(child.pid));
- setInterval(() => {}, 1000);
- `;
+ it("is stopped with every process it started, wherever it went", { skip: NOT_POSIX, timeout: 60_000 }, async () => {
+ const { script, read } = escapingScript();
const result = await run(script, { timeout_s: 1 }); // clamped up to the 5 s minimum
assert.equal(result.details.ok, false);
assert.equal(result.details.timedOut, true);
assert.equal(result.details.timeoutMs, 5000);
- const grandchild = Number(readFileSync(pidFile, "utf8"));
- assert.equal(alive(grandchild), false);
+ const pids = read();
+ assert.deepEqual(Object.keys(pids).sort(), ["launcher", "orphan", "own-session", "same-group"]);
+ for (const [name, pid] of Object.entries(pids)) assert.equal(alive(pid), false, `${name} survived`);
});
it("gets a tool budget longer than the script's own timeout", () => {
@@ -144,6 +211,50 @@ describe("a script past its timeout", () => {
});
});
+describe("a cancelled call", () => {
+ it("stops a child in its own session, and one orphaned at once", { skip: NOT_POSIX, timeout: 60_000 }, async () => {
+ const { script, read } = escapingScript();
+ const controller = new AbortController();
+ const running = run(script, { signal: controller.signal });
+ const pids = await untilOrphaned(read);
+ for (const [name, pid] of Object.entries(pids)) {
+ if (name !== "launcher") assert.equal(alive(pid), true, `${name} was running`);
+ }
+ controller.abort();
+ const result = await running;
+ assert.match(String(result.details.error), /cancelled/);
+ for (const [name, pid] of Object.entries(pids)) assert.equal(alive(pid), false, `${name} survived`);
+ });
+
+ it("stops a system binary orphaned after the plugin saw it", { skip: NOT_POSIX, timeout: 60_000 }, async () => {
+ // macOS hides the environment of its own binaries, such as /bin/sleep, from other processes,
+ // so here the record of processes seen under the script is what finds the orphan.
+ const { script, read } = escapingScript(true);
+ const controller = new AbortController();
+ const running = run(script, { signal: controller.signal });
+ const pids = await untilOrphaned(read);
+ assert.equal(alive(pids.orphan as number), true);
+ controller.abort();
+ await running;
+ for (const [name, pid] of Object.entries(pids)) assert.equal(alive(pid), false, `${name} survived`);
+ });
+
+ it("leaves processes the script did not start alone", { skip: NOT_POSIX, timeout: 60_000 }, async () => {
+ const { script, read, forever } = escapingScript();
+ const bystander = spawn(process.execPath, [forever], { stdio: "ignore", detached: true });
+ try {
+ const controller = new AbortController();
+ const running = run(script, { signal: controller.signal });
+ await untilOrphaned(read);
+ controller.abort();
+ await running;
+ assert.equal(alive(bystander.pid as number), true, "a process outside the run was killed");
+ } finally {
+ bystander.kill("SIGKILL");
+ }
+ });
+});
+
describe("one script at a time", () => {
it("runs a second script only after the first", async () => {
const lock = new PhoneLock();
diff --git a/integrations/openclaw/src/phone-exec.ts b/integrations/openclaw/src/phone-exec.ts
index f10baed..254c9e2 100644
--- a/integrations/openclaw/src/phone-exec.ts
+++ b/integrations/openclaw/src/phone-exec.ts
@@ -10,10 +10,13 @@
* - The child environment drops credentials. Telemetry is Phone Harness's own, on by default
* like the CLI's, and DO_NOT_TRACK or `config set telemetry false` reach it unchanged.
* - One script drives the phone at a time, across subagents in this process.
- * - A script past its timeout, or a cancelled call, is killed with everything it started.
+ * - A script past its timeout, or a cancelled call, is stopped with every process it started,
+ * including ones in their own session or process group. See stopRun.
*/
-import { spawn } from "node:child_process";
+import { execFile, spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
+import { readdir, readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { delimiter, dirname, join } from "node:path";
@@ -123,18 +126,173 @@ export class PhoneLock {
const phoneLock = new PhoneLock();
// ---------------------------------------------------------------------------------------------
-// The child process.
+// Finding and stopping every process a script started.
+//
+// The runner leads its own process group, but a script can start processes that leave it: a new
+// session or group, or a child whose parent exits so that it is re-parented away from the runner.
+// Each run therefore tags its processes with RUN_MARKER, which every child inherits, and keeps a
+// record of the processes it has seen under the runner. Stopping a run kills, in repeated rounds
+// until none is left: the runner's process tree, every process carrying the marker, every process
+// in the record that is still the same process, everything under those, and their process groups.
+
+/** The environment variable that tags a run's processes. Its value is new for every run. */
+export const RUN_MARKER = "PH_OPENCLAW_RUN";
+const SAMPLE_MS = 500;
+const KILL_ROUND_MS = 50;
+const KILL_ROUNDS = 40;
+
+type Proc = { pid: number; ppid: number; pgid: number; zombie: boolean; started: string };
+type ProcessTable = Map<number, Proc>;
+
+function run(file: string, args: string[]): Promise<string> {
+ return new Promise((resolve) => {
+ execFile(file, args, { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 }, (error, stdout) =>
+ resolve(error ? "" : stdout),
+ );
+ });
+}
+
+/** Every process on this machine. Linux reads /proc, so it works without ps; elsewhere, ps. */
+export async function processTable(): Promise<ProcessTable> {
+ const table: ProcessTable = new Map();
+ if (process.platform === "linux") {
+ for (const name of await readdir("/proc").catch(() => [] as string[])) {
+ if (!/^\d+$/.test(name)) continue;
+ const stat = await readFile(`/proc/${name}/stat`, "utf8").catch(() => "");
+ // pid (comm) state ppid pgrp session ... starttime is field 22. comm may hold spaces or parens.
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ if (fields.length < 20) continue;
+ table.set(Number(name), {
+ pid: Number(name),
+ ppid: Number(fields[1]),
+ pgid: Number(fields[2]),
+ zombie: fields[0] === "Z",
+ started: fields[19] ?? "",
+ });
+ }
+ return table;
+ }
+ const out = await run("ps", ["-A", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "stat=", "-o", "lstart="]);
+ for (const line of out.split("\n")) {
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*\S)\s*$/.exec(line);
+ if (!match) continue;
+ const [, pid, ppid, pgid, stat, started] = match as unknown as [string, string, string, string, string, string];
+ table.set(Number(pid), {
+ pid: Number(pid),
+ ppid: Number(ppid),
+ pgid: Number(pgid),
+ zombie: stat.startsWith("Z"),
+ started,
+ });
+ }
+ return table;
+}
-/** Kill the runner and everything it spawned (it leads its own process group). */
-function killGroup(pid: number): void {
+/**
+ * Processes whose environment carries this run's marker. Linux shows the environment of every
+ * process the user owns. macOS shows it through `ps -E`, except for its own system binaries; the
+ * record of processes seen under the runner covers those.
+ */
+export async function markedPids(marker: string): Promise<number[]> {
+ const needle = `${RUN_MARKER}=${marker}`;
+ const found: number[] = [];
+ if (process.platform === "linux") {
+ for (const name of await readdir("/proc").catch(() => [] as string[])) {
+ if (!/^\d+$/.test(name)) continue;
+ const environ = await readFile(`/proc/${name}/environ`, "latin1").catch(() => "");
+ if (environ.split("\0").includes(needle)) found.push(Number(name));
+ }
+ return found;
+ }
+ const out = await run("ps", ["-A", "-E", "-ww", "-o", "pid=", "-o", "command="]);
+ for (const line of out.split("\n")) {
+ const match = /^\s*(\d+)\s(.*)$/.exec(line);
+ if (match && ` ${match[2]} `.includes(` ${needle} `)) found.push(Number(match[1]));
+ }
+ return found;
+}
+
+function descendants(roots: Iterable<number>, table: ProcessTable): Set<number> {
+ const children = new Map<number, number[]>();
+ for (const proc of table.values()) {
+ const siblings = children.get(proc.ppid) ?? [];
+ siblings.push(proc.pid);
+ children.set(proc.ppid, siblings);
+ }
+ const found = new Set<number>();
+ const stack = [...roots];
+ while (stack.length > 0) {
+ for (const child of children.get(stack.pop() as number) ?? []) {
+ if (found.has(child)) continue;
+ found.add(child);
+ stack.push(child);
+ }
+ }
+ return found;
+}
+
+/** Remembers each process seen under the runner, with its start time, so a reused pid is never taken for it. */
+export class RunRecord {
+ readonly seen = new Map<number, string>();
+ readonly rootPid: number;
+ readonly marker: string;
+
+ constructor(rootPid: number, marker: string) {
+ this.rootPid = rootPid;
+ this.marker = marker;
+ }
+
+ note(table: ProcessTable): void {
+ for (const pid of descendants([this.rootPid], table)) {
+ const proc = table.get(pid);
+ if (proc && !this.seen.has(pid)) this.seen.set(pid, proc.started);
+ }
+ }
+
+ /** The run's live processes, found before anything is killed so no child is orphaned first. */
+ async live(table: ProcessTable): Promise<Set<number>> {
+ const roots = new Set<number>([this.rootPid, ...(await markedPids(this.marker))]);
+ for (const [pid, started] of this.seen) {
+ if (table.get(pid)?.started === started) roots.add(pid);
+ }
+ const all = new Set<number>([...roots, ...descendants(roots, table)]);
+ all.delete(process.pid);
+ return new Set([...all].filter((pid) => table.has(pid) && !table.get(pid)?.zombie));
+ }
+}
+
+/** Stop every process the run started. Resolves once none is left, or when the rounds run out. */
+export async function stopRun(record: RunRecord): Promise<void> {
if (process.platform === "win32") {
- spawn("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore" }).on("error", () => {});
+ // Windows has no process groups or sessions to leave; taskkill /T takes the whole tree.
+ spawn("taskkill", ["/T", "/F", "/PID", String(record.rootPid)], { stdio: "ignore" }).on("error", () => {});
return;
}
- try {
- process.kill(-pid, "SIGKILL");
- } catch {
- // Already gone.
+ const deadline = Date.now() + KILL_WAIT_MS / 2;
+ for (let round = 0; round < KILL_ROUNDS && Date.now() < deadline; round++) {
+ const table = await processTable();
+ record.note(table);
+ const targets = await record.live(table);
+ const ownGroup = table.get(process.pid)?.pgid;
+ const groups = new Set<number>([record.rootPid]);
+ for (const pid of targets) groups.add(table.get(pid)?.pgid ?? record.rootPid);
+ for (const group of groups) {
+ if (group <= 1 || group === ownGroup) continue;
+ try {
+ process.kill(-group, "SIGKILL");
+ } catch {
+ // No such group any more.
+ }
+ }
+ for (const pid of targets) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // Already gone.
+ }
+ }
+ if (targets.size === 0 && round > 0) return;
+ await new Promise((resolve) => setTimeout(resolve, KILL_ROUND_MS));
}
}
@@ -168,29 +326,47 @@ function runChild(command: Command, code: string, options: {
return new Promise((resolve) => {
const out = tailCollector(OUTPUT_CAP);
const err = tailCollector(STDERR_CAP);
+ const marker = randomUUID();
const child = spawn(command.file, command.args, {
cwd: options.cwd,
- env: options.env as NodeJS.ProcessEnv,
+ env: { ...options.env, [RUN_MARKER]: marker } as NodeJS.ProcessEnv,
stdio: ["pipe", "pipe", "pipe"],
detached: process.platform !== "win32",
});
+ const record = child.pid === undefined ? undefined : new RunRecord(child.pid, marker);
let timedOut = false;
let aborted = false;
let settled = false;
+ let stopping = false;
let killWait: NodeJS.Timeout | undefined;
+ // Note who is under the runner while it runs, so a process orphaned later can still be found.
+ const sampler =
+ record && process.platform !== "win32"
+ ? setInterval(() => {
+ void processTable().then((table) => record.note(table));
+ }, SAMPLE_MS)
+ : undefined;
+
+ let stopped: Promise<void> = Promise.resolve();
const settle = (exitCode: number | null, spawnError?: NodeJS.ErrnoException) => {
if (settled) return;
settled = true;
clearTimeout(timer);
clearTimeout(killWait);
+ clearInterval(sampler);
options.signal?.removeEventListener("abort", onAbort);
- resolve({ exitCode, stdout: out.read(), stderr: err.read(), timedOut, aborted, spawnError });
+ const result = { exitCode, stdout: out.read(), stderr: err.read(), timedOut, aborted, spawnError };
+ // A stopped run frees the phone only once its last process is gone.
+ void stopped.then(() => resolve(result));
};
const stop = () => {
- if (child.pid !== undefined) killGroup(child.pid);
- // Close follows the kill. Do not hang on a process that left the group and kept a pipe.
+ if (stopping) return;
+ stopping = true;
+ clearInterval(sampler);
+ // Close follows the kill. Do not hang if a pipe stays open anyway.
killWait = setTimeout(() => settle(null), KILL_WAIT_MS);
+ if (record) stopped = stopRun(record).catch(() => {});
};
const onAbort = () => {
aborted = true;
diff --git a/tests/test_openclaw_plugin.py b/tests/test_openclaw_plugin.py
index f8e21ae..0823f49 100644
--- a/tests/test_openclaw_plugin.py
+++ b/tests/test_openclaw_plugin.py
@@ -215,17 +215,10 @@ class Readme(unittest.TestCase):
def test_says_what_telemetry_sends_and_how_to_turn_it_off(self):
text = (PLUGIN / "README.md").read_text(encoding="utf-8")
- for phrase in ("on by default", "us.i.posthog.com", "script text", "printed", "arguments",
- "`phone-harness config set telemetry false`",
- "`uvx phone-harness config set telemetry false`", "`DO_NOT_TRACK=1`",
- "Gateway's own environment"):
+ for phrase in ("PostHog", "scripts and what they print", "`DO_NOT_TRACK=1`",
+ "`uvx phone-harness config set telemetry false`"):
self.assertIn(phrase, text)
- def test_the_listing_summary_names_telemetry_and_the_way_out(self):
- summary = json.loads((PLUGIN / "package.json").read_text(encoding="utf-8"))["description"]
- self.assertIn("telemetry", summary)
- self.assertIn("DO_NOT_TRACK=1", summary)
-
def test_no_posthog_key_ships_in_the_plugin(self):
for path in PLUGIN.rglob("*"):
if path.is_file() and "node_modules" not in path.parts: