Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone tools: a batch tool runs known steps in one call
Xiaolei Shia99d34a3d101
diff --git a/server/drivers/phone-proxy.test.ts b/server/drivers/phone-proxy.test.tsindex 7175d7a6ce..36684e3cea 100644--- a/server/drivers/phone-proxy.test.ts+++ b/server/drivers/phone-proxy.test.ts@@ -1,6 +1,15 @@-import { describe, expect, it } from "vitest";+import { spawn, type ChildProcess } from "node:child_process";+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createInterface } from "node:readline";+import { fileURLToPath } from "node:url";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";-import { TOOLS, createPhoneClaim, findPackages, launchTarget, parseDevices, parseLaunchablePackages, parseUiNodes, typePhoneText } from "./phone-proxy.ts";+import { PHONE_STEP_TOOLS } from "../../shared/phone-steps.ts";+import { TOOLS, createPhoneClaim, findPackages, launchTarget, parseDevices, parseLaunchablePackages, parseSteps, parseUiNodes, runSteps, typePhoneText, type PhoneStep } from "./phone-proxy.ts";describe("phone MCP parsing", () => {it("keeps physical USB devices distinguishable from network and emulator transports", () => {@@ -167,3 +176,315 @@ describe("phone MCP lazy claim gate", () => {await expect(ensure()).resolves.toMatchObject({ ok: false, message: expect.stringContaining("could not be reached") });});});++const SCREEN = '0: "Search" bounds=0,100,200,180 class=android.widget.TextView';+const EARLIER_AND_LATER = "Steps before it were done; do not repeat them. Later steps were not performed.";++describe("phone batch step parsing", () => {+ it.each([+ { case: "coerces named fields", raw: [{ action: "Tap", x: "540", y: 1200 }], steps: [{ action: "tap", x: 540, y: 1200 }] },+ { case: "keeps a numeric code a string", raw: [{ action: "type_text", text: "10001" }, { action: "type_text", text: 10001 }], steps: [{ action: "type_text", text: "10001" }, { action: "type_text", text: "10001" }] },+ { case: "coerces a match index and exact", raw: [{ action: "tap_text", text: "Search", index: "1", exact: "true" }, { action: "tap_text", text: "Search", exact: "false" }], steps: [{ action: "tap_text", text: "Search", index: 1, exact: true }, { action: "tap_text", text: "Search", exact: false }] },+ { case: "treats null and empty fields as absent", raw: [{ action: "tap_text", text: "Search", index: null, exact: "", seconds: null }, { action: "wait", seconds: "" }], steps: [{ action: "tap_text", text: "Search" }, { action: "wait" }] },+ { case: "lowercases action, key and direction", raw: [{ action: "PRESS", key: "Enter" }, { action: "swipe", direction: "UP" }], steps: [{ action: "press", key: "enter" }, { action: "swipe", direction: "up" }] },+ { case: "ignores fields no action takes", raw: [{ action: "read_screen", verify: true }, { action: "open_app", name: "Settings", why: "check" }], steps: [{ action: "read_screen" }, { action: "open_app", name: "Settings" }] },+ { case: "parses steps given as JSON text", raw: '[{"action":"read_screen"}]', steps: [{ action: "read_screen" }] },+ { case: "parses a step given as JSON text", raw: ['{"action":"press","key":"back"}'], steps: [{ action: "press", key: "back" }] },+ { case: "accepts waits from 0 and above 60", raw: [{ action: "wait" }, { action: "wait", seconds: 0 }, { action: "wait", seconds: "75" }], steps: [{ action: "wait" }, { action: "wait", seconds: 0 }, { action: "wait", seconds: 75 }] },+ { case: "accepts 10 steps", raw: Array(10).fill({ action: "read_screen" }), steps: Array(10).fill({ action: "read_screen" }) },+ { case: "coerces both coordinates", raw: [{ action: "tap", x: "540", y: "1200" }], steps: [{ action: "tap", x: 540, y: 1200 }] },+ { case: "counts text to type in characters, as type_text does", raw: [{ action: "type_text", text: "π".repeat(256) }], steps: [{ action: "type_text", text: "π".repeat(256) }] },+ { case: "treats a null or empty serial on a step as absent", raw: [{ action: "read_screen", serial: null }, { action: "read_screen", serial: "" }], steps: [{ action: "read_screen" }, { action: "read_screen" }] },+ { case: "ignores fields named like an object's built-ins", raw: '[{"action":"read_screen","constructor":"x","toString":"y","__proto__":{"action":"tap"}}]', steps: [{ action: "read_screen" }] },+ ])("$case", ({ raw, steps }) => {+ expect(parseSteps(raw)).toEqual(steps);+ });++ it.each([+ { case: "a wait field on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: 5 }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":5} step after it. No step was performed.' },+ { case: "a field of another action", raw: [{ action: "tap", x: 1, y: 2, text: "Go" }], error: 'Step 1 (tap) does not take text, which belongs to tap_text or type_text; write it like {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "missing fields", raw: [{ action: "tap" }], error: 'Step 1 (tap) needs x and y, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "a missing field in a later step", raw: [{ action: "read_screen" }, { action: "type_text", text: "" }], error: 'Step 2 (type_text) needs text, e.g. {"action":"type_text","text":"iPad mini"}. No step was performed.' },+ { case: "a screenshot step", raw: [{ action: "screenshot" }], error: "Step 1: screenshot returns an image and cannot be a batch step; use read_screen, or call screenshot after the batch. No step was performed." },+ { case: "a batch step", raw: [{ action: "batch", steps: [{ action: "read_screen" }] }], error: "Step 1: a batch cannot be a batch step; put its steps in this list. No step was performed." },+ { case: "an action that is not a step", raw: [{ action: "status" }], error: 'Step 1 needs an action from open_app, tap_text, tap, swipe, type_text, press, read_screen, wait, e.g. {"action":"tap_text","text":"Search"}. No step was performed.' },+ { case: "a wait that is not a number", raw: [{ action: "wait", seconds: "x" }], error: 'Step 1 (wait) needs seconds as a number from 0 to 60, e.g. {"action":"wait","seconds":3}. No step was performed.' },+ { case: "coordinates off the screen", raw: [{ action: "tap", x: -1, y: 2 }], error: 'Step 1 (tap) needs x and y from 0 to 10000, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "a fractional match index", raw: [{ action: "tap_text", text: "Search", index: "1.5" }], error: 'Step 1 (tap_text) needs index as a whole number from 0, e.g. {"action":"tap_text","text":"Search","index":1}. No step was performed.' },+ { case: "an exact that is not true or false", raw: [{ action: "tap_text", text: "Search", exact: "yes" }], error: 'Step 1 (tap_text) needs exact as true or false, e.g. {"action":"tap_text","text":"Search","exact":true}. No step was performed.' },+ { case: "blank text to tap", raw: [{ action: "tap_text", text: " " }], error: 'Step 1 (tap_text) needs text that is not blank, e.g. {"action":"tap_text","text":"Search"}. No step was performed.' },+ { case: "a blank app name", raw: [{ action: "open_app", name: " " }], error: `Step 1 (open_app) needs name, an app's English name or package name, e.g. {"action":"open_app","name":"Settings"}. No step was performed.` },+ { case: "text too long to type", raw: [{ action: "type_text", text: "a".repeat(257) }], error: 'Step 1 (type_text) needs text of at most 256 characters, e.g. {"action":"type_text","text":"iPad mini"}. No step was performed.' },+ { case: "an unknown swipe direction", raw: [{ action: "swipe", direction: "north" }], error: 'Step 1 (swipe) needs direction as one of up, down, left, right, e.g. {"action":"swipe","direction":"up"}. No step was performed.' },+ { case: "an unknown key", raw: [{ action: "press", key: "f13" }], error: 'Step 1 (press) needs key as one of back, delete, down, enter, escape, home, left, recent, return, right, sleep, space, tab, up, wakeup, e.g. {"action":"press","key":"enter"}. No step was performed.' },+ { case: "a step that is not an object", raw: ["read_screen"], error: 'Step 1 needs to be an object such as {"action":"tap_text","text":"Search"}. No step was performed.' },+ { case: "11 steps", raw: Array(11).fill({ action: "read_screen" }), error: "A batch runs at most 10 steps, not 11; split them into several batches. No step was performed." },+ { case: "no steps", raw: undefined, error: 'steps needs a list of 1 to 10 steps, e.g. {"steps":[{"action":"tap_text","text":"Search"},{"action":"read_screen"}]}. No step was performed.' },+ { case: "an empty step list", raw: [], error: 'steps needs a list of 1 to 10 steps, e.g. {"steps":[{"action":"tap_text","text":"Search"},{"action":"read_screen"}]}. No step was performed.' },+ { case: "an empty list as text, after a valid step", raw: [{ action: "tap", x: 540, y: 1200 }, { action: "type_text", text: [] }], error: 'Step 2 (type_text) needs text as a single value, not a list or an object, e.g. {"action":"type_text","text":"iPad mini"}. No step was performed.' },+ { case: "a negative match index", raw: [{ action: "tap_text", text: "Search", index: -1 }], error: 'Step 1 (tap_text) needs index as a whole number from 0, e.g. {"action":"tap_text","text":"Search","index":1}. No step was performed.' },+ { case: "a y off the screen", raw: [{ action: "tap", x: 1, y: -1 }], error: 'Step 1 (tap) needs x and y from 0 to 10000, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "an x past 10000", raw: [{ action: "tap", x: 10001, y: 2 }], error: 'Step 1 (tap) needs x and y from 0 to 10000, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "a coordinate that is not a number", raw: [{ action: "tap", x: true, y: 1200 }], error: 'Step 1 (tap) needs x and y from 0 to 10000, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "a blank coordinate string", raw: [{ action: "tap", x: " ", y: 1200 }], error: 'Step 1 (tap) needs x and y from 0 to 10000, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "a negative wait", raw: [{ action: "wait", seconds: -1 }], error: 'Step 1 (wait) needs seconds as a number from 0 to 60, e.g. {"action":"wait","seconds":3}. No step was performed.' },+ { case: "a negative wait on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: -1 }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":3} step after it. No step was performed.' },+ { case: "a wait given as true", raw: [{ action: "wait", seconds: true }], error: 'Step 1 (wait) needs seconds as a number from 0 to 60, e.g. {"action":"wait","seconds":3}. No step was performed.' },+ { case: "a serial on a step", raw: [{ action: "tap", x: 1, y: 2, serial: "B" }], error: 'Step 1 names a serial, but a batch runs on one phone; set serial once beside steps, e.g. {"serial":"B","steps":[{"action":"read_screen"}]}. No step was performed.' },+ { case: "a serial on a step that is not text", raw: [{ action: "read_screen", serial: ["B"] }], error: 'Step 1 names a serial, but a batch runs on one phone; set serial once beside steps, e.g. {"serial":"<serial>","steps":[{"action":"read_screen"}]}. No step was performed.' },+ { case: "an action given as a list", raw: [{ action: ["read_screen"] }], error: 'Step 1 needs an action from open_app, tap_text, tap, swipe, type_text, press, read_screen, wait, e.g. {"action":"tap_text","text":"Search"}. No step was performed.' },+ { case: "a missing field before a list", raw: [{ action: "tap", x: [1] }], error: 'Step 1 (tap) needs y, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' },+ { case: "a zero wait on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: 0 }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":0} step after it. No step was performed.' },+ { case: "an endless wait on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: "Infinity" }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":3} step after it. No step was performed.' },+ { case: "a list as a wait on another action", raw: [{ action: "tap", x: 1, y: 2, seconds: [5] }], error: 'Step 1 (tap) does not take seconds; put a separate {"action":"wait","seconds":3} step after it. No step was performed.' },+ ])("refuses $case", ({ raw, error }) => {+ expect(() => parseSteps(raw)).toThrow(new Error(error));+ });++ const VALID_FIELDS: Record<string, Record<string, unknown>> = {+ open_app: { name: "Settings" },+ tap_text: { text: "Search", exact: true, index: 1 },+ tap: { x: 540, y: 1200 },+ swipe: { direction: "up" },+ type_text: { text: "iPad mini" },+ press: { key: "enter" },+ wait: { seconds: 3 },+ };+ it.each(Object.entries(VALID_FIELDS).flatMap(([action, fields]) => Object.keys(fields).flatMap((field) => [+ { action, field, kind: "a list", step: { action, ...fields, [field]: ["hello", "world"] } },+ { action, field, kind: "an object", step: { action, ...fields, [field]: { value: 1 } } },+ ])))("refuses $kind as $action's $field", ({ action, field, step }) => {+ expect(() => parseSteps([step])).toThrow(new RegExp(`^Step 1 \\(${action}\\) needs ${field} as a single value, not a list or an object, e\\.g\\. \\{"action":"${action}".*\\}\\. No step was performed\\.$`));+ });+});++describe("phone batch runs", () => {+ const OUTPUT: Record<string, string> = { tap: "Tapped 540,1200", tap_text: 'Tapped "Search"', press: "Pressed enter", read_screen: SCREEN };+ const TAP: PhoneStep = { action: "tap", x: 540, y: 1200 };+ const TAP_TEXT: PhoneStep = { action: "tap_text", text: "Search" };+ const PRESS: PhoneStep = { action: "press", key: "enter" };+ const READ: PhoneStep = { action: "read_screen" };+ const run = async (steps: PhoneStep[], failAt = 0, refuseBefore = 0, refusal = "This turn no longer has phone access. Start a new turn to use the phone.") => {+ const performed: string[] = [];+ let claims = 0;+ const result = await runSteps("FAKE123", steps, async () => {+ claims += 1;+ return claims + 1 === refuseBefore ? { ok: false, message: refusal } : { ok: true };+ }, async (serial, step) => {+ performed.push(`${serial} ${step.action}`);+ if (performed.length === failAt) throw new Error('No visible Android text matches "Buy"');+ return OUTPUT[step.action];+ });+ return { performed, claims, text: (result.content[0] as { text: string }).text, isError: result.isError };+ };++ it.each([+ { case: "acts without reading the screen when no step asks", steps: [TAP], performed: ["FAKE123 tap"], claims: 0, text: "1. tap: Tapped 540,1200" },+ { case: "shows the screen under a read_screen step", steps: [TAP, READ], performed: ["FAKE123 tap", "FAKE123 read_screen"], claims: 1, text: `1. tap: Tapped 540,1200\n2. read_screen:\n${SCREEN}` },+ { case: "stops at a failing step 2 without an error flag", steps: [TAP_TEXT, TAP_TEXT, READ], failAt: 2, performed: ["FAKE123 tap_text", "FAKE123 tap_text"], claims: 1, text: `1. tap_text: Tapped "Search"\nStep 2 failed: No visible Android text matches "Buy". Its effect is unknown; call read_screen or screenshot before trying it again. ${EARLIER_AND_LATER}` },+ { case: "flags an error when step 1 fails", steps: [TAP_TEXT, READ], failAt: 1, performed: ["FAKE123 tap_text"], claims: 0, text: `Step 1 failed: No visible Android text matches "Buy". Its effect is unknown; call read_screen or screenshot before trying it again. ${EARLIER_AND_LATER}`, isError: true },+ { case: "stops when the claim is refused before step 2", steps: [TAP, PRESS, READ], refuseBefore: 2, performed: ["FAKE123 tap"], claims: 1, text: `1. tap: Tapped 540,1200\nStopped before step 2: This turn no longer has phone access. Start a new turn to use the phone. ${EARLIER_AND_LATER}` },+ { case: "rechecks the claim before every later step", steps: [TAP, PRESS, READ], refuseBefore: 3, performed: ["FAKE123 tap", "FAKE123 press"], claims: 2, text: `1. tap: Tapped 540,1200\n2. press: Pressed enter\nStopped before step 3: This turn no longer has phone access. Start a new turn to use the phone. ${EARLIER_AND_LATER}` },+ ])("$case", async ({ steps, failAt, refuseBefore, performed, claims, text, isError }) => {+ expect(await run(steps, failAt, refuseBefore)).toEqual({ performed, claims, text, isError });+ });++ it.each([+ { refusal: "Another thread is using the phone. This call was not performed. Pause phone work until that thread finishes, then read the screen again before acting.", said: "Another thread is using the phone. Pause phone work until that thread finishes, then read the screen again before acting" },+ { refusal: "OpenMausBot could not be reached to reserve the phone. This call was not performed; try again.", said: "OpenMausBot could not be reached to reserve the phone" },+ ])("does not call a half-done batch unperformed when the claim is refused: $said", async ({ refusal, said }) => {+ const { text } = await run([TAP, PRESS], 0, 2, refusal);+ expect(text).toBe(`1. tap: Tapped 540,1200\nStopped before step 2: ${said}. ${EARLIER_AND_LATER}`);+ });++ it("waits 2 s by default, and at most 60 s", async () => {+ vi.useFakeTimers();+ try {+ let done = false;+ const result = runSteps("FAKE123", [{ action: "wait" }, { action: "wait", seconds: 75 }], async () => ({ ok: true }));+ void result.then(() => { done = true; });+ await vi.advanceTimersByTimeAsync(61_999);+ expect(done).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ expect(done).toBe(true);+ expect((await result).content).toEqual([{ type: "text", text: "1. wait: Waited 2 s\n2. wait: Waited 60 s (a wait is at most 60 s)" }]);+ } finally {+ vi.useRealTimers();+ }+ });+});++describe("phone MCP tool surface", () => {+ type Property = { enum?: string[]; description?: string };+ const tool = (name: string) => TOOLS.find((candidate) => candidate.name === name) as unknown as {+ description: string;+ inputSchema: { properties: Record<string, Property> & { steps: { maxItems: number; items: { properties: Record<string, Property> } } } };+ };++ it("keeps every schema flat", () => {+ expect(JSON.stringify({ tools: TOOLS })).not.toMatch(/"(oneOf|anyOf|allOf|const|format)":/);+ });++ it("offers the shared step tools and wait as steps, each field naming its action", () => {+ const steps = tool("batch").inputSchema.properties.steps;+ expect(steps.items.properties.action.enum).toEqual([...PHONE_STEP_TOOLS, "wait"]);+ expect(steps.maxItems).toBe(10);+ expect(tool("batch").inputSchema.properties.serial).toEqual({ type: "string" });+ for (const name of PHONE_STEP_TOOLS) {+ for (const field of Object.keys(tool(name).inputSchema.properties).filter((key) => key !== "serial")) {+ expect(steps.items.properties[field]?.description?.split(": ")[0].split(" and "), `${name}.${field}`).toContain(name);+ }+ }+ expect(steps.items.properties.seconds.description).toBe("wait: how long to wait, 0 to 60, default 2.");+ expect(steps.items.properties.index.description).toBe("tap_text: which match of the text, from 0.");+ });++ it("describes batch as designed", () => {+ expect(tool("batch").description).toBe('Run up to 10 phone steps in order in one call. A step is one of open_app, tap_text, tap, swipe, type_text, press, read_screen or wait, with that tool\'s fields: {action, ...fields}. Add read_screen as the last step to see the result; the batch returns the screen only at a read_screen step. A wait step (0 to 60 s) gives content time to load. It stops at the first failing step. End a batch where the next screen is uncertain, such as after a step that may open a dialog, and read it before acting further. Example: {"steps":[{"action":"tap_text","text":"Search"},{"action":"type_text","text":"iPad mini"},{"action":"press","key":"enter"},{"action":"wait","seconds":3},{"action":"read_screen"}]}');+ });++ it("points read_screen and the actions at batch", () => {+ expect(tool("read_screen").description).toBe("Read visible text, accessibility labels, resource ids, and pixel bounds from the connected Android screen. Use it before choosing what to act on. To act and see the result in one call, put the action and read_screen in one batch.");+ for (const name of ["open_app", "tap_text", "tap", "swipe", "type_text", "press"]) {+ expect(tool(name).description).toMatch(/\. To do several steps, or to act and then read the screen, in one call, use batch\.$/);+ expect(tool(name).description).not.toContain("then use read_screen to verify");+ }+ });++ it("keeps serial out of a step's fields", () => {+ expect(tool("batch").inputSchema.properties.steps.items.properties).not.toHaveProperty("serial");+ });++ it("keeps the batch hint off the tools that cannot be steps", () => {+ for (const name of ["status", "screenshot", "list_apps"]) {+ expect(tool(name).description).not.toContain("batch");+ }+ });+});++describe.skipIf(process.platform === "win32")("phone MCP calls through a stand-in adb", () => {+ type Response = { result: { content: Array<{ type: string; text: string }>; isError?: boolean } };+ type Call = (name: string, args: Record<string, unknown>) => Promise<Response>;+ let home = "";+ let adb = "";+ const proxies: ChildProcess[] = [];+ let call: Call;+ const adbLog = () => (existsSync(join(home, "adb.log")) ? readFileSync(join(home, "adb.log"), "utf8").trim().split("\n") : []);+ const DUMP = "-s FAKE123 shell uiautomator dump /dev/tty";++ const startProxy = (harness: Record<string, string> = {}): Call => {+ const env: NodeJS.ProcessEnv = { ...process.env, OMB_ADB_PATH: adb };+ delete env.OMB_HARNESS_URL;+ delete env.OMB_PHONE_TOKEN;+ delete env.PH_ANDROID_SERIAL;+ const proxy = spawn(process.execPath, [fileURLToPath(new URL("./phone-proxy.ts", import.meta.url))], { env: { ...env, ...harness }, stdio: ["pipe", "pipe", "ignore"] });+ proxies.push(proxy);+ const waiting = new Map<number, (response: Response) => void>();+ createInterface({ input: proxy.stdout! }).on("line", (line) => {+ const response = JSON.parse(line) as Response & { id: number };+ waiting.get(response.id)?.(response);+ });+ let id = 0;+ return (name, args) => new Promise((resolve) => {+ waiting.set(++id, resolve);+ proxy.stdin!.write(`${JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } })}\n`);+ });+ };++ beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), "omb-phone-proxy-"));+ adb = join(home, "adb");+ writeFileSync(adb, `#!/bin/sh+echo "$*" >> "$(dirname "$0")/adb.log"+case "$*" in+ "devices -l") printf 'List of devices attached\\nFAKE123 device usb:1-2 product:husky model:Pixel_8 transport_id:4\\n' ;;+ *"uiautomator dump /dev/tty") printf '%s' '<?xml version="1.0" encoding="UTF-8"?><hierarchy rotation="0"><node text="Search" resource-id="" class="android.widget.TextView" content-desc="" bounds="[0,100][200,180]" /></hierarchy>' ;;+ *"cmd package query-activities"*) echo "com.ubercab/.presidio.RootActivity" ;;+ *"wm size") echo "Physical size: 1080x2400" ;;+esac+`);+ chmodSync(adb, 0o755);+ call = startProxy();+ });+ afterAll(() => {+ for (const proxy of proxies) proxy.kill();+ rmSync(home, { recursive: true, force: true });+ });++ it.each([+ { name: "read_screen", args: {}, text: SCREEN, adb: [DUMP] },+ { name: "open_app", args: { name: "Uber" }, text: "Opened Uber (com.ubercab)", adb: ["-s FAKE123 shell cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.LAUNCHER", "-s FAKE123 shell monkey -p com.ubercab -c android.intent.category.LAUNCHER 1"] },+ { name: "tap_text", args: { text: "search" }, text: 'Tapped "Search"', adb: [DUMP, "-s FAKE123 shell input tap 100 140"] },+ { name: "tap", args: { x: 540, y: 1200 }, text: "Tapped 540,1200", adb: ["-s FAKE123 shell input tap 540 1200"] },+ { name: "swipe", args: { direction: "up" }, text: "Swiped up", adb: ["-s FAKE123 shell wm size", "-s FAKE123 shell input swipe 540 1800 540 600 260"] },+ { name: "type_text", args: { text: "iPad mini" }, text: "Typed text into the focused Android field", adb: ["-s FAKE123 shell input text iPad%smini"] },+ { name: "press", args: { key: "enter" }, text: "Pressed enter", adb: ["-s FAKE123 shell input keyevent KEYCODE_ENTER"] },+ ])("$name returns its single-call text", async ({ name, args, text, adb }) => {+ rmSync(join(home, "adb.log"), { force: true });+ expect((await call(name, args)).result).toEqual({ content: [{ type: "text", text }] });+ expect(adbLog()).toEqual(["devices -l", ...adb]);+ });++ it("runs a batch's steps in one call and returns the screen only at its read_screen step", async () => {+ rmSync(join(home, "adb.log"), { force: true });+ const response = await call("batch", { steps: [{ action: "tap_text", text: "Search" }, { action: "wait", seconds: 0 }, { action: "read_screen" }] });+ expect(response.result).toEqual({ content: [{ type: "text", text: `1. tap_text: Tapped "Search"\n2. wait: Waited 0 s\n3. read_screen:\n${SCREEN}` }] });+ expect(adbLog()).toEqual(["devices -l", DUMP, "-s FAKE123 shell input tap 100 140", DUMP]);+ });++ it("passes a step's coerced index and exact on to tap_text", async () => {+ const twoMatches = join(home, "adb-two-matches");+ writeFileSync(twoMatches, `#!/bin/sh+echo "$*" >> "$(dirname "$0")/adb.log"+case "$*" in+ "devices -l") printf 'List of devices attached\\nFAKE123 device usb:1-2 product:husky model:Pixel_8 transport_id:4\\n' ;;+ *"uiautomator dump /dev/tty") printf '%s' '<?xml version="1.0" encoding="UTF-8"?><hierarchy rotation="0"><node text="Search" resource-id="" class="android.widget.TextView" content-desc="" bounds="[0,100][200,180]" /><node text="Search history" resource-id="" class="android.widget.TextView" content-desc="" bounds="[0,300][200,380]" /></hierarchy>' ;;+esac+`);+ chmodSync(twoMatches, 0o755);+ const onTwoMatches = startProxy({ OMB_ADB_PATH: twoMatches });+ rmSync(join(home, "adb.log"), { force: true });+ const response = await onTwoMatches("batch", { steps: [{ action: "tap_text", text: "search", index: "1" }, { action: "tap_text", text: "history", exact: "true" }] });+ expect(response.result).toEqual({ content: [{ type: "text", text: `1. tap_text: Tapped "Search history"\nStep 2 failed: No visible Android text matches "history". Its effect is unknown; call read_screen or screenshot before trying it again. ${EARLIER_AND_LATER}` }] });+ expect(adbLog()).toEqual(["devices -l", DUMP, "-s FAKE123 shell input tap 100 340", DUMP]);+ });++ it("refuses an invalid batch before touching the phone", async () => {+ rmSync(join(home, "adb.log"), { force: true });+ const response = await call("batch", { steps: [{ action: "read_screen" }, { action: "tap" }] });+ expect(response.result).toEqual({ content: [{ type: "text", text: 'Step 2 (tap) needs x and y, e.g. {"action":"tap","x":540,"y":1200}. No step was performed.' }], isError: true });+ expect(adbLog()).toEqual([]);+ });++ it("keeps a single tool to its own action whatever action its arguments name", async () => {+ rmSync(join(home, "adb.log"), { force: true });+ expect((await call("tap", { x: 540, y: 1200, action: "press", key: "home" })).result).toEqual({ content: [{ type: "text", text: "Tapped 540,1200" }] });+ expect(adbLog()).toEqual(["devices -l", "-s FAKE123 shell input tap 540 1200"]);+ });++ it("runs a batch on the device its serial names", async () => {+ rmSync(join(home, "adb.log"), { force: true });+ const response = await call("batch", { serial: "MISSING", steps: [{ action: "tap", x: 540, y: 1200 }] });+ expect(response.result).toEqual({ content: [{ type: "text", text: "No physical USB Android device is connected" }], isError: true });+ expect(adbLog()).toEqual(["devices -l"]);+ });++ it("stops a batch at the next step once the harness refuses the claim", async () => {+ const answers = [200, 409];+ const harness = createServer((request, response) => {+ request.resume();+ response.writeHead(answers.shift() ?? 409).end("{}");+ });+ await new Promise<void>((resolve) => harness.listen(0, "127.0.0.1", resolve));+ try {+ const { port } = harness.address() as AddressInfo;+ const claimed = startProxy({ OMB_HARNESS_URL: `http://127.0.0.1:${port}`, OMB_PHONE_TOKEN: "tok" });+ rmSync(join(home, "adb.log"), { force: true });+ const response = await claimed("batch", { steps: [{ action: "tap", x: 540, y: 1200 }, { action: "press", key: "enter" }] });+ expect(response.result).toEqual({ content: [{ type: "text", text: "1. tap: Tapped 540,1200\nStopped before step 2: Another thread is using the phone. Pause phone work until that thread finishes, then read the screen again before acting. Steps before it were done; do not repeat them. Later steps were not performed." }] });+ expect(adbLog()).toEqual(["devices -l", "-s FAKE123 shell input tap 540 1200"]);+ } finally {+ harness.close();+ }+ });+});diff --git a/server/drivers/phone-proxy.ts b/server/drivers/phone-proxy.tsindex 12157f8340..c829f43b42 100644--- a/server/drivers/phone-proxy.ts+++ b/server/drivers/phone-proxy.ts@@ -5,6 +5,8 @@ import { createInterface } from "node:readline";import { delimiter, join } from "node:path";import { homedir } from "node:os";+import { PHONE_STEP_TOOLS, type PhoneStepTool } from "../../shared/phone-steps.ts";+type Json = Record<string, unknown>;type Device = { serial: string; state: string; model: string; connection: "usb" | "network" | "emulator" };type UiNode = { text: string; description: string; id: string; className: string; bounds: [number, number, number, number] };@@ -259,22 +261,182 @@ function nodeLines(nodes: UiNode[]) {}).join("\n") || "No accessible Android UI text is visible.";}-export const TOOLS = [+const SINGLE_TOOLS = [{ name: "status", description: "Check physical USB Android devices and USB-debugging authorization before any Android phone task.", inputSchema: { type: "object", properties: {} } },- { name: "read_screen", description: "Read visible text, accessibility labels, resource ids, and pixel bounds from the connected Android screen. Use after every action to verify the result.", inputSchema: { type: "object", properties: { serial: { type: "string" } } } },+ { name: "read_screen", description: "Read visible text, accessibility labels, resource ids, and pixel bounds from the connected Android screen. Use it before choosing what to act on. To act and see the result in one call, put the action and read_screen in one batch.", inputSchema: { type: "object", properties: { serial: { type: "string" } } } },{ name: "screenshot", description: "Capture the connected Android screen when accessibility text is insufficient. Returns a PNG image.", inputSchema: { type: "object", properties: { serial: { type: "string" } } } },{ name: "list_apps", description: "List installed launchable Android package names, optionally filtered by a human app name. Prefer open_app first.", inputSchema: { type: "object", properties: { query: { type: "string" }, serial: { type: "string" } } } },{ name: "open_app", description: "Open an installed Android app directly by its English name, such as Uber or Skyscanner, or by its package name. Do not scan the app drawer first.", inputSchema: { type: "object", properties: { name: { type: "string" }, serial: { type: "string" } }, required: ["name"] } },- { name: "tap_text", description: "Tap visible Android text or an accessibility label, then use read_screen to verify.", inputSchema: { type: "object", properties: { text: { type: "string" }, exact: { type: "boolean" }, index: { type: "integer", minimum: 0 }, serial: { type: "string" } }, required: ["text"] } },+ { name: "tap_text", description: "Tap visible Android text or an accessibility label.", inputSchema: { type: "object", properties: { text: { type: "string" }, exact: { type: "boolean" }, index: { type: "integer", minimum: 0 }, serial: { type: "string" } }, required: ["text"] } },{ name: "tap", description: "Tap Android screen pixel coordinates obtained from read_screen or screenshot.", inputSchema: { type: "object", properties: { x: { type: "number" }, y: { type: "number" }, serial: { type: "string" } }, required: ["x", "y"] } },- { name: "swipe", description: "Swipe the Android screen in a direction, then use read_screen to verify.", inputSchema: { type: "object", properties: { direction: { type: "string", enum: ["up", "down", "left", "right"] }, serial: { type: "string" } }, required: ["direction"] } },+ { name: "swipe", description: "Swipe the Android screen in a direction.", inputSchema: { type: "object", properties: { direction: { type: "string", enum: ["up", "down", "left", "right"] }, serial: { type: "string" } }, required: ["direction"] } },{ name: "type_text", description: "Type text into the focused Android field. Letters, digits, spaces and _.,@- always work; other text, such as Chinese, emoji or +, needs the ADBKeyBoard keyboard selected on the phone. Never enter passwords or payment details. A one-time code only for a sign-in the person asked for, into the app it was sent for.", inputSchema: { type: "object", properties: { text: { type: "string", maxLength: 256 }, serial: { type: "string" } }, required: ["text"] } },{ name: "press", description: "Press an Android navigation or keyboard key. wakeup turns the screen on and sleep turns it off.", inputSchema: { type: "object", properties: { key: { type: "string", enum: Object.keys(KEYCODES) }, serial: { type: "string" } }, required: ["key"] } },] as const;+type StepAction = PhoneStepTool | "wait";+export type PhoneStep = Json & { action: StepAction };+type StepRule = { ok: (step: Json) => boolean; needs: string; example?: Json };+type FieldSchema = { type?: string; enum?: readonly string[]; [keyword: string]: unknown };++const STEP_ACTIONS: readonly StepAction[] = [...PHONE_STEP_TOOLS, "wait"];+const MAX_STEPS = 10;+const DEFAULT_WAIT_SECONDS = 2;+const MAX_WAIT_SECONDS = 60;+const STEP_FIELD_NOTES: Record<string, string> = {+ name: "the app's English name or package name",+ text: "the visible text to tap, or the text to type",+ exact: "true to match the whole text, not part of it",+ index: "which match of the text, from 0",+ x: "pixel x from read_screen or screenshot",+ y: "pixel y from read_screen or screenshot",+ direction: "which way to swipe",+ key: "the key to press",+ seconds: `how long to wait, 0 to ${MAX_WAIT_SECONDS}, default ${DEFAULT_WAIT_SECONDS}`,+};+const STEP_EXAMPLES: Record<StepAction, Json> = {+ open_app: { action: "open_app", name: "Settings" },+ tap_text: { action: "tap_text", text: "Search" },+ tap: { action: "tap", x: 540, y: 1200 },+ swipe: { action: "swipe", direction: "up" },+ type_text: { action: "type_text", text: "iPad mini" },+ press: { action: "press", key: "enter" },+ read_screen: { action: "read_screen" },+ wait: { action: "wait", seconds: 3 },+};+const inPixels = (value: unknown) => Number.isFinite(value) && Number(value) >= 0 && Number(value) <= 10_000;+const STEP_RULES: Partial<Record<StepAction, StepRule[]>> = {+ open_app: [{ ok: (step) => String(step.name).trim() !== "", needs: "name, an app's English name or package name" }],+ tap_text: [+ { ok: (step) => String(step.text).trim() !== "", needs: "text that is not blank" },+ { ok: (step) => step.index === undefined || (Number.isInteger(step.index) && Number(step.index) >= 0), needs: "index as a whole number from 0", example: { action: "tap_text", text: "Search", index: 1 } },+ ],+ tap: [{ ok: (step) => inPixels(step.x) && inPixels(step.y), needs: "x and y from 0 to 10000" }],+ type_text: [{ ok: (step) => [...String(step.text)].length <= 256, needs: "text of at most 256 characters" }],+ wait: [{ ok: (step) => step.seconds === undefined || Number(step.seconds) >= 0, needs: `seconds as a number from 0 to ${MAX_WAIT_SECONDS}` }],+};++function stepSchema(action: StepAction): { properties: Record<string, FieldSchema>; required?: readonly string[] } {+ if (action === "wait") return { properties: { seconds: { type: "number", minimum: 0 } } };+ return SINGLE_TOOLS.find((tool) => tool.name === action)!.inputSchema;+}++const stepFields = (action: StepAction) => Object.keys(stepSchema(action).properties).filter((field) => field !== "serial");+const fieldOwners = (field: string) => STEP_ACTIONS.filter((action) => stepFields(action).includes(field));++function stepProperties() {+ const properties: Record<string, FieldSchema> = {+ action: { type: "string", enum: STEP_ACTIONS, description: "What the step does: a phone tool's name, or wait." },+ };+ for (const action of STEP_ACTIONS) {+ for (const field of stepFields(action)) {+ const owners = fieldOwners(field).join(" and ");+ const note = STEP_FIELD_NOTES[field];+ properties[field] ??= { ...stepSchema(action).properties[field], description: note ? `${owners}: ${note}.` : owners };+ }+ }+ return properties;+}++const STEP_PROPERTIES = stepProperties();++const lower = (value: unknown) => String(value).toLowerCase();+const toNumber = (value: unknown) => (typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : Number.NaN);++function coerce(field: string, value: unknown): unknown {+ const { type, enum: choices } = STEP_PROPERTIES[field];+ if (type === "number" || type === "integer") return toNumber(value);+ if (type === "boolean") return value === "true" || value === "false" ? value === "true" : value;+ if (type === "string") return choices ? lower(value) : String(value);+ return value;+}++function typeRules(action: StepAction): StepRule[] {+ return stepFields(action).flatMap((field): StepRule[] => {+ const { type, enum: choices } = stepSchema(action).properties[field];+ if (type === "boolean") {+ return [{ ok: (step) => step[field] === undefined || typeof step[field] === "boolean", needs: `${field} as true or false`, example: { ...STEP_EXAMPLES[action], [field]: true } }];+ }+ if (choices) return [{ ok: (step) => step[field] === undefined || choices.includes(String(step[field])), needs: `${field} as one of ${choices.join(", ")}` }];+ return [];+ });+}++const BATCH_HINT = "To do several steps, or to act and then read the screen, in one call, use batch.";+const takesBatchHint = (name: string) => name !== "read_screen" && (PHONE_STEP_TOOLS as readonly string[]).includes(name);++export const TOOLS = [+ ...SINGLE_TOOLS.map((tool) => (takesBatchHint(tool.name) ? { ...tool, description: `${tool.description} ${BATCH_HINT}` } : tool)),+ {+ name: "batch",+ description: `Run up to ${MAX_STEPS} phone steps in order in one call. A step is one of open_app, tap_text, tap, swipe, type_text, press, read_screen or wait, with that tool's fields: {action, ...fields}. Add read_screen as the last step to see the result; the batch returns the screen only at a read_screen step. A wait step (0 to ${MAX_WAIT_SECONDS} s) gives content time to load. It stops at the first failing step. End a batch where the next screen is uncertain, such as after a step that may open a dialog, and read it before acting further. Example: {"steps":[{"action":"tap_text","text":"Search"},{"action":"type_text","text":"iPad mini"},{"action":"press","key":"enter"},{"action":"wait","seconds":3},{"action":"read_screen"}]}`,+ inputSchema: {+ type: "object",+ properties: {+ steps: { type: "array", maxItems: MAX_STEPS, items: { type: "object", properties: STEP_PROPERTIES, required: ["action"] } },+ serial: { type: "string" },+ },+ required: ["steps"],+ },+ },+] as const;+type ToolResult = { content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }>; isError?: boolean };const textResult = (text: string, isError = false): ToolResult => ({ content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) });+const isStepAction = (value: unknown): value is StepAction => STEP_ACTIONS.includes(value as StepAction);+const refusal = (problem: string) => new Error(`${problem}. No step was performed.`);++function parseJson(value: unknown): unknown {+ if (typeof value !== "string") return value;+ try {+ return JSON.parse(value);+ } catch {+ return value;+ }+}++export function parseSteps(raw: unknown): PhoneStep[] {+ const steps = parseJson(raw);+ if (!Array.isArray(steps) || !steps.length) {+ throw refusal(`steps needs a list of 1 to ${MAX_STEPS} steps, e.g. {"steps":[{"action":"tap_text","text":"Search"},{"action":"read_screen"}]}`);+ }+ if (steps.length > MAX_STEPS) throw refusal(`A batch runs at most ${MAX_STEPS} steps, not ${steps.length}; split them into several batches`);+ return steps.map((step, index) => parseStep(parseJson(step), index + 1));+}++function parseStep(raw: unknown, n: number): PhoneStep {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw refusal(`Step ${n} needs to be an object such as ${JSON.stringify(STEP_EXAMPLES.tap_text)}`);+ const { serial } = raw as Json;+ if (serial !== undefined && serial !== null && serial !== "") {+ const named = typeof serial === "string" || typeof serial === "number" ? String(serial) : "<serial>";+ throw refusal(`Step ${n} names a serial, but a batch runs on one phone; set serial once beside steps, e.g. ${JSON.stringify({ serial: named, steps: [STEP_EXAMPLES.read_screen] })}`);+ }+ const step: Json = {};+ for (const [field, value] of Object.entries(raw)) {+ if (!Object.hasOwn(STEP_PROPERTIES, field) || value === null || value === "") continue;+ step[field] = typeof value === "object" ? value : coerce(field, value);+ }+ const { action } = step;+ if (action === "screenshot") throw refusal(`Step ${n}: screenshot returns an image and cannot be a batch step; use read_screen, or call screenshot after the batch`);+ if (action === "batch") throw refusal(`Step ${n}: a batch cannot be a batch step; put its steps in this list`);+ if (!isStepAction(action)) throw refusal(`Step ${n} needs an action from ${STEP_ACTIONS.join(", ")}, e.g. ${JSON.stringify(STEP_EXAMPLES.tap_text)}`);+ const example = JSON.stringify(STEP_EXAMPLES[action]);+ const foreign = Object.keys(step).find((field) => field !== "action" && !stepFields(action).includes(field));+ if (foreign === "seconds") {+ const seconds = Number.isFinite(step.seconds) && Number(step.seconds) >= 0 ? step.seconds : STEP_EXAMPLES.wait.seconds;+ throw refusal(`Step ${n} (${action}) does not take seconds; put a separate ${JSON.stringify({ action: "wait", seconds })} step after it`);+ }+ if (foreign) throw refusal(`Step ${n} (${action}) does not take ${foreign}, which belongs to ${fieldOwners(foreign).join(" or ")}; write it like ${example}`);+ const missing = (stepSchema(action).required ?? []).filter((field) => step[field] === undefined);+ if (missing.length) throw refusal(`Step ${n} (${action}) needs ${missing.join(" and ")}, e.g. ${example}`);+ const nested = Object.keys(step).find((field) => typeof step[field] === "object");+ if (nested) throw refusal(`Step ${n} (${action}) needs ${nested} as a single value, not a list or an object, e.g. ${example}`);+ const broken = [...(STEP_RULES[action] ?? []), ...typeRules(action)].find((rule) => !rule.ok(step));+ if (broken) throw refusal(`Step ${n} (${action}) needs ${broken.needs}, e.g. ${JSON.stringify(broken.example ?? STEP_EXAMPLES[action])}`);+ return { ...step, action };+}+// The harness reserves the phone per turn from the first real tool call. Retained MCP processes can// outlive their turn, so every call revalidates the claim.export function createPhoneClaim(@@ -307,13 +469,64 @@ export function createPhoneClaim(};}-async function callTool(name: string, args: Json): Promise<ToolResult> {+async function wait(requested: unknown): Promise<string> {+ const seconds = Math.min(requested === undefined ? DEFAULT_WAIT_SECONDS : Number(requested), MAX_WAIT_SECONDS);+ await new Promise((resolve) => setTimeout(resolve, seconds * 1000));+ return seconds < Number(requested) ? `Waited ${seconds} s (a wait is at most ${MAX_WAIT_SECONDS} s)` : `Waited ${seconds} s`;+}++async function act(serial: string, { action, ...fields }: PhoneStep): Promise<string> {+ if (action === "wait") return wait(fields.seconds);+ const [first] = (await callToolOn(serial, action, fields)).content;+ return first.type === "text" ? first.text : "";+}++const reason = (problem: unknown) => (problem instanceof Error ? problem.message : String(problem)).replace(/\.$/, "");+// Mid-batch, earlier steps did run, so a claim text's "This call was not performed" sentence would be false.+const midBatchClaimReason = (message: string) => reason(message.replace(/ This call was not performed[^.]*\./, ""));+const EARLIER_AND_LATER_STEPS = "Steps before it were done; do not repeat them. Later steps were not performed.";++export async function runSteps(+ serial: string,+ steps: PhoneStep[],+ ensureClaim: () => Promise<ClaimOutcome>,+ perform: (serial: string, step: PhoneStep) => Promise<string> = act,+): Promise<ToolResult> {+ const lines: string[] = [];+ for (const [index, step] of steps.entries()) {+ const n = index + 1;+ // Stopping the turn revokes its phone claim while this process lives on, so each later step rechecks it.+ if (n > 1) {+ const claim = await ensureClaim();+ if (!claim.ok) return textResult([...lines, `Stopped before step ${n}: ${midBatchClaimReason(claim.message)}. ${EARLIER_AND_LATER_STEPS}`].join("\n"));+ }+ let output: string;+ try {+ output = await perform(serial, step);+ } catch (error) {+ // An error flag leads models to redo the whole call, so it marks only a first-step failure, where no finished step is redone.+ return textResult([...lines, `Step ${n} failed: ${reason(error)}. Its effect is unknown; call read_screen or screenshot before trying it again. ${EARLIER_AND_LATER_STEPS}`].join("\n"), n === 1);+ }+ lines.push(step.action === "read_screen" ? `${n}. read_screen:\n${output}` : `${n}. ${step.action}: ${output}`);+ }+ return textResult(lines.join("\n"));+}++async function callTool(name: string, args: Json, ensureClaim: () => Promise<ClaimOutcome>): Promise<ToolResult> {if (name === "status") {const adb = resolveAdbPath();const devices = adb ? await usbDevices() : [];return textResult(JSON.stringify({ available: Boolean(adb), devices }, null, 2));}+ if (name === "batch") {+ const steps = parseSteps(args.steps);+ return runSteps(await readySerial(args.serial), steps, ensureClaim);+ }const serial = await readySerial(args.serial);+ return callToolOn(serial, name, args);+}++async function callToolOn(serial: string, name: string, args: Json): Promise<ToolResult> {if (name === "read_screen") return textResult(nodeLines(await readNodes(serial)));if (name === "screenshot") {const png = await onDevice(serial, ["exec-out", "screencap", "-p"], true);@@ -398,7 +611,7 @@ async function handle(message: Json, ensureClaim: () => Promise<ClaimOutcome>) {const claim = await ensureClaim();if (!claim.ok) return ok(id, textResult(claim.message, true));try {- return ok(id, await callTool(name, (params.arguments ?? {}) as Json));+ return ok(id, await callTool(name, (params.arguments ?? {}) as Json, ensureClaim));} catch (error) {return ok(id, textResult(error instanceof Error ? error.message : String(error), true));}diff --git a/shared/phone-steps.ts b/shared/phone-steps.tsnew file mode 100644index 0000000000..eee319f557--- /dev/null+++ b/shared/phone-steps.ts@@ -0,0 +1,4 @@+/** The phone tools a step of the phone server's batch tool can run; a batch may run only where all of them may. */+export const PHONE_STEP_TOOLS = ["open_app", "tap_text", "tap", "swipe", "type_text", "press", "read_screen"] as const;++export type PhoneStepTool = (typeof PHONE_STEP_TOOLS)[number];diff --git a/shared/tool-scope.test.ts b/shared/tool-scope.test.tsindex 3e4680c875..8db31f9d52 100644--- a/shared/tool-scope.test.ts+++ b/shared/tool-scope.test.ts@@ -92,6 +92,21 @@ describe("per-bot tool selection", () => {expect(canUseMcpServer(undefined, "agents", [])).toBe(false);});+ it.each([+ { scope: { deny: ["mcp:phone:type_text"] }, allowed: false },+ { scope: { deny: ["mcp:phone:batch"] }, allowed: false },+ { scope: { allow: ["mcp:phone:batch", "mcp:phone:read_screen"] }, allowed: false },+ { scope: { allow: ["mcp:phone:*"] }, allowed: true },+ { scope: { allow: ["batch", "open_app", "tap_text", "tap", "swipe", "type_text", "press", "read_screen"].map((name) => `mcp:phone:${name}`) }, allowed: true },+ { scope: undefined, allowed: true },+ ])("lets a phone batch run only where all its step tools may: $scope", ({ scope, allowed }) => {+ expect(allowsTool(scope, { kind: "mcp", server: "phone", name: "batch" })).toBe(allowed);+ });++ it("keeps another server's batch tool to its own selector", () => {+ expect(allowsTool({ allow: ["mcp:notes:batch"] }, { kind: "mcp", server: "notes", name: "batch" })).toBe(true);+ });+it("detects added authority without mistaking narrower or equivalent selections for widening", () => {expect(toolScopeWidens({ allow: ["native:read"] }, { allow: ["native:edit", "native:read"] })).toBe(true);expect(toolScopeWidens({ allow: ["native:*"] }, { allow: ["native:read"] })).toBe(false);diff --git a/shared/tool-scope.ts b/shared/tool-scope.tsindex 362f7544e3..d798c4cb5c 100644--- a/shared/tool-scope.ts+++ b/shared/tool-scope.ts@@ -1,4 +1,5 @@import { agentsCallIdentities } from "./agents-tool-names.ts";+import { PHONE_STEP_TOOLS } from "./phone-steps.ts";export type ToolScope = {allow?: string[];@@ -75,6 +76,10 @@ function permitsNamed(scope: ToolScope | undefined, tool: ToolIdentity, names: rfunction permits(scope: ToolScope | undefined, tool: ToolIdentity, args?: unknown): boolean {if (!validName(tool.name) || (tool.kind === "mcp" && !SERVER_NAME.test(tool.server))) return false;+ // A phone batch runs the step tools, so a selection that refuses any of them refuses the batch.+ if (tool.kind === "mcp" && tool.server === "phone" && tool.name === "batch") {+ return ["batch", ...PHONE_STEP_TOOLS].every((name) => permitsNamed(scope, tool, [name]));+ }// An agents call is named by what it does: a selector naming one action's own tool name allows or refuses that action.const named = tool.kind === "mcp" && tool.server === "agents" ? agentsCallIdentities(tool.name, args) : [[tool.name]];return named.some((names) => permitsNamed(scope, tool, names));diff --git a/skills/phone-harness/SKILL.md b/skills/phone-harness/SKILL.mdindex 1b35724c72..e432969b43 100644--- a/skills/phone-harness/SKILL.md+++ b/skills/phone-harness/SKILL.md@@ -16,10 +16,13 @@ with Bash, raw `adb`, `subprocess`, an emulator, network ADB, or Tailscale.2. Call `open_app` with the human app name. Do not scan the launcher first.Use `list_apps` only when the name is ambiguous or not found, then pass thepackage name.-3. Call `read_screen` before choosing a target and after every action. Prefer- `tap_text`; use `screenshot` and pixel `tap` only when accessibility text- cannot identify the target.-4. Use `swipe`, `type_text`, and `press` for interaction, verifying each step.+3. Call `read_screen` before choosing a target. After that, to act and see the+ result, put the action and `read_screen` in one `batch`. Prefer `tap_text`;+ use `screenshot` and pixel `tap` only when accessibility text cannot+ identify the target.+4. Use `swipe`, `type_text`, and `press` for interaction. When you know the+ next few steps, put them in one `batch`. To wait for content to load, add a+ `wait` step to the batch, not Bash `sleep`.The tools operate the user's real phone. Navigate and read only what the taskneeds. Stop before sending, posting, purchasing, booking, deleting, changing