UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

274 lines (273 loc) • 14.4 kB
import { execFile } from "node:child_process"; import { randomUUID } from "node:crypto"; import { readFile, unlink } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { verifiedHelper } from "./native-helpers.js"; import { execProbe } from "./probe-processes.js"; import { BridgeError } from "./protocol.js"; // simulator-stream.ts imports verifiedHelper from this module. export { verifiedHelper }; const execFileAsync = promisify(execFile); /** Every simulator child is killed outright at its timeout. SIGTERM, the * default, let one that ignored it hold its promise, and with it a stream's * slot, for good. */ const exec = (file, args, options) => (args[0] === "simctl" && ["list", "listapps"].includes(args[1]) ? execProbe : execFileAsync)(file, args, { ...options, killSignal: "SIGKILL", encoding: "utf8" }); export const SIMULATOR_UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i; /** `simctl list devices [filter] -j`, parsed (every device without a filter); undefined when simctl failed, timed * out or answered nonsense. */ async function listDevices(filter) { const listed = await exec("/usr/bin/xcrun", ["simctl", "list", "devices", ...(filter ? [filter] : []), "-j"], { timeout: 8_000, maxBuffer: 8_388_608 }).catch(() => undefined); if (!listed) return undefined; try { return JSON.parse(listed.stdout); } catch { return undefined; } } /** com.apple.CoreSimulator.SimRuntime.iOS-26-1 → iOS 26.1 */ const runtimeName = (runtimeID) => runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " "); /** The iOS simulators booted on this Mac, from `simctl`; none elsewhere. */ export async function bootedSimulators() { if (process.platform !== "darwin") return []; const parsed = await listDevices("booted") ?? {}; const list = []; for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) { const runtime = runtimeName(runtimeID); for (const device of devices ?? []) { if (device.state !== "Booted" || !device.udid || !SIMULATOR_UDID.test(device.udid)) continue; list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime }); if (list.length >= 16) return list; } } return list; } /** Most devices `GET /v1/simulators?all=1` lists. */ export const SIMULATOR_DEVICE_LIMIT = 64; /** * Every iOS simulator this Mac can run (`simctl list devices available`), booted or not, with its `state` * (`Booted`, `Shutdown`, `Booting`, `Shutting Down`): booted ones first, then the newest runtime, then by * name, at most SIMULATOR_DEVICE_LIMIT. For the phone's device picker, which boots one from here. */ export async function simulatorDevices() { if (process.platform !== "darwin") return []; const parsed = await listDevices("available") ?? {}; const list = []; for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) { if (!/SimRuntime\.iOS-/.test(runtimeID)) continue; const version = (/iOS-(\d+)-(\d+)/.exec(runtimeID) ?? []).slice(1).map(Number); for (const device of devices ?? []) { if (device.isAvailable === false || !device.udid || !SIMULATOR_UDID.test(device.udid)) continue; const state = typeof device.state === "string" && /^[A-Za-z ]{1,32}$/.test(device.state) ? device.state : "Unknown"; list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime: runtimeName(runtimeID), state, version }); } } const newer = (a, b) => (b[0] ?? 0) - (a[0] ?? 0) || (b[1] ?? 0) - (a[1] ?? 0); return list.sort((a, b) => Number(b.state === "Booted") - Number(a.state === "Booted") || newer(a.version, b.version) || a.name.localeCompare(b.name)) .slice(0, SIMULATOR_DEVICE_LIMIT).map(({ version: _version, ...device }) => device); } /** A simulator's state as `simctl` reports it now, from every device it has (a booted device whose runtime is no * longer available still shuts down): `missing` when simctl lists no such device, undefined when it couldn't say. */ async function deviceState(udid) { const listed = await listDevices(); if (!listed) return undefined; for (const devices of Object.values(listed.devices ?? {})) { const device = devices?.find(d => d.udid?.toUpperCase() === udid.toUpperCase()); if (device) return String(device.state ?? ""); } return "missing"; } /** A PNG of one booted simulator's screen. */ export async function simulatorScreenshot(udid) { if (!SIMULATOR_UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier."); if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only."); const file = path.join(tmpdir(), `phren-sim-${randomUUID()}.png`); try { await exec("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file], { timeout: 15_000 }); return await readFile(file); } catch (error) { if (error instanceof BridgeError) throw error; throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?"); } finally { await unlink(file).catch(() => undefined); } } /** A drag's duration bounds, in ms. */ export const DRAG_DEFAULT_MS = 300, DRAG_MIN_MS = 50, DRAG_MAX_MS = 5_000; /** The native helpers are built in native-helpers.ts (simtap for input, simcast * for simulator-stream.ts). */ let inputQueue = Promise.resolve(); function simtap(name, ...args) { const task = inputQueue.catch(() => { }).then(() => executeSimtap(name, ...args)); inputQueue = task; return task; } async function executeSimtap(name, ...args) { const binary = await verifiedHelper(); try { await exec(binary, [name, ...args], { timeout: 60_000 }); } catch (error) { const failure = error; const message = String(failure?.stderr ?? failure?.message ?? ""); if (/accessibility/.test(message)) { await promptAccessibility(binary, false); throw new BridgeError(403, accessibilityHelp(binary), { code: "simulator-accessibility", helper: binary }); } if (/no window/.test(message)) throw new BridgeError(409, "That simulator has no window on screen."); if (/not running/.test(message)) throw new BridgeError(409, "The Simulator app is not running."); throw new BridgeError(409, `The simulator did not take that: ${message.slice(0, 160) || "unknown error"}`); } } /** The steps for the Accessibility grant, for the 403 and the docs. */ export function accessibilityHelp(binary) { return "Touches and keys need Accessibility for Phren's simulator helper. On the Mac, open System Settings → Privacy & Security → Accessibility and switch on simtap. " + `If it isn't listed, click +, press ⌘⇧G, paste ${binary} and click Open.`; } /** Asks macOS for the helper's Accessibility grant: the helper joins the * Accessibility list, switched off, and the system dialog shows. Once per Hook * run unless the person asks again, so a burst of taps raises one dialog. * Resolves whether the helper is already trusted. */ let prompted = false; async function promptAccessibility(binary, force) { if (prompted && !force) return false; prompted = true; return exec(binary, ["-", "prompt"], { timeout: 15_000 }).then(() => true, () => false); } const ACCESSIBILITY_PANE = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"; // macOS virtual key codes. const KEY_H = "4", KEY_L = "37"; export async function simulatorAct(udid, request) { if (!SIMULATOR_UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier."); if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "drag", "screenshot-ready", "accessibility-settings"].includes(request.action)) throw new BridgeError(400, "Unknown simulator action."); if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only."); const simctl = (...args) => exec("/usr/bin/xcrun", ["simctl", ...args], { timeout: 30_000 }).catch(() => { throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`); }); // Boot and shutdown take any device, booted or not, and a device already in (or on its way to) the asked-for // state is not a failure: the phone's picker may be a moment behind. A list that failed (simctl slow to start) // is no reason to refuse; simctl itself then says. const settle = async (verb, done) => { const state = await deviceState(udid); if (state === "missing") throw new BridgeError(404, "No such simulator on this Mac."); if (state !== undefined && done.includes(state)) return; try { await simctl(verb, udid); } catch (error) { const now = await deviceState(udid); if (now === undefined || !done.includes(now)) throw error; } }; switch (request.action) { case "boot": await settle("boot", ["Booted", "Booting"]); // Taps, drags and keys go to the device's window in the Simulator app, which booting alone doesn't open. await exec("/usr/bin/open", ["-a", "Simulator", "--args", "-CurrentDeviceUDID", udid.toUpperCase()], { timeout: 15_000 }).catch(() => undefined); break; case "shutdown": await settle("shutdown", ["Shutdown", "Shutting Down"]); break; case "launch": if (typeof request.bundleId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9.-]{2,199}$/.test(request.bundleId)) throw new BridgeError(400, "Invalid bundle identifier."); await simctl("launch", udid, request.bundleId); break; case "openurl": if (typeof request.url !== "string" || !/^[a-z][a-z0-9+.-]*:/i.test(request.url) || request.url.length > 2048) throw new BridgeError(400, "Invalid URL."); await simctl("openurl", udid, request.url); break; case "home": await simtap(await deviceName(udid), "key", KEY_H, "cmd", "shift"); break; case "lock": await simtap(await deviceName(udid), "key", KEY_L, "cmd"); break; case "type": if (typeof request.text !== "string" || !request.text || request.text.length > 500 || /[\x00-\x09\x0b-\x1f\x7f]/.test(request.text) || (request.text.includes("\n") && request.submit !== true) || (request.submit !== undefined && typeof request.submit !== "boolean")) throw new BridgeError(400, "Type at most 500 characters; newlines require submit: true and other control characters are forbidden."); await simtap(await deviceName(udid), "type", request.text, ...(request.submit === true ? ["submit"] : [])); break; case "tap": { // x and y are fractions of the screenshot. const { x, y } = request; if (![x, y].every(v => typeof v === "number" && v >= 0 && v <= 1)) throw new BridgeError(400, "Tap outside the screen."); await simtap(await deviceName(udid), "tap", String(x), String(y)); break; } case "drag": { // From and to are fractions of the screenshot, as a tap's are. const { x1, y1, x2, y2 } = request, durationMs = request.durationMs ?? DRAG_DEFAULT_MS; if (![x1, y1, x2, y2].every(v => typeof v === "number" && v >= 0 && v <= 1)) throw new BridgeError(400, "Drag outside the screen."); if (typeof durationMs !== "number" || !Number.isInteger(durationMs) || durationMs < DRAG_MIN_MS || durationMs > DRAG_MAX_MS) { throw new BridgeError(400, `A drag takes ${DRAG_MIN_MS} to ${DRAG_MAX_MS} ms.`); } await simtap(await deviceName(udid), "drag", String(x1), String(y1), String(x2), String(y2), String(durationMs)); break; } case "screenshot-ready": break; case "accessibility-settings": { // The phone's "Open Accessibility settings": ask for the grant again and // open the pane on this Mac, where the switch is. const binary = await verifiedHelper(); const trusted = await promptAccessibility(binary, true); await exec("/usr/bin/open", [ACCESSIBILITY_PANE], { timeout: 15_000 }).catch(() => { throw new BridgeError(409, "Couldn't open System Settings on the Mac."); }); return { ok: true, trusted, helper: binary }; } default: throw new BridgeError(400, "Unknown simulator action."); } return { ok: true }; } async function deviceName(udid) { const device = (await bootedSimulators()).find(d => d.udid === udid.toUpperCase()); if (!device) throw new BridgeError(409, "That simulator is not booted."); return String(device.name); } /** The apps a simulator has, for the launcher. */ export async function simulatorApps(udid) { if (!SIMULATOR_UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier."); if (process.platform !== "darwin") return []; const { stdout } = await exec("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15_000, maxBuffer: 4_194_304 }).catch(() => ({ stdout: "" })); const apps = []; const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/); for (const block of blocks) { const id = /CFBundleIdentifier = "?([^";\n]+)"?;/.exec(block)?.[1], name = /CFBundleDisplayName = "?([^";\n]+)"?;/.exec(block)?.[1]; const type = /ApplicationType = "?([^";\n]+)"?;/.exec(block)?.[1]; if (id && name && type === "User" && !/\.xctrunner$/.test(id)) apps.push({ bundleId: id, name }); } return apps.sort((a, b) => String(a.name).localeCompare(String(b.name))).slice(0, 100); }