agent-device 0.12.2 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/bin.js CHANGED
@@ -1,7 +1,7 @@
1
- let e,t,r,n,a,i,o;import s from"node:path";import{styleText as l}from"node:util";import{fileURLToPath as u,pathToFileURL as c}from"node:url";import p from"node:net";import d from"node:http";import m from"node:https";import f,{promises as h}from"node:fs";import{spawn as g}from"node:child_process";import{createHash as y}from"node:crypto";import w from"node:os";import{PNG as b}from"pngjs";import{parseDeviceRotation as v,SESSION_SURFACES as x,readProcessCommand as k,waitForProcessExit as I,serializeSessionListEntry as A,serializeSnapshotResult as D,isAgentDeviceDaemonProcess as S,buildDeviceIdentifiers as $,buildAppIdentifiers as M,isEnvTruthy as P,parseBatchStepsJson as N,computeDaemonCodeSignature as L,resolveDaemonTransportPreference as E,splitSelectorFromArgs as R,serializeOpenResult as _,parseWaitArgs as T,expandUserHomePath as O,serializeDeployResult as C,readCommandMessage as U,serializeEnsureSimulatorResult as F,serializeDevice as j,buildSnapshotDisplayLines as V,buildMobileSnapshotPresentation as B,createRequestId as G,tryParseSelectorChain as q,readVersion as X,displayNodeLabel as Y,findProjectRoot as H,getDiagnosticsMeta as J,withDiagnosticTimer as K,resolveUserPath as z,serializeCloseResult as W,emitDiagnostic as Z,SETTINGS_USAGE_OVERRIDE as Q,isProcessAlive as ee,readProcessStartTime as et,withDiagnosticsScope as er,resolveDaemonPaths as en,flushDiagnosticsToSessionFile as ea,resolveDaemonServerMode as ei,serializeInstallFromSourceResult as eo,decodePng as es,stopProcessForTakeover as el,formatSnapshotLine as eu}from"./155.js";import{whichCmd as ec,runCmdDetached as ep,runCmdSync as ed,asAppError as em,normalizeError as ef,runCmd as eh,AppError as eg}from"./818.js";import{METRO_COMPANION_RUN_ARG as ey,normalizeBaseUrl as ew,buildBundleUrl as eb,ENV_SERVER_BASE_URL as ev,ENV_LOCAL_BASE_URL as ex,ENV_STATE_PATH as ek,ENV_LAUNCH_URL as eI,ENV_BEARER_TOKEN as eA}from"./320.js";import{maybeRunUpgradeNotifier as eD}from"./113.js";function eS(e,t){for(let[r,n]of Object.entries(t))void 0!==n&&(e[r]=n);return e}let e$=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],eM=["snapshotDepth","snapshotScope","snapshotRaw"],eP=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","apple"],usageLabel:"--platform ios|macos|android|linux|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:x,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Test: maximum wall-clock time per script attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG; diff screenshot: also write a separate current-screen overlay guide"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],eN=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),eL={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{usageOverride:"snapshot [--diff] [-i] [-c] [-d <depth>] [-s <scope>] [--raw]",helpDescription:"Capture accessibility tree or diff against the previous session baseline",positionalArgs:[],allowedFlags:["snapshotDiff",...e$]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind"],allowedFlags:[...e$,"baseline","threshold","out","overlayRefs"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare --public-base-url <url> [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]",listUsageOverride:"metro prepare --public-base-url <url>",helpDescription:"Prepare a local Metro runtime and optionally bridge it through a remote host",summary:"Prepare local Metro runtime",positionalArgs:["prepare"],allowedFlags:["metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss the device keyboard",summary:"Inspect or dismiss the device keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics",summary:"Show performance metrics",positionalArgs:[],allowedFlags:[]},back:{usageOverride:"back [--in-app|--system]",helpDescription:"Navigate back with explicit app or system semantics",summary:"Go back",positionalArgs:[],allowedFlags:["backMode"]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},rotate:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",summary:"Rotate device orientation",positionalArgs:["orientation"],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...eM]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",helpDescription:"Inspect or handle alert (iOS simulator and macOS desktop)",summary:"Inspect or handle iOS/macOS alerts",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",helpDescription:"Tap/click by coordinates, snapshot ref, or selector",summary:"Tap by coordinates, ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap","clickButton",...eM]},get:{usageOverride:"get text|attrs <@ref|selector>",helpDescription:"Return element text/attributes by ref or selector",summary:"Get text or attrs by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...eM]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},test:{usageOverride:"test <path-or-glob>...",listUsageOverride:"test <path-or-glob>...",helpDescription:"Run one or more .ad scripts as a serial test suite",summary:"Run .ad test suites",positionalArgs:["pathOrGlob"],allowsExtraPositionals:!0,allowedFlags:["replayUpdate","failFast","timeoutMs","retries","artifactsDir","reportJunit"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",helpDescription:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",summary:"Press by coordinates, ref, or selector",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...eM]},longpress:{helpDescription:"Long press by coordinates (iOS and Android)",summary:"Long press by coordinates",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",summary:"Swipe coordinates",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{helpDescription:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{helpDescription:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:["delayMs"]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",helpDescription:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...eM,"delayMs"]},scroll:{usageOverride:"scroll <direction> [amount] [--pixels <n>]",helpDescription:"Scroll in direction (relative amount or explicit pixels)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:["pixels"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...eM]},settings:{usageOverride:Q,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, appearance, and app permissions (macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location remain unsupported on macOS; mobile permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",helpDescription:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},eE=new Map,eR=new Map;for(let e of eP){for(let t of e.names)eE.set(t,e);let t=eR.get(e.key);t?t.push(e):eR.set(e.key,[e])}function e_(e){if(e)return eL[e]}function eT(){return Object.keys(eL)}function eO(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let eC=(e=`agent-device <command> [args] [--json]
1
+ let e,t,r,n,a,i,o;import s from"node:path";import{styleText as l}from"node:util";import{fileURLToPath as c,pathToFileURL as u}from"node:url";import d from"node:net";import p from"node:http";import m from"node:https";import f,{promises as h}from"node:fs";import{spawn as g}from"node:child_process";import y,{createHash as w}from"node:crypto";import b from"node:os";import{PNG as v}from"pngjs";import{parseDeviceRotation as I,SESSION_SURFACES as k,readProcessCommand as x,waitForProcessExit as A,serializeSessionListEntry as S,serializeSnapshotResult as D,isAgentDeviceDaemonProcess as $,buildDeviceIdentifiers as M,buildAppIdentifiers as P,isEnvTruthy as N,parseBatchStepsJson as L,computeDaemonCodeSignature as R,resolveDaemonTransportPreference as _,splitSelectorFromArgs as E,serializeOpenResult as T,parseWaitArgs as C,expandUserHomePath as O,serializeDeployResult as U,readCommandMessage as F,serializeEnsureSimulatorResult as j,serializeDevice as B,buildSnapshotDisplayLines as V,buildMobileSnapshotPresentation as G,createRequestId as q,tryParseSelectorChain as H,readVersion as K,displayNodeLabel as X,findProjectRoot as Y,getDiagnosticsMeta as J,withDiagnosticTimer as z,resolveUserPath as W,serializeCloseResult as Z,emitDiagnostic as Q,SETTINGS_USAGE_OVERRIDE as ee,isProcessAlive as et,readProcessStartTime as er,withDiagnosticsScope as en,resolveDaemonPaths as ea,flushDiagnosticsToSessionFile as ei,resolveDaemonServerMode as eo,serializeInstallFromSourceResult as es,decodePng as el,stopProcessForTakeover as ec,formatSnapshotLine as eu}from"./155.js";import{whichCmd as ed,runCmdDetached as ep,runCmdSync as em,asAppError as ef,normalizeError as eh,runCmd as eg,AppError as ey}from"./818.js";import{METRO_COMPANION_RUN_ARG as ew,normalizeBaseUrl as eb,buildBundleUrl as ev,ENV_SERVER_BASE_URL as eI,ENV_LOCAL_BASE_URL as ek,ENV_STATE_PATH as ex,ENV_LAUNCH_URL as eA,ENV_SCOPE_TENANT_ID as eS,ENV_SCOPE_RUN_ID as eD,ENV_BEARER_TOKEN as e$,ENV_SCOPE_LEASE_ID as eM}from"./320.js";import{maybeRunUpgradeNotifier as eP}from"./113.js";function eN(e,t){for(let[r,n]of Object.entries(t))void 0!==n&&(e[r]=n);return e}let eL=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],eR=["snapshotDepth","snapshotScope","snapshotRaw"],e_=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"leaseBackend",names:["--lease-backend"],type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"],usageLabel:"--lease-backend ios-simulator|ios-instance|android-instance",usageDescription:"Lease backend for remote tenant connection admission"},{key:"force",names:["--force"],type:"boolean",usageLabel:"--force",usageDescription:"Force connection state replacement when reconnecting"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","apple"],usageLabel:"--platform ios|macos|android|linux|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:k,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Test: maximum wall-clock time per script attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG; diff screenshot: also write a separate current-screen overlay guide"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],eE=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","leaseBackend","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),eT={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},connect:{usageOverride:"connect --remote-config <path> [--tenant <id>] [--run-id <id>] [--lease-backend <backend>] [--force]",helpDescription:"Connect to a remote daemon, allocate a tenant lease, and prepare Metro",summary:"Connect to remote daemon",positionalArgs:[],allowedFlags:["force","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps","launchUrl"],skipCapabilityCheck:!0},disconnect:{helpDescription:"Disconnect remote daemon state, stop owned Metro companion, and release lease",summary:"Disconnect remote daemon",positionalArgs:[],allowedFlags:["shutdown"],skipCapabilityCheck:!0},connection:{usageOverride:"connection status",listUsageOverride:"connection status",helpDescription:"Inspect active remote connection state",summary:"Inspect remote connection",positionalArgs:["status"],allowedFlags:[],skipCapabilityCheck:!0},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{usageOverride:"snapshot [--diff] [-i] [-c] [-d <depth>] [-s <scope>] [--raw]",helpDescription:"Capture accessibility tree or diff against the previous session baseline",positionalArgs:[],allowedFlags:["snapshotDiff",...eL]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [current.png] [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind","current?"],allowedFlags:[...eL,"baseline","threshold","out","overlayRefs"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare --public-base-url <url> [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]",listUsageOverride:"metro prepare --public-base-url <url>",helpDescription:"Prepare a local Metro runtime and optionally bridge it through a remote host",summary:"Prepare local Metro runtime",positionalArgs:["prepare"],allowedFlags:["metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss the device keyboard",summary:"Inspect or dismiss the device keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics",summary:"Show performance metrics",positionalArgs:[],allowedFlags:[]},back:{usageOverride:"back [--in-app|--system]",helpDescription:"Navigate back with explicit app or system semantics",summary:"Go back",positionalArgs:[],allowedFlags:["backMode"]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},rotate:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",summary:"Rotate device orientation",positionalArgs:["orientation"],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...eR]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",helpDescription:"Inspect or handle alert (iOS simulator and macOS desktop)",summary:"Inspect or handle iOS/macOS alerts",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",helpDescription:"Tap/click by coordinates, snapshot ref, or selector",summary:"Tap by coordinates, ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap","clickButton",...eR]},get:{usageOverride:"get text|attrs <@ref|selector>",helpDescription:"Return element text/attributes by ref or selector",summary:"Get text or attrs by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...eR]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},test:{usageOverride:"test <path-or-glob>...",listUsageOverride:"test <path-or-glob>...",helpDescription:"Run one or more .ad scripts as a serial test suite",summary:"Run .ad test suites",positionalArgs:["pathOrGlob"],allowsExtraPositionals:!0,allowedFlags:["replayUpdate","failFast","timeoutMs","retries","artifactsDir","reportJunit"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",helpDescription:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",summary:"Press by coordinates, ref, or selector",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...eR]},longpress:{helpDescription:"Long press by coordinates (iOS and Android)",summary:"Long press by coordinates",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",summary:"Swipe coordinates",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{helpDescription:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{helpDescription:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:["delayMs"]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",helpDescription:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...eR,"delayMs"]},scroll:{usageOverride:"scroll <direction> [amount] [--pixels <n>]",helpDescription:"Scroll in direction (relative amount or explicit pixels)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:["pixels"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...eR]},settings:{usageOverride:ee,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, appearance, and app permissions (macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location remain unsupported on macOS; mobile permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",helpDescription:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},eC=new Map,eO=new Map;for(let e of e_){for(let t of e.names)eC.set(t,e);let t=eO.get(e.key);t?t.push(e):eO.set(e.key,[e])}function eU(e){if(e)return eT[e]}function eF(){return Object.keys(eT)}function ej(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let eB=(e=`agent-device <command> [args] [--json]
2
2
 
3
3
  CLI to control iOS and Android devices for AI agents.
4
- `,t=ej("Commands:",eT().map(e=>{let t=eL[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let r=t.positionalArgs.map(r=>{var n,a,i;let o,s,l,u;return n=e,a=t,s=(o=(i=r).endsWith("?"))?i.slice(0,-1):i,u=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(s))||void 0!==a.usageOverride&&a.usageOverride.startsWith(`${n} ${s}`),o?l?`[${s}]`:u?s:`[${s}]`:u?s:`<${s}>`});return[e,...r].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),r=eF("Flags:",eU(eN)),n=[ej("Agent Skills:",[{label:"agent-device",description:"Canonical mobile automation flows"},{label:"dogfood",description:"Exploratory QA and bug hunts"}]),"See `skills/<name>/SKILL.md` in the installed package."].join("\n\n"),a=eV("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),i=ej("Environment:",[{label:"AGENT_DEVICE_SESSION",description:"Default session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"}]),o=eV("Examples:",["agent-device open Settings --platform ios","agent-device open TextEdit --platform macos","agent-device snapshot -i",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"]),`${e}
4
+ `,t=eq("Commands:",eF().map(e=>{let t=eT[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let r=t.positionalArgs.map(r=>{var n,a,i;let o,s,l,c;return n=e,a=t,s=(o=(i=r).endsWith("?"))?i.slice(0,-1):i,c=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(s))||void 0!==a.usageOverride&&a.usageOverride.startsWith(`${n} ${s}`),o?l?`[${s}]`:c?s:`[${s}]`:c?s:`<${s}>`});return[e,...r].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),r=eG("Flags:",eV(eE)),n=[eq("Agent Skills:",[{label:"agent-device",description:"Canonical mobile automation flows"},{label:"dogfood",description:"Exploratory QA and bug hunts"}]),"See `skills/<name>/SKILL.md` in the installed package."].join("\n\n"),a=eH("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),i=eq("Environment:",[{label:"AGENT_DEVICE_SESSION",description:"Default session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"}]),o=eH("Examples:",["agent-device open Settings --platform ios","agent-device open TextEdit --platform macos","agent-device snapshot -i",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"]),`${e}
5
5
  ${t}
6
6
 
7
7
  ${r}
@@ -13,76 +13,77 @@ ${a}
13
13
  ${i}
14
14
 
15
15
  ${o}
16
- `);function eU(e){return eP.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function eF(e,t){return ej(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function ej(e,t){if(0===t.length)return`${e}
17
- (none)`;let r=Math.max(...t.map(e=>e.label.length))+2,n=[e];for(let e of t)n.push(` ${e.label.padEnd(r)}${e.description}`);return n.join("\n")}function eV(e,t){return 0===t.length?`${e}
18
- (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let eB=new Set(["1","true","yes","on"]),eG=new Set(["0","false","no","off"]);function eq(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function eX(e,t,r,n){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>eX({...e,multiple:!1},t,r,n));if("boolean"===e.type){var a=t,i=r,o=n;if("boolean"==typeof a)return a;if("string"==typeof a){let e=eY(a);if(void 0!==e)return e}throw new eg("INVALID_ARGS",`Invalid value for "${o}" in ${i}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==eY(t))return eY(t);if("string"==typeof t&&t.trim().length>0)return t;throw new eg("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new eg("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var s=e,l=t,u=r,c=n;let a=s.setValue;if(l===a)return a;if("string"==typeof l){let e=l.trim();if(""===e||"true"===e||"1"===e)return a;if("false"===e||"0"===e)return}if(!0===l)return a;if(!1!==l)throw new eg("INVALID_ARGS",`Invalid value for "${c}" in ${u}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new eg("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let p="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(p)||!Number.isInteger(p))throw new eg("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected integer.`);if("number"==typeof e.min&&p<e.min)throw new eg("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&p>e.max)throw new eg("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Must be <= ${e.max}.`);return p}function eY(e){let t=e.trim().toLowerCase();return!!eB.has(t)||!eG.has(t)&&void 0}let eH=new Set(["config","remoteConfig","help","version","batchSteps"]),eJ={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eK=function(){let e=new Map;for(let t of eP){let r=e.get(t.key);r?r.push(t):e.set(t.key,[t])}let t=new Map;for(let e of eN)t.set(e,new Set(["*"]));for(let e of eT()){let r=e_(e);if(r)for(let n of r.allowedFlags){let r=t.get(n);r&&r.has("*")||(r?r.add(e):t.set(n,new Set([e])))}}return[...e.entries()].map(([e,r])=>({key:e,flagDefinitions:r,config:{enabled:!eH.has(e),key:e},env:{names:[eq(e),...eJ[e]??[]]},supportsCommand(r){let n=t.get(e);return!!n&&(!!n.has("*")||!!r&&n.has(r))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),ez=new Map(eK.map(e=>[e.key,e]));function eW(e,t){return ez.get(e)?.supportsCommand(t)??!1}function eZ(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let r=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===r.type){let t=e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...r,setValue:void 0,enumValues:t}}return r}function eQ(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function e0(e){return e.replace(/^-+/,"")}function e1(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?eQ(e):[e,void 0];return void 0!==eE.get(t)}function e2(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function e3(e){process.stdout.write(`${JSON.stringify(e,null,2)}
19
- `)}function e5(e,t={}){let r=e instanceof eg?ef(e):e;process.stderr.write(`Error (${r.code}): ${r.message}
16
+ `);function eV(e){return e_.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function eG(e,t){return eq(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function eq(e,t){if(0===t.length)return`${e}
17
+ (none)`;let r=Math.max(...t.map(e=>e.label.length))+2,n=[e];for(let e of t)n.push(` ${e.label.padEnd(r)}${e.description}`);return n.join("\n")}function eH(e,t){return 0===t.length?`${e}
18
+ (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let eK=new Set(["1","true","yes","on"]),eX=new Set(["0","false","no","off"]);function eY(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function eJ(e,t,r,n){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>eJ({...e,multiple:!1},t,r,n));if("boolean"===e.type){var a=t,i=r,o=n;if("boolean"==typeof a)return a;if("string"==typeof a){let e=ez(a);if(void 0!==e)return e}throw new ey("INVALID_ARGS",`Invalid value for "${o}" in ${i}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==ez(t))return ez(t);if("string"==typeof t&&t.trim().length>0)return t;throw new ey("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new ey("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var s=e,l=t,c=r,u=n;let a=s.setValue;if(l===a)return a;if("string"==typeof l){let e=l.trim();if(""===e||"true"===e||"1"===e)return a;if("false"===e||"0"===e)return}if(!0===l)return a;if(!1!==l)throw new ey("INVALID_ARGS",`Invalid value for "${u}" in ${c}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new ey("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let d="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(d)||!Number.isInteger(d))throw new ey("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Expected integer.`);if("number"==typeof e.min&&d<e.min)throw new ey("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&d>e.max)throw new ey("INVALID_ARGS",`Invalid value for "${n}" in ${r}. Must be <= ${e.max}.`);return d}function ez(e){let t=e.trim().toLowerCase();return!!eK.has(t)||!eX.has(t)&&void 0}let eW=new Set(["config","remoteConfig","help","version","batchSteps"]),eZ={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eQ=function(){let e=new Map;for(let t of e_){let r=e.get(t.key);r?r.push(t):e.set(t.key,[t])}let t=new Map;for(let e of eE)t.set(e,new Set(["*"]));for(let e of eF()){let r=eU(e);if(r)for(let n of r.allowedFlags){let r=t.get(n);r&&r.has("*")||(r?r.add(e):t.set(n,new Set([e])))}}return[...e.entries()].map(([e,r])=>({key:e,flagDefinitions:r,config:{enabled:!eW.has(e),key:e},env:{names:[eY(e),...eZ[e]??[]]},supportsCommand(r){let n=t.get(e);return!!n&&(!!n.has("*")||!!r&&n.has(r))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),e0=new Map(eQ.map(e=>[e.key,e]));function e1(e,t){return e0.get(e)?.supportsCommand(t)??!1}function e2(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let r=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===r.type){let t=e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...r,setValue:void 0,enumValues:t}}return r}function e3(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function e5(e){return e.replace(/^-+/,"")}function e8(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?e3(e):[e,void 0];return void 0!==eC.get(t)}function e4(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function e6(e){process.stdout.write(`${JSON.stringify(e,null,2)}
19
+ `)}function e7(e,t={}){let r=e instanceof ey?eh(e):e;process.stderr.write(`Error (${r.code}): ${r.message}
20
20
  `),r.hint&&process.stderr.write(`Hint: ${r.hint}
21
21
  `),r.diagnosticId&&process.stderr.write(`Diagnostic ID: ${r.diagnosticId}
22
22
  `),r.logPath&&process.stderr.write(`Diagnostics Log: ${r.logPath}
23
23
  `),t.showDetails&&r.details&&process.stderr.write(`${JSON.stringify(r.details,null,2)}
24
- `)}function e8(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function e4(e){return e>0?`+${e}`:String(e)}function e6(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:"",r=e.regionIndex?` r${e.regionIndex}`:"";return`${e.likelyKind}${t}${r}`}function e7(e){return e.min===e.max?e4(e.min):`${e4(e.min)}..${e4(e.max)}`}function e9(e){let t=process.cwd(),r=s.relative(t,e);return""!==r&&(r.startsWith("..")||s.isAbsolute(r))?e:""===r?".":`.${s.sep}${r}`}function te(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function tt(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function tr(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function tn(e){var t;let r="scroll-area"===(t=e.type)||"list"===t||"collection"===t||"table"===t?t:null;if(!r)return[];let n=[];if(e.node.hiddenContentAbove&&n.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&n.push(`[content below ${r} hidden]`),0===n.length)return[];let a=" ".repeat(e.depth+1);return n.map(e=>`${a}${e}`)}let ta="sha256";async function ti(e){let{localPath:t,baseUrl:r,token:n}=e,a=f.statSync(t),i=a.isDirectory(),o=s.basename(t),l=i?"app-bundle":"file",u=r.endsWith("/")?r:`${r}/`,c=i?void 0:await ts(t);if(c){let e=await to({normalizedBase:u,token:n,hash:c,filename:o,sizeBytes:a.size,artifactType:l});if(e)return e}let p=new URL("upload",u),h="https:"===p.protocol?m:d,y={"x-artifact-type":l,"x-artifact-filename":o,"transfer-encoding":"chunked"};return c&&(y["x-artifact-hash"]=c,y["x-artifact-hash-algorithm"]=ta),n&&(y.authorization=`Bearer ${n}`,y["x-agent-device-token"]=n),new Promise((e,r)=>{let n=h.request({protocol:p.protocol,host:p.hostname,port:p.port,method:"POST",path:p.pathname+p.search,headers:y},t=>{let n="";t.setEncoding("utf8"),t.on("data",e=>{n+=e}),t.on("end",()=>{clearTimeout(a);try{let t=JSON.parse(n);if(!t.ok||!t.uploadId)return void r(new eg("COMMAND_FAILED",`Upload failed: ${n}`));e(t.uploadId)}catch{r(new eg("COMMAND_FAILED",`Invalid upload response: ${n}`))}})}),a=setTimeout(()=>{n.destroy(),r(new eg("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(n.on("error",e=>{clearTimeout(a),r(new eg("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),i){let e=g("tar",["cf","-","-C",s.dirname(t),s.basename(t)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(n),e.on("error",e=>{n.destroy(),r(new eg("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(n.destroy(),r(new eg("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=f.createReadStream(t);e.pipe(n),e.on("error",e=>{n.destroy(),r(new eg("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}async function to(e){var t;let r=new URL("upload/preflight",e.normalizedBase),n={"content-type":"application/json"};e.token&&(n.authorization=`Bearer ${e.token}`,n["x-agent-device-token"]=e.token);let a=await fetch(r,{method:"POST",headers:n,signal:AbortSignal.timeout(3e4),body:JSON.stringify({hash:e.hash,hashAlgorithm:ta,fileName:e.filename,sizeBytes:e.sizeBytes,artifactType:e.artifactType})}).catch(()=>void 0);if(!a?.ok)return;let i=await a.json().catch(()=>void 0);return(t=i)&&"object"==typeof t&&!0===t.ok&&!0===t.cacheHit&&"string"==typeof t.uploadId?i.uploadId:void 0}async function ts(e){let t=y(ta);return await new Promise((r,n)=>{f.createReadStream(e).on("data",e=>t.update(e)).on("error",e=>{n(new eg("COMMAND_FAILED","Failed to read local artifact",{},e))}).on("end",r)}),t.digest("hex")}let tl=tB(),tu=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),tc=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),tp=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],td=new p.BlockList;async function tm(e){let t=e.meta?.requestId??G(),r=!!(e.meta?.debug||e.flags?.verbose),n=function(e){let t,r=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,n=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new eg("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new eg("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),a=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var i=n,o=a;if(!(!i||"localhost"===(t=new URL(i).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(p.isIPv4(t)?td.check(t,"ipv4"):!!p.isIPv6(t)&&td.check(t,"ipv6")))&&("string"!=typeof o||!(o.trim().length>0)))throw new eg("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:i,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let s=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,l=E(s);if(n&&"socket"===l)throw new eg("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:n});let u=ei(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===s?"dual":void 0));return{paths:en(r),transportPreference:l,serverMode:u,remoteBaseUrl:n,remoteAuthToken:a}}(e),a=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return tB(t)}(e.command),i=await K("daemon_startup",async()=>await tw(n),{requestId:t,session:e.session}),o=await tf(e,i),s={...e,positionals:o.positionals,flags:o.flags,token:i.token,meta:{...e.meta??{},requestId:t,debug:r,cwd:e.meta?.cwd,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...o.uploadedArtifactId?{uploadedArtifactId:o.uploadedArtifactId}:{},...o.clientArtifactPaths?{clientArtifactPaths:o.clientArtifactPaths}:{},...o.installSource?{installSource:o.installSource}:{}}};return Z({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await K("daemon_request",async()=>await tL(i,s,n.transportPreference,a),{requestId:t,command:e.command})}async function tf(e,t){let r,n=[...e.positionals??[]],a=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,o={};if(tU(t)){let l=function(e,t){if("screenshot"===e.command){let r=tg(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:ty("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:ty("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=tg(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:ty("recording",s.extname(t)||".mp4")}}return null}(e,n);l&&(void 0!==l.positionalPath&&(n[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((a??={}).out=l.flagPath),o[l.field]=l.localPath);let u=await th(e,t);u&&(i=u.installSource,r=u.uploadedArtifactId??r)}if(!tU(t)||"install"!==e.command&&"reinstall"!==e.command||n.length<2)return{positionals:n,flags:a,installSource:i,uploadedArtifactId:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let l=n[1];if(l.startsWith("remote:"))return n[1]=l.slice(7),{positionals:n,flags:a,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let u=s.isAbsolute(l)?l:s.resolve(e.meta?.cwd??process.cwd(),l);return f.existsSync(u)?{positionals:n,flags:a,installSource:i,uploadedArtifactId:r=await ti({localPath:u,baseUrl:t.baseUrl,token:t.token}),...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}:{positionals:n,flags:a,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}}async function th(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let n=r.path.trim();if(!n)return{installSource:r};if(n.startsWith("remote:"))return{installSource:{...r,path:n.slice(7)}};let a=s.isAbsolute(n)?n:s.resolve(e.meta?.cwd??process.cwd(),n);if(!f.existsSync(a))return{installSource:{...r,path:a}};let i=await ti({localPath:a,baseUrl:t.baseUrl,token:t.token});return{installSource:{...r,path:a},uploadedArtifactId:i}}function tg(e,t,r,n=0){let a=e.positionals?.[n]??e.flags?.out,i=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,o=a&&a.trim().length>0?a:i;return s.isAbsolute(o)?o:s.resolve(e.meta?.cwd??process.cwd(),o)}function ty(e,t){let r=t.startsWith(".")?t:`.${t}`;return s.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function tw(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await tM(t,"http"))return t;throw new eg("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}let r=tI(e.paths.infoPath),n=X(),a=L((t=tN()).useSrc?t.srcPath:t.distPath,t.root),i=!!r&&await tM(r,e.transportPreference);if(r&&r.version===n&&r.codeSignature===a&&i)return r;r&&(r.version!==n||r.codeSignature!==a||!i)&&(await tk(r),t$(e.paths.infoPath)),function(e){let t=tD(e);if(!t.hasLock||t.hasInfo)return;let r=tA(e.lockPath);if(!r)return t$(e.lockPath);S(r.pid,r.processStartTime)||t$(e.lockPath)}(e.paths);let o=0;for(let t=1;t<=tc;t+=1){await tP(e);let r=await tb(tu,e);if(r)return r;if(await tx(e.paths)){o+=1;continue}let n=tD(e.paths);if(!(t<tc))break;if(!n.hasInfo&&!n.hasLock){await tv(150);continue}}let s=tD(e.paths);throw new eg("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:tu,startupAttempts:tc,lockRecoveryCount:o,metadataState:s,hint:function(e,t=en(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(s,e.paths)})}async function tb(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=tI(t.paths.infoPath);if(e&&await tM(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function tv(e){await new Promise(t=>setTimeout(t,e))}async function tx(e){let t=tD(e);if(!t.hasLock||t.hasInfo)return!1;let r=tA(e.lockPath);return r&&S(r.pid,r.processStartTime)&&await el(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),t$(e.lockPath),!0}async function tk(e){await el(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function tI(e){let t=tS(e);if(!t||"object"!=typeof t)return null;let r="string"==typeof t.token&&t.token.length>0?t.token:null;if(!r)return null;let n=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!n&&!a)return null;let i=t.transport,o="string"==typeof t.version?t.version:void 0,s="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,u=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:n?Number(t.port):void 0,httpPort:a?Number(t.httpPort):void 0,transport:"socket"===i||"http"===i||"dual"===i?i:void 0,pid:u?Number(t.pid):0,version:o,codeSignature:s,processStartTime:l}}function tA(e){let t=tS(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}td.addSubnet("127.0.0.0",8,"ipv4"),td.addAddress("::1","ipv6"),td.addSubnet("::ffff:127.0.0.0",104,"ipv6");function tD(e){return{hasInfo:f.existsSync(e.infoPath),hasLock:f.existsSync(e.lockPath)}}function tS(e){if(!f.existsSync(e))return null;try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}}function t$(e){try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}async function tM(e,t){var r;return"http"===tE(e,t)?await function(e){let t=e.baseUrl?tF(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let r=new URL(t),n="https:"===r.protocol?m:d,a=e.baseUrl?3e3:500;return new Promise(e=>{let t=n.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:a},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=p.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function tP(e){let t=tN(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};ep(process.execPath,r,{env:n})}function tN(){let e=H(),t=s.join(e,"dist","src","daemon.js"),r=s.join(e,"src","daemon.ts"),n=f.existsSync(t),a=f.existsSync(r);if(!n&&!a)throw new eg("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?a:!n&&a}}async function tL(e,t,r,n){return"http"===tE(e,r)?await tC(e,t,n):await tO(e,t,n)}function tE(e,t){if(e.baseUrl){if("socket"===t)throw new eg("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,n=t;if(tR(r,n))return n;throw new eg("COMMAND_FAILED","http"===n?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let a=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tR(e,t));if(a)return a;throw new eg("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tR(e,t){return"http"===t?!!e.httpPort:!!e.port}function t_(e,t,r,n,a,i){let o=a?{terminated:0}:function(){let e=0;try{for(let t of tp){let r=ed("pkill",["-f",t],{allowFailure:!0});0===r.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=a?{forcedKill:!1}:function(e,t){let r=!1;try{S(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{el(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{t$(t.infoPath),t$(t.lockPath)}return{forcedKill:r}}(e,t);return Z({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:i,requestId:r,command:n,timedOutRunnerPidsTerminated:o.terminated,timedOutRunnerCleanupError:o.error,daemonPidReset:a?void 0:e.pid,daemonPidForceKilled:a?void 0:s.forcedKill,daemonBaseUrl:e.baseUrl}}),new eg("COMMAND_FAILED","Daemon request timed out",{timeoutMs:i,requestId:r,hint:a?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."})}function tT(e,t,r){return Z({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new eg("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t,hint:r?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e instanceof Error?e:void 0)}async function tO(e,t,r){let n=e.port;if(!n)throw new eg("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,i)=>{let o=p.createConnection({host:"127.0.0.1",port:n},()=>{o.write(`${JSON.stringify(t)}
25
- `)}),s=en(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{o.destroy(),i(t_(e,s,t.meta?.requestId,t.command,!1,r))},r):void 0,u="";o.setEncoding("utf8"),o.on("data",e=>{let r=(u+=e).indexOf("\n");if(-1===r)return;let n=u.slice(0,r).trim();if(n)try{let e=JSON.parse(n);o.end(),l&&clearTimeout(l),a(e)}catch(e){l&&clearTimeout(l),i(new eg("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:n},e instanceof Error?e:void 0))}}),o.on("error",e=>{l&&clearTimeout(l),i(tT(e,t.meta?.requestId,!1))})})}async function tC(e,t,r){let n=e.baseUrl?new URL(tF(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!n)throw new eg("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let a=JSON.stringify({jsonrpc:"2.0",id:t.meta?.requestId??G(),method:"agent_device.command",params:t}),i={"content-type":"application/json","content-length":Buffer.byteLength(a)};return e.baseUrl&&e.token&&(i.authorization=`Bearer ${e.token}`,i["x-agent-device-token"]=e.token),await new Promise((o,s)=>{let l=en(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),u=("https:"===n.protocol?m:d).request({protocol:n.protocol,host:n.hostname,port:n.port,method:"POST",path:n.pathname+n.search,headers:i},r=>{let n="";r.setEncoding("utf8"),r.on("data",e=>{n+=e}),r.on("end",()=>{p&&clearTimeout(p);try{let r=JSON.parse(n);if(r.error){let e=r.error.data??{};s(new eg(String(e.code??"COMMAND_FAILED"),String(e.message??r.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:t.meta?.requestId}));return}if(!r.result||"object"!=typeof r.result)return void s(new eg("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void tj(e,t,r.result).then(o).catch(s);o(r.result)}catch(e){p&&clearTimeout(p),s(new eg("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:n},e instanceof Error?e:void 0))}})}),c=tU(e),p="number"==typeof r?setTimeout(()=>{u.destroy(),s(t_(e,l,t.meta?.requestId,t.command,c,r))},r):void 0;u.on("error",e=>{p&&clearTimeout(p),s(tT(e,t.meta?.requestId,c))}),u.write(a),u.end()})}function tU(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function tF(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function tj(e,t,r){let n=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===n.length||!e.baseUrl)return r;let a=r.data?{...r.data}:{},i=[];for(let r of n){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){i.push(r);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return s.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await tV({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:n,requestId:t.meta?.requestId}),a[r.field]=n,i.push({...r,localPath:n})}return a.artifacts=i,{ok:!0,data:a}}async function tV(e){var t,r;let n,a=new URL((t=e.baseUrl,r=e.artifactId,n=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,n).toString())),i="https:"===a.protocol?m:d;await f.promises.mkdir(s.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let n=!1,o=e.timeoutMs??tl,s=a=>{if(!n){if(n=!0,clearTimeout(u),a)return void f.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(a));t()}},l=i.request({protocol:a.protocol,host:a.hostname,port:a.port,method:"GET",path:a.pathname+a.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{s(new eg("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=f.createWriteStream(e.destinationPath);r.on("error",e=>{s(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{s(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{s(new eg("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>s())}),t.pipe(r)}),u=setTimeout(()=>{l.destroy(new eg("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:o}))},o);l.on("error",t=>{t instanceof eg?s(t):s(new eg("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:o},t instanceof Error?t:void 0))}),l.end()})}function tB(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}let tG="metro-companion";function tq(e){return y("sha256").update(e).digest("hex")}function tX(e){return e?.trim()?e.trim():void 0}function tY(e,t){let r=s.join(e,".agent-device");if(!t)return{statePath:s.join(r,"metro-companion.json"),logPath:s.join(r,"metro-companion.log")};let n=tq(t).slice(0,12),a=s.join(r,tG);return{statePath:s.join(a,`metro-companion-${n}.json`),logPath:s.join(a,`metro-companion-${n}.log`)}}function tH(e){try{let t=JSON.parse(f.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let r=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:tX("string"==typeof t.launchUrl?t.launchUrl:void 0),tokenHash:t.tokenHash,consumers:r}}catch{return null}}function tJ(e,t){f.mkdirSync(s.dirname(e),{recursive:!0}),f.writeFileSync(e,`${JSON.stringify(t,null,2)}
26
- `,"utf8")}function tK(e){try{let t=f.readdirSync(e);0===t.length&&f.rmdirSync(e)}catch{}}function tz(e){let t=s.dirname(e.statePath),r=s.dirname(e.logPath);var n=e.statePath;try{f.unlinkSync(n)}catch{}var a=e.logPath;try{f.unlinkSync(a)}catch{}tK(t),r!==t&&tK(r),s.basename(t)===tG&&tK(s.dirname(t))}function tW(e){return e.includes(ey)}function tZ(e){return tX(e.consumerKey)??tX(e.profileKey)??null}function tQ(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function t0(e){if(!ee(e.pid))return;let t=k(e.pid);if(t&&tW(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await I(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await I(e.pid,1e3)}}}async function t1(e){let t=tZ(e),r=tY(e.projectRoot,e.profileKey),n=tH(r.statePath);if(n&&function(e,t){if(!ee(e.pid))return!1;if(e.startTime){let t=et(e.pid);if(!t||t!==e.startTime)return!1}let r=k(e.pid);return!!r&&!!tW(r)&&e.serverBaseUrl===ew(t.serverBaseUrl)&&e.localBaseUrl===ew(t.localBaseUrl)&&e.launchUrl===tX(t.launchUrl)&&e.tokenHash===tq(t.bearerToken)}(n,e)){let e=tQ(n,t);return e!==n&&tJ(r.statePath,e),{pid:n.pid,spawned:!1,statePath:r.statePath,logPath:r.logPath}}n&&(await t0(n),tz(r));let a=function(e,t){let r=function(){let e=u(import.meta.url),t=s.extname(e)||".js",r=s.join(s.dirname(e),`metro-companion${t}`);if(!f.existsSync(r))throw Error(`Metro companion entrypoint not found at ${r}. Rebuild the package to include the companion worker entry.`);return r}(),n=r.endsWith(".ts")?["--experimental-strip-types"]:[];f.mkdirSync(s.dirname(t),{recursive:!0});let a=f.openSync(t,"a"),i=0;try{let t;i=ep(process.execPath,[...n,r,ey],{env:(t={...e.env??process.env,[ev]:ew(e.serverBaseUrl),[eA]:e.bearerToken,[ex]:ew(e.localBaseUrl),[ek]:tY(e.projectRoot,e.profileKey).statePath},e.launchUrl?.trim()?t[eI]=e.launchUrl.trim():delete t[eI],t),stdio:["ignore",a,a]})}finally{f.closeSync(a)}if(!Number.isInteger(i)||i<=0)throw Error("Failed to start Metro companion process.");return{pid:i,startTime:et(i)??void 0,command:k(i)??void 0,serverBaseUrl:ew(e.serverBaseUrl),localBaseUrl:ew(e.localBaseUrl),launchUrl:tX(e.launchUrl),tokenHash:tq(e.bearerToken),consumers:[]}}(e,r.logPath);return tJ(r.statePath,tQ(a,t)),{pid:a.pid,spawned:!0,statePath:r.statePath,logPath:r.logPath}}async function t2(e){let t=tZ(e),r=tY(e.projectRoot,e.profileKey),n=tH(r.statePath);if(!n)return tz(r),{stopped:!1,statePath:r.statePath};let a=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return a.consumers.length>0?(tJ(r.statePath,a),{stopped:!1,statePath:r.statePath}):(await t0(n),tz(r),{stopped:!0,statePath:r.statePath})}function t3(e){return"string"==typeof e&&e.trim()?ew(e.trim()):""}function t5(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function t8(e,t,r){return z(e,{env:t,cwd:r})}function t4(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}function t6(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function t7(e,t){return{platform:t,bundleUrl:eb(e,t)}}function t9(e,t){return{platform:t,metroHost:t5(e?.metro_host),metroPort:e?.metro_port,bundleUrl:t5(e?.metro_bundle_url),launchUrl:t5(e?.launch_url)}}async function re(e){await new Promise(t=>setTimeout(t,e))}async function rt(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function rr(e,t){try{let r=await rt(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function rn(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await I(e,1e3)){try{process.kill(e,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await I(e,1e3)}}}function ra(e,t){let r=Error(e);return r.retryable=t,r}function ri(e,t){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(t).includes("Metro companion is not connected"))}async function ro(e){let t;try{var r,n;t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(r=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...r.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw ra(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw ra(t instanceof Error?t.message:String(t),!0)}let a=function(e,t,r){if(!e)return{};try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Expected a JSON object");return t}catch(i){let n=e.slice(0,200),a=i instanceof Error?i.message:String(i);throw ra(`/api/metro/bridge returned invalid JSON (${t}) from ${r}: ${a}. body=${JSON.stringify(n)}`,ri(t,e))}}(await t.text(),t.status,e.baseUrl);if(!t.ok)throw ra(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(a)}`,ri(t.status,a));var i=a;let o=i.data??i;if(!o||"object"!=typeof o||Array.isArray(o))throw ra("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:o.enabled,baseUrl:o.base_url,statusUrl:o.status_url??"",bundleUrl:o.bundle_url??"",iosRuntime:t9(o.ios_runtime,"ios"),androidRuntime:t9(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url??"",host:o.upstream.host??"",port:o.upstream.port??0,statusUrl:o.upstream.status_url??""},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}catch(e){throw ra(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function rs(e,t,r,n,a){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),a&&i.push(`metroCompanionLog=${a}`),i.join(" ")}async function rl(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await rr(e,t))return!0;let a=Math.min(500,Math.max(n-Date.now(),0));a>0&&await re(a)}return!1}async function ru(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await ro({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let a=Math.min(1e3,Math.max(t-Date.now(),0));a>0&&await re(a)}throw Error(rs(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function rc(e={}){let t=e.env??process.env,r=process.cwd(),n=t8(e.projectRoot??r,t,r),a=function(e,t){if("auto"!==t)return t;let r=function(e){let t=s.join(e,"package.json");if(!t4(t))throw new eg("INVALID_ARGS",`package.json not found at ${t}`);return JSON.parse(f.readFileSync(t,"utf8"))}(e);return"string"==typeof({...r.dependencies??{},...r.devDependencies??{}}).expo?"expo":"react-native"}(n,e.kind??"auto"),i=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new eg("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(e.metroPort??8081),o=t5(e.listenHost)??"0.0.0.0",l=t5(e.statusHost)??"127.0.0.1",u=t3(e.publicBaseUrl),c=t6(e.startupTimeoutMs,18e4,3e4),p=t6(e.probeTimeoutMs,1e4,1e3),d=e.reuseExisting??!0,m=e.installDependenciesIfNeeded??!0,h=e.runtimeFilePath?t8(e.runtimeFilePath,t,r):null,g=t8(e.logPath??s.join(n,".agent-device","metro.log"),t,r);if(!u)throw new eg("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:y,proxyBaseUrl:w,proxyBearerToken:b}=function(e,t){if(e&&!t)throw new eg("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new eg("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(t3(e.proxyBaseUrl),t5(e.proxyBearerToken)??""),v=m?function(e,t){if(function(e){try{return f.statSync(e).isDirectory()}catch{return!1}}(s.join(e,"node_modules")))return{installed:!1};let r=t4(s.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:t4(s.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return ed(r.command,r.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:r.command}}(n,t):{installed:!1},x=`http://${l}:${i}/status`,k=!1,I=!1,A=0;if(d&&await rr(x,p))I=!0;else if(k=!0,A=function(e,t,r,n,a,i){let o="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",n,"--port",String(r)]};f.mkdirSync(s.dirname(a),{recursive:!0});let l=f.openSync(a,"a"),u=0;try{u=ep(o.command,o.installArgs,{cwd:e,env:i,stdio:["ignore",l,l]})}finally{f.closeSync(l)}if(!Number.isInteger(u)||u<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:u}}(n,a,i,o,g,t).pid,!await rl(x,c,p))throw await rn(A).catch(()=>{}),Error(`Metro did not become ready at ${x} within ${c}ms. Check ${g}.`);let D=t7(u,"ios"),S=t7(u,"android"),$=null,M=null;if(y)try{$=await ro({baseUrl:w,bearerToken:b,runtime:{metro_bundle_url:D.bundleUrl},timeoutMs:p})}catch(e){M=e instanceof Error?e.message:String(e)}if(y&&(!$||!1===$.probe.reachable)){let r;try{r=(await t1({projectRoot:n,serverBaseUrl:w,bearerToken:b,localBaseUrl:`http://${l}:${i}`,launchUrl:t5(e.launchUrl),profileKey:t5(e.companionProfileKey),consumerKey:t5(e.companionConsumerKey),env:t})).logPath}catch(e){throw Error(rs(w,e instanceof Error?e.message:String(e),$,M))}try{$=await ru({baseUrl:w,bearerToken:b,runtime:{metro_bundle_url:D.bundleUrl},probeTimeoutMs:p,startupTimeoutMs:c,initialBridgeError:M,companionLogPath:r})}catch(e){throw e instanceof Error?e:Error(String(e))}}let P=$?.iosRuntime??D,N=$?.androidRuntime??S,L={projectRoot:n,kind:a,dependenciesInstalled:v.installed,packageManager:v.packageManager??null,started:k,reused:I,pid:A,logPath:g,statusUrl:x,runtimeFilePath:h,iosRuntime:P,androidRuntime:N,bridge:$};return h&&(f.mkdirSync(s.dirname(h),{recursive:!0}),f.writeFileSync(h,JSON.stringify(L,null,2))),L}let rp="alert",rd="appstate",rm="app-switcher",rf="apps",rh="back",rg="batch",ry="boot",rw="click",rb="clipboard",rv="devices",rx="diff",rk="fill",rI="find",rA="focus",rD="home",rS="keyboard",r$="logs",rM="longpress",rP="network",rN="perf",rL="pinch",rE="press",rR="push",r_="record",rT="replay",rO="rotate",rC="scroll",rU="screenshot",rF="settings",rj="snapshot",rV="swipe",rB="test",rG="trace",rq="trigger-app-event",rX="type",rY="wait",rH=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"platform",type:"enum",enumValues:["ios","macos","android","linux","apple"]},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,legacyEnvNames:["IOS_SIMULATOR_DEVICE_SET"]},{key:"androidDeviceAllowlist",type:"string",legacyEnvNames:["ANDROID_DEVICE_ALLOWLIST"]},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string",legacyEnvNames:["AGENT_DEVICE_PROXY_TOKEN"]},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],rJ=new Map(rH.map(e=>[e.key,e]));function rK(e){let t=e.env??process.env;return z(e.configPath,{cwd:e.cwd,env:t})}function rz(e){let t=function(e){let t,r,n=e.env??process.env,a=rK(e);if(!f.existsSync(a))throw new eg("INVALID_ARGS",`Remote config file not found: ${a}`);try{t=f.readFileSync(a,"utf8")}catch(e){throw new eg("INVALID_ARGS",`Failed to read remote config file: ${a}`,{cause:e instanceof Error?e.message:String(e)})}try{r=JSON.parse(t)}catch(e){throw new eg("INVALID_ARGS",`Invalid JSON in remote config file: ${a}`,{cause:e instanceof Error?e.message:String(e)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new eg("INVALID_ARGS",`Remote config file must contain a JSON object: ${a}`);let i={},o=r,l=s.dirname(a);for(let[e,t]of Object.entries(o)){let r=rJ.get(e);if(!r)throw new eg("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${a}.`);let o=eX(r,t,`remote config file ${a}`,e);i[r.key]="string"==typeof o&&"path"in r&&r.path?z(o,{cwd:l,env:n}):o}return{resolvedPath:a,profile:i}}(e);return{resolvedPath:t.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of rH){let n=r[e.key];void 0!==n&&(t[e.key]=n)}return t}(function(e=process.env){let t={};for(let r of rH){let n=(function(e){let t=rJ.get(e);return[eq(e),...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);n&&(t[r.key]=eX(r,n.value,`environment variable ${n.name}`,n.name))}return t}(e.env),t.profile)}}let rW=rH.map(e=>e.key),rZ=["remoteConfig","session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"];function rQ(e){return e.remoteConfig?{...function(e){let t={};for(let r of rW){let n=e[r];void 0!==n&&(t[r]=n)}return t}(rz({configPath:e.remoteConfig,cwd:e.cwd,env:e.env}).profile),remoteConfig:e.remoteConfig}:{}}function r0(e,t,r,n){let a=r(e[t]);if(void 0===a)throw new eg("COMMAND_FAILED",n,{response:e});return a}function r1(e,t){return r0(e,t,r6,`Daemon response is missing "${t}".`)}function r2(e,t){return r6(e[t])}function r3(e,t){var r;let n;return r=r6,null===(n=e[t])?null:r(n)}function r5(e,t){return r0(e,t,r9,`Daemon response has invalid "${t}".`)}function r8(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function r4(e,t){let r=e[t];if(!nr(r))return;let n="number"==typeof r.x?r.x:void 0,a="number"==typeof r.y?r.y:void 0,i="number"==typeof r.width?r.width:void 0,o="number"==typeof r.height?r.height:void 0;if(void 0!==n&&void 0!==a&&void 0!==i&&void 0!==o)return{x:n,y:a,width:i,height:o}}function r6(e){return"string"==typeof e&&e.length>0?e:void 0}function r7(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function r9(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function ne(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function nt(e){if(!nr(e))throw new eg("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function nr(e){return"object"==typeof e&&null!==e}function nn(e){let t={};for(let[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function na(e,t){let r=r2(e,"bundleId"),n=r2(e,"package");return{app:r1(e,"app"),appPath:r1(e,"appPath"),platform:r5(e,"platform"),appId:r??n,bundleId:r,package:n,identifiers:M({session:t,bundleId:r,packageName:n})}}function ni(e){let t=nt(e),r=r5(t,"platform"),n=r1(t,"id"),a=r1(t,"name");return{platform:r,target:r8(t,"target"),kind:r0(t,"kind",ne,'Daemon response has invalid "kind".'),id:n,name:a,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:$(r,n,a),ios:"ios"===r?{udid:n}:void 0,android:"android"===r?{serial:n}:void 0}}function no(e){let t=nt(e),r=r5(t,"platform"),n=r1(t,"id"),a=r1(t,"name"),i=r8(t,"target"),o=r1(t,"device"),s={session:a,...$(r,n,o)};return{name:a,createdAt:r0(t,"createdAt",r7,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:i,id:n,name:o,identifiers:s,ios:"ios"===r?{udid:n,simulatorSetPath:r3(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:n}:void 0},identifiers:s}}function ns(e){return e??"default"}function nl(e){return void 0!==e.ref?[e.ref,...nu(e.label)]:void 0!==e.selector?[e.selector]:[String(e.x),String(e.y)]}function nu(e){return void 0===e?[]:[e]}function nc(e){return void 0===e?[]:[String(e)]}function np(e,t,r){return r.remoteConfig&&r.remoteConfig!==e.remoteConfig?{...nd({...e,...r}),...e,...r}:{...t,...e,...r}}function nd(e){if(!e.remoteConfig)return{};let{runtime:t,...r}=rQ({remoteConfig:e.remoteConfig,cwd:e.cwd??process.cwd(),env:process.env});return r}function nm(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function nf(e,t,r){var n;if(e.json)return void e3({success:!0,data:t});let a=r?.();a&&(n=a,process.stdout.write(n.endsWith("\n")?n:`${n}
27
- `))}function nh(e,t){nf(e,t,()=>U(t))}let ng=async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new eg("INVALID_ARGS","session only supports list");let n={sessions:(await r.sessions.list()).map(A)};return nf(t,n,()=>JSON.stringify(n,null,2)),!0},ny=async({flags:e,client:t})=>{let r=await t.devices.list(nm(e));return nf(e,{devices:r.map(j)},()=>r.map(nw).join("\n")),!0};function nw(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",n="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${n}`}let nb=async({flags:e,client:t})=>{if(!e.device)throw new eg("INVALID_ARGS","ensure-simulator requires --device <name>");let r=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet});return nf(e,F(r),()=>{let e=r.created?"Created":"Reused",t=r.booted?" (booted)":"";return r.runtime?`${e}: ${r.device} ${r.udid}${t}
28
- Runtime: ${r.runtime}`:`${e}: ${r.device} ${r.udid}${t}`}),!0},nv=async({positionals:e,flags:t,client:r})=>{if("prepare"!==(e[0]??"").toLowerCase())throw new eg("INVALID_ARGS","metro only supports prepare");if(!t.metroPublicBaseUrl)throw new eg("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let n=await r.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile});return nf(t,n,()=>JSON.stringify(n,null,2)),!0},nx=async({flags:e,client:t})=>{let r=await t.apps.list({...nm(e),appsFilter:e.appsFilter});return nf(e,{apps:r},()=>r.join("\n")),!0},nk=async({positionals:e,flags:t,client:r})=>{let n=C(await nD("install",e,t,r));return nh(t,n),!0},nI=async({positionals:e,flags:t,client:r})=>{let n=C(await nD("reinstall",e,t,r));return nh(t,n),!0},nA=async({positionals:e,flags:t,client:r})=>{let n=eo(await nS(e,t,r));return nh(t,n),!0};async function nD(e,t,r,n){let a=t[0],i=t[1];if(!a||!i)throw new eg("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let o={app:a,appPath:i,...nm(r)};return"install"===e?await n.apps.install(o):await n.apps.reinstall(o)}async function nS(e,t,r){let n=e[0]?.trim();if(!n)throw new eg("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new eg("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await r.apps.installFromSource({...nm(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:n,headers:function(e){if(!e||0===e.length)return;let t={};for(let r of e){let e=r.indexOf(":");if(e<=0)throw new eg("INVALID_ARGS",`Invalid --header value "${r}". Expected "name:value".`);let n=r.slice(0,e).trim(),a=r.slice(e+1).trim();if(!n)throw new eg("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[n]=a}return t}(t.header)}})}async function n$(e){await t2(e)}async function nM(e,t){if(!e.remoteConfig)return;let r=e.platform;if("ios"!==r&&"android"!==r)throw new eg("INVALID_ARGS",'open --remote-config requires platform "ios" or "android" in the remote config file or CLI flags.');if(!e.metroPublicBaseUrl)throw new eg("INVALID_ARGS",'open --remote-config requires "metroPublicBaseUrl" in the remote config file.');let n=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,launchUrl:e.launchUrl,companionProfileKey:rK({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),companionConsumerKey:e.session,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return"ios"===r?n.iosRuntime:n.androidRuntime}let nP=async({positionals:e,flags:t,client:r})=>{let n=await nM(t,r),a=_(await r.apps.open({app:e[0],url:e[1],surface:t.surface,activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,runtime:n,...nm(t)}));return nh(t,a),!0},nN=async({positionals:e,flags:t,client:r})=>{let n=(()=>{let e;if(!t.remoteConfig)return null;try{e=rz({configPath:t.remoteConfig,cwd:process.cwd(),env:process.env})}catch{return null}return e.profile.metroProjectRoot&&e.profile.metroProxyBaseUrl?{projectRoot:e.profile.metroProjectRoot,profileKey:e.resolvedPath,consumerKey:t.session}:null})(),a=async e=>{try{return await e()}finally{try{n&&await n$(n)}catch{}}},i=W(await a(async()=>e[0]?await r.apps.close({app:e[0],shutdown:t.shutdown}):await r.sessions.close({shutdown:t.shutdown})));return nh(t,i),!0},nL=async({flags:e,client:t})=>{let r=D(await t.capture.snapshot({...nm(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return nf(e,r,()=>(function(e,t={}){var r,n,a;let i,o=e.nodes,s=Array.isArray(o)?o:[],l="string"==typeof e.backend?e.backend:void 0,u=t.raw||"macos-helper"===l?null:B(s),c=!!e.truncated,p="string"==typeof e.appName?e.appName:void 0,d="string"==typeof e.appBundleId?e.appBundleId:void 0,m=[];p&&m.push(`Page: ${p}`),d&&m.push(`App: ${d}`);let f=u?.nodes??s,h=t.raw||"macos-helper"===l?null:function(e,t,r,n){let a=e.visibility;if(a&&"object"==typeof a&&"boolean"==typeof a.partial&&"number"==typeof a.visibleNodeCount&&"number"==typeof a.totalNodeCount&&Array.isArray(a.reasons))return{partial:a.partial,visibleNodeCount:a.visibleNodeCount,totalNodeCount:a.totalNodeCount,reasons:a.reasons.filter(e=>"string"==typeof e)};let i=t?.hiddenCount??0,o=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return i>0?{partial:!0,visibleNodeCount:r,totalNodeCount:n,reasons:["offscreen-nodes"]}:o?{partial:!0,visibleNodeCount:r,totalNodeCount:r,reasons:[]}:null}(e,u,f.length,s.length),g=h?.partial?h.totalNodeCount>h.visibleNodeCount?`Snapshot: ${h.visibleNodeCount} visible nodes (${h.totalNodeCount} total)${c?" (truncated)":""}`:`Snapshot: ${h.visibleNodeCount} visible nodes${c?" (truncated)":""}`:`Snapshot: ${s.length} nodes${c?" (truncated)":""}`,y=m.length>0?`${m.join("\n")}
29
- `:"",w=(r=e,n=s,a=t,i=tr(r),!a.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let r of e){let e=(r.type??"").toLowerCase(),n=Y(r).trim().toLowerCase();if(!n)continue;let a=`${e}|${n}`;t.set(a,(t.get(a)??0)+1)}let r=0;for(let e of t.values())e>1&&(r+=e);return r>=8}(n)&&i.push("Warning: possible repeated nav subtree detected."),i),b=w.length>0?`${w.join("\n")}
24
+ `)}function e9(e){let t=to(),r=!0===e.match,n=ti(e.differentPixels),a=ti(e.totalPixels),i=ti(e.mismatchPercentage),o=e.diffPath,s=e.dimensionMismatch,c=[];if(r){let e=t?l("green","✓"):"✓";c.push(`${e} Screenshots match.`)}else if(s){let e=t?l("red","✗"):"✗",r=s.expected,n=s.actual;c.push(`${e} Screenshots have different dimensions: expected ${r?.width}x${r?.height}, got ${n?.width}x${n?.height}`)}else{let e=t?l("red","✗"):"✗",r=0===i&&n>0?"<0.01":String(i),a=`${r}% pixels differ`;c.push(`${e} ${t?l("red",a):a}`)}if(o&&!r){let e=ta(o),r=t?l("dim","Diff image:"):"Diff image:",n=t?l("green",e):e;c.push(` ${r} ${n}`)}if(e.currentOverlayPath&&!r){let r=ta(e.currentOverlayPath),n=t?l("dim","Current overlay:"):"Current overlay:",a=t?l("green",r):r,i=ti(e.currentOverlayRefCount),o=i>0?` (${i} refs)`:"";c.push(` ${n} ${a}${o}`)}if(!r&&!s){let e=t?l("red",String(n)):String(n);c.push(` ${e} different / ${a} total pixels`)}let u=r||s?[]:function(e){let t=[];for(let r of(e.ocr?.movementClusters??[]).slice(0,2))t.push(`text movement cluster: ${function(e){let t=e.slice(0,4).map(e=>JSON.stringify(e)),r=e.length>t.length?` +${e.length-t.length} more`:"";return`${t.join(", ")}${r}`}(r.texts)} dx=${tn(r.xRange)}px dy=${tn(r.yRange)}px`);let r=(e.nonTextDeltas??[]).filter(e=>["icon","toggle","chevron"].includes(e.likelyKind)).slice(0,3);r.length>0&&t.push(`non-text controls: ${r.map(tr).join("; ")}`);let n=(e.nonTextDeltas??[]).filter(e=>"separator"===e.likelyKind).slice(0,2);return n.length>0&&t.push(`non-text boundaries: ${n.map(tr).join("; ")}`),t.slice(0,6)}(e);if(u.length>0)for(let e of(c.push(` ${ts("Hints:",t)}`),u))c.push(` - ${e}`);let d=Array.isArray(e.regions)?e.regions:[];if(!r&&!s&&d.length>0)for(let e of(c.push(` ${ts("Changed regions:",t)}`),d.slice(0,5))){let t=0===e.shareOfDiffPercentage&&e.differentPixels>0?"<0.01":String(e.shareOfDiffPercentage),r=e.rect;c.push(` ${e.index}. ${e.location} x=${r.x} y=${r.y} ${r.width}x${r.height}, ${t}% of diff, change=${e.dominantChange}`);let n=function(e){let t=[e.size?`size=${e.size}`:null,e.shape?`shape=${e.shape}`:null,"number"==typeof e.densityPercentage?`density=${e.densityPercentage}%`:null,e.averageBaselineColorHex&&e.averageCurrentColorHex?`avgColor=${e.averageBaselineColorHex}->${e.averageCurrentColorHex}`:null,"number"==typeof e.baselineLuminance&&"number"==typeof e.currentLuminance?`luminance=${e.baselineLuminance}->${e.currentLuminance}`:null].filter(e=>null!==e);return t.length>0?t.join(" "):null}(e);n&&c.push(` ${n}`);let a=e.currentOverlayMatches?.[0];if(a){let e=a.label?` "${a.label}"`:"";c.push(` overlaps @${a.ref}${e}, ${a.regionCoveragePercentage}% of region`)}}let p=e.ocr?.matches??[];if(!r&&!s&&p.length>0){let r=p.slice(0,8);for(let[n,a]of(c.push(` ${ts(`OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${r.length}/${p.length}; px):`,t)}`),c.push(` ${ts("item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint",t)}`),r.entries())){let e=a.delta;c.push(` ${n+1} | ${JSON.stringify(a.text)} | ${tt(e.x)},${tt(e.y)} | ${tt(e.width)},${tt(e.height)} | ${te(a.baselineRect)} | ${te(a.currentRect)} | ${a.confidence} | ${a.possibleTextMetricMismatch?"ocr-bbox-size-change":"-"}`)}}let m=e.nonTextDeltas??[];if(!r&&!s&&m.length>0){let e=m.slice(0,8);for(let r of(c.push(` ${ts(`Non-text visual deltas (showing ${e.length}/${m.length}; px):`,t)}`),c.push(` ${ts("item | region | slot | kind | bboxCurrent | nearestText",t)}`),e))c.push(` ${r.index} | ${r.regionIndex?`r${r.regionIndex}`:"-"} | ${r.slot} | ${r.likelyKind} | ${te(r.rect)} | ${r.nearestText?JSON.stringify(r.nearestText):"-"}`)}return`${c.join("\n")}
25
+ `}function te(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function tt(e){return e>0?`+${e}`:String(e)}function tr(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:"",r=e.regionIndex?` r${e.regionIndex}`:"";return`${e.likelyKind}${t}${r}`}function tn(e){return e.min===e.max?tt(e.min):`${tt(e.min)}..${tt(e.max)}`}function ta(e){let t=process.cwd(),r=s.relative(t,e);return""!==r&&(r.startsWith("..")||s.isAbsolute(r))?e:""===r?".":`.${s.sep}${r}`}function ti(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function to(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function ts(e,t){return t?l("dim",e):e}function tl(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function tc(e){var t;let r="scroll-area"===(t=e.type)||"list"===t||"collection"===t||"table"===t?t:null;if(!r)return[];let n=[];if(e.node.hiddenContentAbove&&n.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&n.push(`[content below ${r} hidden]`),0===n.length)return[];let a=" ".repeat(e.depth+1);return n.map(e=>`${a}${e}`)}let tu="sha256";async function td(e){let{localPath:t,baseUrl:r,token:n}=e,a=f.statSync(t),i=a.isDirectory(),o=s.basename(t),l=i?"app-bundle":"file",c=r.endsWith("/")?r:`${r}/`,u=i?void 0:await tm(t);if(u){let e=await tp({normalizedBase:c,token:n,hash:u,filename:o,sizeBytes:a.size,artifactType:l});if(e)return e}let d=new URL("upload",c),h="https:"===d.protocol?m:p,y={"x-artifact-type":l,"x-artifact-filename":o,"transfer-encoding":"chunked"};return u&&(y["x-artifact-hash"]=u,y["x-artifact-hash-algorithm"]=tu),n&&(y.authorization=`Bearer ${n}`,y["x-agent-device-token"]=n),new Promise((e,r)=>{let n=h.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:y},t=>{let n="";t.setEncoding("utf8"),t.on("data",e=>{n+=e}),t.on("end",()=>{clearTimeout(a);try{let t=JSON.parse(n);if(!t.ok||!t.uploadId)return void r(new ey("COMMAND_FAILED",`Upload failed: ${n}`));e(t.uploadId)}catch{r(new ey("COMMAND_FAILED",`Invalid upload response: ${n}`))}})}),a=setTimeout(()=>{n.destroy(),r(new ey("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(n.on("error",e=>{clearTimeout(a),r(new ey("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),i){let e=g("tar",["cf","-","-C",s.dirname(t),s.basename(t)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(n),e.on("error",e=>{n.destroy(),r(new ey("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(n.destroy(),r(new ey("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=f.createReadStream(t);e.pipe(n),e.on("error",e=>{n.destroy(),r(new ey("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}async function tp(e){var t;let r=new URL("upload/preflight",e.normalizedBase),n={"content-type":"application/json"};e.token&&(n.authorization=`Bearer ${e.token}`,n["x-agent-device-token"]=e.token);let a=await fetch(r,{method:"POST",headers:n,signal:AbortSignal.timeout(3e4),body:JSON.stringify({hash:e.hash,hashAlgorithm:tu,fileName:e.filename,sizeBytes:e.sizeBytes,artifactType:e.artifactType})}).catch(()=>void 0);if(!a?.ok)return;let i=await a.json().catch(()=>void 0);return(t=i)&&"object"==typeof t&&!0===t.ok&&!0===t.cacheHit&&"string"==typeof t.uploadId?i.uploadId:void 0}async function tm(e){let t=w(tu);return await new Promise((r,n)=>{f.createReadStream(e).on("data",e=>t.update(e)).on("error",e=>{n(new ey("COMMAND_FAILED","Failed to read local artifact",{},e))}).on("end",r)}),t.digest("hex")}let tf=tY(),th=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),tg=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),ty=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],tw=new d.BlockList;async function tb(e){let t=e.meta?.requestId??q(),r=!!(e.meta?.debug||e.flags?.verbose),n=function(e){let t,r=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,n=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new ey("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new ey("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),a=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var i=n,o=a;if(!(!i||"localhost"===(t=new URL(i).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(d.isIPv4(t)?tw.check(t,"ipv4"):!!d.isIPv6(t)&&tw.check(t,"ipv6")))&&("string"!=typeof o||!(o.trim().length>0)))throw new ey("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:i,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let s=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,l=_(s);if(n&&"socket"===l)throw new ey("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:n});let c=eo(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===s?"dual":void 0));return{paths:ea(r),transportPreference:l,serverMode:c,remoteBaseUrl:n,remoteAuthToken:a}}(e),a=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return tY(t)}(e.command),i=await z("daemon_startup",async()=>await tA(n),{requestId:t,session:e.session}),o=await tv(e,i),s={...e,positionals:o.positionals,flags:o.flags,token:i.token,meta:{...e.meta??{},requestId:t,debug:r,cwd:e.meta?.cwd,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...o.uploadedArtifactId?{uploadedArtifactId:o.uploadedArtifactId}:{},...o.clientArtifactPaths?{clientArtifactPaths:o.clientArtifactPaths}:{},...o.installSource?{installSource:o.installSource}:{}}};return Q({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await z("daemon_request",async()=>await tO(i,s,n.transportPreference,a),{requestId:t,command:e.command})}async function tv(e,t){let r,n=[...e.positionals??[]],a=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,o={};if(tq(t)){let l=function(e,t){if("screenshot"===e.command){let r=tk(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:tx("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:tx("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=tk(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:tx("recording",s.extname(t)||".mp4")}}return null}(e,n);l&&(void 0!==l.positionalPath&&(n[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((a??={}).out=l.flagPath),o[l.field]=l.localPath);let c=await tI(e,t);c&&(i=c.installSource,r=c.uploadedArtifactId??r)}if(!tq(t)||"install"!==e.command&&"reinstall"!==e.command||n.length<2)return{positionals:n,flags:a,installSource:i,uploadedArtifactId:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let l=n[1];if(l.startsWith("remote:"))return n[1]=l.slice(7),{positionals:n,flags:a,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let c=s.isAbsolute(l)?l:s.resolve(e.meta?.cwd??process.cwd(),l);return f.existsSync(c)?{positionals:n,flags:a,installSource:i,uploadedArtifactId:r=await td({localPath:c,baseUrl:t.baseUrl,token:t.token}),...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}:{positionals:n,flags:a,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}}async function tI(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let n=r.path.trim();if(!n)return{installSource:r};if(n.startsWith("remote:"))return{installSource:{...r,path:n.slice(7)}};let a=s.isAbsolute(n)?n:s.resolve(e.meta?.cwd??process.cwd(),n);if(!f.existsSync(a))return{installSource:{...r,path:a}};let i=await td({localPath:a,baseUrl:t.baseUrl,token:t.token});return{installSource:{...r,path:a},uploadedArtifactId:i}}function tk(e,t,r,n=0){let a=e.positionals?.[n]??e.flags?.out,i=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,o=a&&a.trim().length>0?a:i;return s.isAbsolute(o)?o:s.resolve(e.meta?.cwd??process.cwd(),o)}function tx(e,t){let r=t.startsWith(".")?t:`.${t}`;return s.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function tA(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await tE(t,"http"))return t;throw new ey("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}let r=tP(e.paths.infoPath),n=K(),a=R((t=tC()).useSrc?t.srcPath:t.distPath,t.root),i=!!r&&await tE(r,e.transportPreference);if(r&&r.version===n&&r.codeSignature===a&&i)return r;r&&(r.version!==n||r.codeSignature!==a||!i)&&(await tM(r),t_(e.paths.infoPath)),function(e){let t=tL(e);if(!t.hasLock||t.hasInfo)return;let r=tN(e.lockPath);if(!r)return t_(e.lockPath);$(r.pid,r.processStartTime)||t_(e.lockPath)}(e.paths);let o=0;for(let t=1;t<=tg;t+=1){await tT(e);let r=await tS(th,e);if(r)return r;if(await t$(e.paths)){o+=1;continue}let n=tL(e.paths);if(!(t<tg))break;if(!n.hasInfo&&!n.hasLock){await tD(150);continue}}let s=tL(e.paths);throw new ey("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:th,startupAttempts:tg,lockRecoveryCount:o,metadataState:s,hint:function(e,t=ea(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(s,e.paths)})}async function tS(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=tP(t.paths.infoPath);if(e&&await tE(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function tD(e){await new Promise(t=>setTimeout(t,e))}async function t$(e){let t=tL(e);if(!t.hasLock||t.hasInfo)return!1;let r=tN(e.lockPath);return r&&$(r.pid,r.processStartTime)&&await ec(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),t_(e.lockPath),!0}async function tM(e){await ec(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function tP(e){let t=tR(e);if(!t||"object"!=typeof t)return null;let r="string"==typeof t.token&&t.token.length>0?t.token:null;if(!r)return null;let n=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!n&&!a)return null;let i=t.transport,o="string"==typeof t.version?t.version:void 0,s="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,c=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:n?Number(t.port):void 0,httpPort:a?Number(t.httpPort):void 0,transport:"socket"===i||"http"===i||"dual"===i?i:void 0,pid:c?Number(t.pid):0,version:o,codeSignature:s,processStartTime:l}}function tN(e){let t=tR(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}tw.addSubnet("127.0.0.0",8,"ipv4"),tw.addAddress("::1","ipv6"),tw.addSubnet("::ffff:127.0.0.0",104,"ipv6");function tL(e){return{hasInfo:f.existsSync(e.infoPath),hasLock:f.existsSync(e.lockPath)}}function tR(e){if(!f.existsSync(e))return null;try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}}function t_(e){try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}async function tE(e,t){var r;return"http"===tU(e,t)?await function(e){let t=e.baseUrl?tH(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let r=new URL(t),n="https:"===r.protocol?m:p,a=e.baseUrl?3e3:500;return new Promise(e=>{let t=n.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:a},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=d.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function tT(e){let t=tC(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};ep(process.execPath,r,{env:n})}function tC(){let e=Y(),t=s.join(e,"dist","src","daemon.js"),r=s.join(e,"src","daemon.ts"),n=f.existsSync(t),a=f.existsSync(r);if(!n&&!a)throw new ey("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?a:!n&&a}}async function tO(e,t,r,n){return"http"===tU(e,r)?await tG(e,t,n):await tV(e,t,n)}function tU(e,t){if(e.baseUrl){if("socket"===t)throw new ey("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,n=t;if(tF(r,n))return n;throw new ey("COMMAND_FAILED","http"===n?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let a=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tF(e,t));if(a)return a;throw new ey("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tF(e,t){return"http"===t?!!e.httpPort:!!e.port}function tj(e,t,r,n,a,i){let o=a?{terminated:0}:function(){let e=0;try{for(let t of ty){let r=em("pkill",["-f",t],{allowFailure:!0});0===r.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=a?{forcedKill:!1}:function(e,t){let r=!1;try{$(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{ec(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{t_(t.infoPath),t_(t.lockPath)}return{forcedKill:r}}(e,t);return Q({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:i,requestId:r,command:n,timedOutRunnerPidsTerminated:o.terminated,timedOutRunnerCleanupError:o.error,daemonPidReset:a?void 0:e.pid,daemonPidForceKilled:a?void 0:s.forcedKill,daemonBaseUrl:e.baseUrl}}),new ey("COMMAND_FAILED","Daemon request timed out",{timeoutMs:i,requestId:r,hint:a?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."})}function tB(e,t,r){return Q({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new ey("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t,hint:r?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e instanceof Error?e:void 0)}async function tV(e,t,r){let n=e.port;if(!n)throw new ey("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,i)=>{let o=d.createConnection({host:"127.0.0.1",port:n},()=>{o.write(`${JSON.stringify(t)}
26
+ `)}),s=ea(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{o.destroy(),i(tj(e,s,t.meta?.requestId,t.command,!1,r))},r):void 0,c="";o.setEncoding("utf8"),o.on("data",e=>{let r=(c+=e).indexOf("\n");if(-1===r)return;let n=c.slice(0,r).trim();if(n)try{let e=JSON.parse(n);o.end(),l&&clearTimeout(l),a(e)}catch(e){l&&clearTimeout(l),i(new ey("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:n},e instanceof Error?e:void 0))}}),o.on("error",e=>{l&&clearTimeout(l),i(tB(e,t.meta?.requestId,!1))})})}async function tG(e,t,r){var n,a,i;let o,s=e.baseUrl?new URL(tH(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!s)throw new ey("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let l=JSON.stringify((n=t,a={includeTokenParam:!e.baseUrl},o=n.meta?.requestId??q(),"lease_allocate"!==(i=n.command)&&"lease_heartbeat"!==i&&"lease_release"!==i?{jsonrpc:"2.0",id:o,method:"agent_device.command",params:n}:{jsonrpc:"2.0",id:o,method:function(e){switch(e){case"lease_allocate":return"agent_device.lease.allocate";case"lease_heartbeat":return"agent_device.lease.heartbeat";case"lease_release":return"agent_device.lease.release"}}(n.command),params:function(e,t,r){let n={...r.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...n,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...n,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...n,leaseId:e.meta?.leaseId}}}(n,n.command,a)})),c={"content-type":"application/json","content-length":Buffer.byteLength(l)};return e.baseUrl&&e.token&&(c.authorization=`Bearer ${e.token}`,c["x-agent-device-token"]=e.token),await new Promise((n,a)=>{let i=ea(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),o=("https:"===s.protocol?m:p).request({protocol:s.protocol,host:s.hostname,port:s.port,method:"POST",path:s.pathname+s.search,headers:c},r=>{let i="";r.setEncoding("utf8"),r.on("data",e=>{i+=e}),r.on("end",()=>{d&&clearTimeout(d);try{let r=JSON.parse(i);if(r.error){let e=r.error.data??{};a(new ey(String(e.code??"COMMAND_FAILED"),String(e.message??r.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:t.meta?.requestId}));return}if(!r.result||"object"!=typeof r.result)return void a(new ey("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void tK(e,t,r.result).then(n).catch(a);n(r.result)}catch(e){d&&clearTimeout(d),a(new ey("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:i},e instanceof Error?e:void 0))}})}),u=tq(e),d="number"==typeof r?setTimeout(()=>{o.destroy(),a(tj(e,i,t.meta?.requestId,t.command,u,r))},r):void 0;o.on("error",e=>{d&&clearTimeout(d),a(tB(e,t.meta?.requestId,u))}),o.write(l),o.end()})}function tq(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function tH(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function tK(e,t,r){let n=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===n.length||!e.baseUrl)return r;let a=r.data?{...r.data}:{},i=[];for(let r of n){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){i.push(r);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return s.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await tX({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:n,requestId:t.meta?.requestId}),a[r.field]=n,i.push({...r,localPath:n})}return a.artifacts=i,{ok:!0,data:a}}async function tX(e){var t,r;let n,a=new URL((t=e.baseUrl,r=e.artifactId,n=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,n).toString())),i="https:"===a.protocol?m:p;await f.promises.mkdir(s.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let n=!1,o=e.timeoutMs??tf,s=a=>{if(!n){if(n=!0,clearTimeout(c),a)return void f.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(a));t()}},l=i.request({protocol:a.protocol,host:a.hostname,port:a.port,method:"GET",path:a.pathname+a.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{s(new ey("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=f.createWriteStream(e.destinationPath);r.on("error",e=>{s(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{s(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{s(new ey("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>s())}),t.pipe(r)}),c=setTimeout(()=>{l.destroy(new ey("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:o}))},o);l.on("error",t=>{t instanceof ey?s(t):s(new ey("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:o},t instanceof Error?t:void 0))}),l.end()})}function tY(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}let tJ="metro-companion";function tz(e){return w("sha256").update(e).digest("hex")}function tW(e){return e?.trim()?e.trim():void 0}function tZ(e,t){let r=s.join(e,".agent-device");if(!t)return{statePath:s.join(r,"metro-companion.json"),logPath:s.join(r,"metro-companion.log")};let n=tz(t).slice(0,12),a=s.join(r,tJ);return{statePath:s.join(a,`metro-companion-${n}.json`),logPath:s.join(a,`metro-companion-${n}.log`)}}function tQ(e){try{let t=JSON.parse(f.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let r=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:tW("string"==typeof t.launchUrl?t.launchUrl:void 0),bridgeScope:function(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.tenantId&&"string"==typeof e.runId&&"string"==typeof e.leaseId)return{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId}}(t.bridgeScope),tokenHash:t.tokenHash,consumers:r}}catch{return null}}function t0(e,t){f.mkdirSync(s.dirname(e),{recursive:!0}),f.writeFileSync(e,`${JSON.stringify(t,null,2)}
27
+ `,"utf8")}function t1(e){try{let t=f.readdirSync(e);0===t.length&&f.rmdirSync(e)}catch{}}function t2(e){let t=s.dirname(e.statePath),r=s.dirname(e.logPath);var n=e.statePath;try{f.unlinkSync(n)}catch{}var a=e.logPath;try{f.unlinkSync(a)}catch{}t1(t),r!==t&&t1(r),s.basename(t)===tJ&&t1(s.dirname(t))}function t3(e){return e.includes(ew)}function t5(e){return tW(e.consumerKey)??tW(e.profileKey)??null}function t8(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function t4(e){if(!et(e.pid))return;let t=x(e.pid);if(t&&t3(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await A(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await A(e.pid,1e3)}}}async function t6(e){let t=t5(e),r=tZ(e.projectRoot,e.profileKey),n=tQ(r.statePath);if(n&&function(e,t){var r,n;if(!et(e.pid))return!1;if(e.startTime){let t=er(e.pid);if(!t||t!==e.startTime)return!1}let a=x(e.pid);return!!a&&!!t3(a)&&!!e.bridgeScope&&e.serverBaseUrl===eb(t.serverBaseUrl)&&e.localBaseUrl===eb(t.localBaseUrl)&&e.launchUrl===tW(t.launchUrl)&&(r=e.bridgeScope,n=t.bridgeScope,r.tenantId===n.tenantId&&r.runId===n.runId&&r.leaseId===n.leaseId)&&e.tokenHash===tz(t.bearerToken)}(n,e)){let e=t8(n,t);return e!==n&&t0(r.statePath,e),{pid:n.pid,spawned:!1,statePath:r.statePath,logPath:r.logPath}}n&&(await t4(n),t2(r));let a=function(e,t){let r=function(){let e=c(import.meta.url),t=s.extname(e)||".js",r=s.join(s.dirname(e),`metro-companion${t}`);if(!f.existsSync(r))throw Error(`Metro companion entrypoint not found at ${r}. Rebuild the package to include the companion worker entry.`);return r}(),n=r.endsWith(".ts")?["--experimental-strip-types"]:[];f.mkdirSync(s.dirname(t),{recursive:!0});let a=f.openSync(t,"a"),i=0;try{let t;i=ep(process.execPath,[...n,r,ew],{env:((t={...e.env??process.env,[eI]:eb(e.serverBaseUrl),[e$]:e.bearerToken,[ek]:eb(e.localBaseUrl),[ex]:tZ(e.projectRoot,e.profileKey).statePath})[eS]=e.bridgeScope.tenantId,t[eD]=e.bridgeScope.runId,t[eM]=e.bridgeScope.leaseId,e.launchUrl?.trim()?t[eA]=e.launchUrl.trim():delete t[eA],t),stdio:["ignore",a,a]})}finally{f.closeSync(a)}if(!Number.isInteger(i)||i<=0)throw Error("Failed to start Metro companion process.");return{pid:i,startTime:er(i)??void 0,command:x(i)??void 0,serverBaseUrl:eb(e.serverBaseUrl),localBaseUrl:eb(e.localBaseUrl),launchUrl:tW(e.launchUrl),bridgeScope:e.bridgeScope,tokenHash:tz(e.bearerToken),consumers:[]}}(e,r.logPath);return t0(r.statePath,t8(a,t)),{pid:a.pid,spawned:!0,statePath:r.statePath,logPath:r.logPath}}async function t7(e){let t=t5(e),r=tZ(e.projectRoot,e.profileKey),n=tQ(r.statePath);if(!n)return t2(r),{stopped:!1,statePath:r.statePath};let a=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return a.consumers.length>0?(t0(r.statePath,a),{stopped:!1,statePath:r.statePath}):(await t4(n),t2(r),{stopped:!0,statePath:r.statePath})}function t9(e){return"string"==typeof e&&e.trim()?eb(e.trim()):""}function re(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function rt(e,t,r){return W(e,{env:t,cwd:r})}function rr(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}function rn(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function ra(e,t){return{platform:t,bundleUrl:ev(e,t)}}function ri(e,t){return{platform:t,metroHost:re(e?.metro_host),metroPort:e?.metro_port,bundleUrl:re(e?.metro_bundle_url),launchUrl:re(e?.launch_url)}}async function ro(e){await new Promise(t=>setTimeout(t,e))}async function rs(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function rl(e,t){try{let r=await rs(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function rc(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await A(e,1e3)){try{process.kill(e,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await A(e,1e3)}}}function ru(e,t){let r=Error(e);return r.retryable=t,r}function rd(e,t){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(t).includes("Metro companion is not connected"))}function rp(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function rm(e){let t;try{var r,n;t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(r=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...r.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({...e.scope,ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw ru(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw ru(t instanceof Error?t.message:String(t),!0)}let a=function(e,t,r){if(!e)return{};try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Expected a JSON object");return t}catch(i){let n=e.slice(0,200),a=i instanceof Error?i.message:String(i);throw ru(`/api/metro/bridge returned invalid JSON (${t}) from ${r}: ${a}. body=${JSON.stringify(n)}`,rd(t,e))}}(await t.text(),t.status,e.baseUrl);if(!t.ok)throw ru(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(a)}`,rd(t.status,a));var i=a;let o=i.data??i;if(!o||"object"!=typeof o||Array.isArray(o))throw ru("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:o.enabled,baseUrl:o.base_url,statusUrl:o.status_url??"",bundleUrl:o.bundle_url??"",iosRuntime:ri(o.ios_runtime,"ios"),androidRuntime:ri(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url??"",host:o.upstream.host??"",port:o.upstream.port??0,statusUrl:o.upstream.status_url??""},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}catch(e){throw ru(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function rf(e,t,r,n,a){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),a&&i.push(`metroCompanionLog=${a}`),i.join(" ")}async function rh(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await rl(e,t))return!0;let a=Math.min(500,Math.max(n-Date.now(),0));a>0&&await ro(a)}return!1}async function rg(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await rm({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!rp(e))break}let a=Math.min(1e3,Math.max(t-Date.now(),0));a>0&&await ro(a)}throw Error(rf(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function ry(e={}){let t=e.env??process.env,r=process.cwd(),n=rt(e.projectRoot??r,t,r),a=function(e,t){if("auto"!==t)return t;let r=function(e){let t=s.join(e,"package.json");if(!rr(t))throw new ey("INVALID_ARGS",`package.json not found at ${t}`);return JSON.parse(f.readFileSync(t,"utf8"))}(e);return"string"==typeof({...r.dependencies??{},...r.devDependencies??{}}).expo?"expo":"react-native"}(n,e.kind??"auto"),i=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new ey("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(e.metroPort??8081),o=re(e.listenHost)??"0.0.0.0",l=re(e.statusHost)??"127.0.0.1",c=t9(e.publicBaseUrl),u=rn(e.startupTimeoutMs,18e4,3e4),d=rn(e.probeTimeoutMs,1e4,1e3),p=e.reuseExisting??!0,m=e.installDependenciesIfNeeded??!0,h=e.runtimeFilePath?rt(e.runtimeFilePath,t,r):null,g=rt(e.logPath??s.join(n,".agent-device","metro.log"),t,r);if(!c)throw new ey("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:y,proxyBaseUrl:w,proxyBearerToken:b}=function(e,t){if(e&&!t)throw new ey("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new ey("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(t9(e.proxyBaseUrl),re(e.proxyBearerToken)??""),v=y?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new ey("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(e.bridgeScope):null,I=m?function(e,t){if(function(e){try{return f.statSync(e).isDirectory()}catch{return!1}}(s.join(e,"node_modules")))return{installed:!1};let r=rr(s.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:rr(s.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return em(r.command,r.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:r.command}}(n,t):{installed:!1},k=`http://${l}:${i}/status`,x=!1,A=!1,S=0;if(p&&await rl(k,d))A=!0;else if(x=!0,S=function(e,t,r,n,a,i){let o="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",n,"--port",String(r)]};f.mkdirSync(s.dirname(a),{recursive:!0});let l=f.openSync(a,"a"),c=0;try{c=ep(o.command,o.installArgs,{cwd:e,env:i,stdio:["ignore",l,l]})}finally{f.closeSync(l)}if(!Number.isInteger(c)||c<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:c}}(n,a,i,o,g,t).pid,!await rh(k,u,d))throw await rc(S).catch(()=>{}),Error(`Metro did not become ready at ${k} within ${u}ms. Check ${g}.`);let D=ra(c,"ios"),$=ra(c,"android"),M=null,P=null;if(v)try{M=await rm({baseUrl:w,bearerToken:b,scope:v,runtime:{metro_bundle_url:D.bundleUrl},timeoutMs:d})}catch(e){if(!rp(e))throw e;P=e instanceof Error?e.message:String(e)}if(v&&(!M||!1===M.probe.reachable)){let r;try{r=(await t6({projectRoot:n,serverBaseUrl:w,bearerToken:b,bridgeScope:v,localBaseUrl:`http://${l}:${i}`,launchUrl:re(e.launchUrl),profileKey:re(e.companionProfileKey),consumerKey:re(e.companionConsumerKey),env:t})).logPath}catch(e){throw Error(rf(w,e instanceof Error?e.message:String(e),M,P))}try{M=await rg({baseUrl:w,bearerToken:b,scope:v,runtime:{metro_bundle_url:D.bundleUrl},probeTimeoutMs:d,startupTimeoutMs:u,initialBridgeError:P,companionLogPath:r})}catch(e){throw e instanceof Error?e:Error(String(e))}}let N=M?.iosRuntime??D,L=M?.androidRuntime??$,R={projectRoot:n,kind:a,dependenciesInstalled:I.installed,packageManager:I.packageManager??null,started:x,reused:A,pid:S,logPath:g,statusUrl:k,runtimeFilePath:h,iosRuntime:N,androidRuntime:L,bridge:M};return h&&(f.mkdirSync(s.dirname(h),{recursive:!0}),f.writeFileSync(h,JSON.stringify(R,null,2))),R}let rw="alert",rb="appstate",rv="app-switcher",rI="apps",rk="back",rx="batch",rA="boot",rS="click",rD="clipboard",r$="devices",rM="diff",rP="fill",rN="find",rL="focus",rR="home",r_="keyboard",rE="logs",rT="longpress",rC="network",rO="perf",rU="pinch",rF="press",rj="push",rB="record",rV="replay",rG="rotate",rq="scroll",rH="screenshot",rK="settings",rX="snapshot",rY="swipe",rJ="test",rz="trace",rW="trigger-app-event",rZ="type",rQ="wait";function r0(e,t,r,n){let a=r(e[t]);if(void 0===a)throw new ey("COMMAND_FAILED",n,{response:e});return a}function r1(e,t){return r0(e,t,r6,`Daemon response is missing "${t}".`)}function r2(e,t){return r6(e[t])}function r3(e,t){var r;let n;return r=r6,null===(n=e[t])?null:r(n)}function r5(e,t){return r0(e,t,r9,`Daemon response has invalid "${t}".`)}function r8(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function r4(e,t){let r=e[t];if(!nr(r))return;let n="number"==typeof r.x?r.x:void 0,a="number"==typeof r.y?r.y:void 0,i="number"==typeof r.width?r.width:void 0,o="number"==typeof r.height?r.height:void 0;if(void 0!==n&&void 0!==a&&void 0!==i&&void 0!==o)return{x:n,y:a,width:i,height:o}}function r6(e){return"string"==typeof e&&e.length>0?e:void 0}function r7(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function r9(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function ne(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function nt(e){if(!nr(e))throw new ey("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function nr(e){return"object"==typeof e&&null!==e}function nn(e){let t={};for(let[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function na(e,t){let r=r2(e,"bundleId"),n=r2(e,"package");return{app:r1(e,"app"),appPath:r1(e,"appPath"),platform:r5(e,"platform"),appId:r??n,bundleId:r,package:n,identifiers:P({session:t,bundleId:r,packageName:n})}}function ni(e){let t=nt(e),r=r5(t,"platform"),n=r1(t,"id"),a=r1(t,"name");return{platform:r,target:r8(t,"target"),kind:r0(t,"kind",ne,'Daemon response has invalid "kind".'),id:n,name:a,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:M(r,n,a),ios:"ios"===r?{udid:n}:void 0,android:"android"===r?{serial:n}:void 0}}function no(e){let t=nt(e),r=r5(t,"platform"),n=r1(t,"id"),a=r1(t,"name"),i=r8(t,"target"),o=r1(t,"device"),s={session:a,...M(r,n,o)};return{name:a,createdAt:r0(t,"createdAt",r7,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:i,id:n,name:o,identifiers:s,ios:"ios"===r?{udid:n,simulatorSetPath:r3(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:n}:void 0},identifiers:s}}function ns(e){return e??"default"}function nl(e){return void 0!==e.ref?[e.ref,...nc(e.label)]:void 0!==e.selector?[e.selector]:[String(e.x),String(e.y)]}function nc(e){return void 0===e?[]:[e]}function nu(e){return void 0===e?[]:[String(e)]}function nd(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:r1(t,"leaseId"),tenantId:r1(t,"tenantId"),runId:r1(t,"runId"),backend:r1(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}function np(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function nm(e,t,r){var n;if(e.json)return void e6({success:!0,data:t});let a=r?.();a&&(n=a,process.stdout.write(n.endsWith("\n")?n:`${n}
28
+ `))}function nf(e,t){nm(e,t,()=>F(t))}let nh=async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new ey("INVALID_ARGS","session only supports list");let n={sessions:(await r.sessions.list()).map(S)};return nm(t,n,()=>JSON.stringify(n,null,2)),!0},ng=async({flags:e,client:t})=>{let r=await t.devices.list(np(e));return nm(e,{devices:r.map(B)},()=>r.map(ny).join("\n")),!0};function ny(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",n="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${n}`}let nw=async({flags:e,client:t})=>{if(!e.device)throw new ey("INVALID_ARGS","ensure-simulator requires --device <name>");let r=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet});return nm(e,j(r),()=>{let e=r.created?"Created":"Reused",t=r.booted?" (booted)":"";return r.runtime?`${e}: ${r.device} ${r.udid}${t}
29
+ Runtime: ${r.runtime}`:`${e}: ${r.device} ${r.udid}${t}`}),!0},nb=async({positionals:e,flags:t,client:r})=>{if("prepare"!==(e[0]??"").toLowerCase())throw new ey("INVALID_ARGS","metro only supports prepare");if(!t.metroPublicBaseUrl)throw new ey("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let n=await r.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,bridgeScope:t.tenant&&t.runId&&t.leaseId?{tenantId:t.tenant,runId:t.runId,leaseId:t.leaseId}:void 0,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile});return nm(t,n,()=>JSON.stringify(n,null,2)),!0},nv=async({flags:e,client:t})=>{let r=await t.apps.list({...np(e),appsFilter:e.appsFilter});return nm(e,{apps:r},()=>r.join("\n")),!0},nI=async({positionals:e,flags:t,client:r})=>{let n=U(await nA("install",e,t,r));return nf(t,n),!0},nk=async({positionals:e,flags:t,client:r})=>{let n=U(await nA("reinstall",e,t,r));return nf(t,n),!0},nx=async({positionals:e,flags:t,client:r})=>{let n=es(await nS(e,t,r));return nf(t,n),!0};async function nA(e,t,r,n){let a=t[0],i=t[1];if(!a||!i)throw new ey("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let o={app:a,appPath:i,...np(r)};return"install"===e?await n.apps.install(o):await n.apps.reinstall(o)}async function nS(e,t,r){let n=e[0]?.trim();if(!n)throw new ey("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new ey("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await r.apps.installFromSource({...np(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:n,headers:function(e){if(!e||0===e.length)return;let t={};for(let r of e){let e=r.indexOf(":");if(e<=0)throw new ey("INVALID_ARGS",`Invalid --header value "${r}". Expected "name:value".`);let n=r.slice(0,e).trim(),a=r.slice(e+1).trim();if(!n)throw new ey("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[n]=a}return t}(t.header)}})}let nD=async({positionals:e,flags:t,client:r})=>{let n=T(await r.apps.open({app:e[0],url:e[1],surface:t.surface,activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,...np(t)}));return nf(t,n),!0},n$=async({positionals:e,flags:t,client:r})=>{let n=Z(e[0]?await r.apps.close({app:e[0],shutdown:t.shutdown}):await r.sessions.close({shutdown:t.shutdown}));return nf(t,n),!0};async function nM(e){await t7(e)}let nP=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"leaseBackend",type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"]},{key:"platform",type:"enum",enumValues:["ios","macos","android","linux","apple"]},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,legacyEnvNames:["IOS_SIMULATOR_DEVICE_SET"]},{key:"androidDeviceAllowlist",type:"string",legacyEnvNames:["ANDROID_DEVICE_ALLOWLIST"]},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string",legacyEnvNames:["AGENT_DEVICE_PROXY_TOKEN"]},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],nN=new Map(nP.map(e=>[e.key,e]));function nL(e){let t=function(e){var t;let r,n,a,i=e.env??process.env,o=(r=(t=e).env??process.env,W(t.configPath,{cwd:t.cwd,env:r}));if(!f.existsSync(o))throw new ey("INVALID_ARGS",`Remote config file not found: ${o}`);try{n=f.readFileSync(o,"utf8")}catch(e){throw new ey("INVALID_ARGS",`Failed to read remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}try{a=JSON.parse(n)}catch(e){throw new ey("INVALID_ARGS",`Invalid JSON in remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}if(!a||"object"!=typeof a||Array.isArray(a))throw new ey("INVALID_ARGS",`Remote config file must contain a JSON object: ${o}`);let l={},c=a,u=s.dirname(o);for(let[e,t]of Object.entries(c)){let r=nN.get(e);if(!r)throw new ey("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${o}.`);let n=eJ(r,t,`remote config file ${o}`,e);l[r.key]="string"==typeof n&&"path"in r&&r.path?W(n,{cwd:u,env:i}):n}return{resolvedPath:o,profile:l}}(e);return{resolvedPath:t.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of nP){let n=r[e.key];void 0!==n&&(t[e.key]=n)}return t}(function(e=process.env){let t={};for(let r of nP){let n=(function(e){let t=nN.get(e);return[eY(e),...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);n&&(t[r.key]=eJ(r,n.value,`environment variable ${n.name}`,n.name))}return t}(e.env),t.profile)}}function nR(e){var t;let r,n=nT(e);if(!f.existsSync(n))return null;try{r=JSON.parse(f.readFileSync(n,"utf8"))}catch(t){return nj(e,t),null}return!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&1===t.version&&"string"==typeof t.session&&"string"==typeof t.remoteConfigPath&&"string"==typeof t.remoteConfigHash&&(void 0===t.daemon||"object"==typeof t.daemon&&null!==t.daemon&&!Array.isArray(t.daemon))&&"string"==typeof t.tenant&&"string"==typeof t.runId&&"string"==typeof t.leaseId&&"string"==typeof t.leaseBackend&&"string"==typeof t.connectedAt&&"string"==typeof t.updatedAt?r:(nj(e),null)}function n_(e){f.rmSync(nT(e),{force:!0});let t=nC(e.stateDir);nU(e.stateDir)===e.session&&f.rmSync(t,{force:!0})}function nE(e){try{return y.createHash("sha256").update(f.readFileSync(e)).digest("hex")}catch(t){throw new ey("INVALID_ARGS",`Remote config file not found: ${e}`,{cause:t instanceof Error?t.message:String(t)})}}function nT(e){return s.join(e.stateDir,"remote-connections",`${function(e){let t=e.replaceAll(/[^a-zA-Z0-9._-]/g,"_");if(!t)return"default";if(t===e)return t;let r=y.createHash("sha256").update(e).digest("hex").slice(0,8);return`${t}-${r}`}(e.session)}.json`)}function nC(e){return s.join(e,"remote-connections",".active-session.json")}function nO(e){let t=nU(e.stateDir);return t?nR({stateDir:e.stateDir,session:t}):null}function nU(e){let t=nC(e);if(f.existsSync(t))try{let e=JSON.parse(f.readFileSync(t,"utf8"));return"string"==typeof e.session?e.session:void 0}catch{return}}function nF(e,t){f.writeFileSync(e,`${JSON.stringify(t,null,2)}
30
+ `,{encoding:"utf8",mode:384}),f.chmodSync(e,384)}function nj(e,t){Q({level:"warn",phase:"remote_connection_state_invalid",data:{session:e.session,cause:t instanceof Error?t.message:t?String(t):void 0}}),n_(e)}let nB=async({flags:e,client:t})=>{var r,n,a,i;let o,l;if(!e.remoteConfig)throw new ey("INVALID_ARGS","connect requires --remote-config <path>.");let c=e.session??"default",u=e.tenant,d=e.runId;if(!u)throw new ey("INVALID_ARGS","connect requires tenant in remote config or via --tenant <id>.");if(!d)throw new ey("INVALID_ARGS","connect requires runId in remote config or via --run-id <id>.");if(!e.daemonBaseUrl)throw new ey("INVALID_ARGS","connect requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.");let p=nL({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),m=nE(p.resolvedPath),h=e.leaseBackend??function(e){if("android"===e)return"android-instance";if("ios"===e)return"ios-instance";throw new ey("INVALID_ARGS","connect requires --lease-backend when platform is not ios or android.")}(e.platform),g={baseUrl:function(e){if(!e)return;let t=new URL(e);for(let e of(t.username="",t.password="",[...t.searchParams.keys()]))/(auth|key|password|secret|token)/i.test(e)&&t.searchParams.delete(e);return t.toString().replace(/\/+$/,"")}((r=e).daemonBaseUrl),transport:r.daemonTransport,serverMode:r.daemonServerMode},y=ea(e.stateDir).baseDir,w=nR({stateDir:y,session:c});if(w&&(n=w,a={flags:e,remoteConfigPath:p.resolvedPath,remoteConfigHash:m,leaseBackend:h,daemon:g},!(n.remoteConfigPath===a.remoteConfigPath&&n.remoteConfigHash===a.remoteConfigHash&&n.session===(a.flags.session??"default")&&n.tenant===a.flags.tenant&&n.runId===a.flags.runId&&n.leaseBackend===a.leaseBackend&&n.platform===a.flags.platform&&n.target===a.flags.target&&nY(n.daemon,a.daemon)))&&!e.force)throw new ey("INVALID_ARGS","A different remote connection is already active for this session. Re-run connect with --force to replace it.",{session:c,remoteConfig:w.remoteConfigPath});let b=!1,v=!1;try{let r;(o=w&&w.leaseId&&!e.force?await nq(t,w.leaseId,{tenant:u,runId:d,leaseBackend:h}):void 0)||(o=await t.leases.allocate({tenant:u,runId:d,leaseBackend:h}),b=!0);let n=await nH(e,t,p.resolvedPath,c,{tenantId:o.tenantId,runId:o.runId,leaseId:o.leaseId});l=n.cleanup;let a=new Date().toISOString(),I={version:1,session:c,remoteConfigPath:p.resolvedPath,remoteConfigHash:m,daemon:g,tenant:u,runId:d,leaseId:o.leaseId,leaseBackend:h,platform:e.platform,target:e.target,runtime:n.runtime,metro:l,connectedAt:w&&!e.force?w.connectedAt:a,updatedAt:a};i={stateDir:y,state:I},r=nT({stateDir:i.stateDir,session:i.state.session}),f.mkdirSync(s.dirname(r),{recursive:!0}),nF(r,i.state),nF(nC(i.stateDir),{session:i.state.session}),v=!0,w&&e.force&&(w.metro?.projectRoot!==l?.projectRoot||w.metro?.profileKey!==l?.profileKey||w.metro?.consumerKey!==l?.consumerKey)&&await nK(w.metro),w&&e.force&&(w.tenant!==I.tenant||w.runId!==I.runId||w.leaseId!==I.leaseId||!nY(w.daemon,I.daemon))&&await nX(t,w),nm(e,nJ(I),()=>`Connected remote session "${c}" tenant "${u}" run "${d}" lease ${I.leaseId}`)}catch(e){if(v||await nK(l),b&&o)try{await t.leases.release({tenant:u,runId:d,leaseId:o.leaseId})}catch{}throw e}return!0},nV=async({flags:e,client:t})=>{let r=e.session??"default",n=ea(e.stateDir).baseDir,a=nR({stateDir:n,session:r})??(e.session?null:nO({stateDir:n}));if(!a)return nm(e,{connected:!1,session:r},()=>`No remote connection for "${r}".`),!0;let i=a.session;try{await t.sessions.close({shutdown:e.shutdown})}catch{}await nK(a.metro);let o=!1;try{o=(await t.leases.release({tenant:a.tenant,runId:a.runId,leaseId:a.leaseId})).released}catch{}return n_({stateDir:n,session:i}),nm(e,{connected:!1,session:i,released:o},()=>`Disconnected remote session "${i}".`),!0},nG=async({positionals:e,flags:t})=>{if("status"!==e[0])throw new ey("INVALID_ARGS","connection accepts only: status");let r=t.session??"default",n=ea(t.stateDir).baseDir,a=nR({stateDir:n,session:r})??(t.session?null:nO({stateDir:n}));return a?nm(t,nJ(a),()=>[`Connected remote session "${a.session}".`,`tenant=${a.tenant} runId=${a.runId} leaseId=${a.leaseId} backend=${a.leaseBackend}`,`remoteConfig=${a.remoteConfigPath}`,a.runtime?"metro=prepared":"metro=not-prepared"].join("\n")):nm(t,{connected:!1,session:r},()=>`No remote connection for "${r}".`),!0};async function nq(e,t,r){try{return await e.leases.heartbeat({tenant:r.tenant,runId:r.runId,leaseId:t,leaseBackend:r.leaseBackend})}catch(e){var n;if((n=e)instanceof ey&&"UNAUTHORIZED"===n.code&&(n.details?.reason==="LEASE_NOT_FOUND"||n.details?.reason==="LEASE_EXPIRED"||n.details?.reason==="LEASE_REVOKED"))return;throw e}}async function nH(e,t,r,n,a){if(!e.metroProjectRoot&&!e.metroPublicBaseUrl&&!e.metroProxyBaseUrl)return{};if("ios"!==e.platform&&"android"!==e.platform)throw new ey("INVALID_ARGS",'connect Metro preparation requires platform "ios" or "android".');if(!e.metroPublicBaseUrl)throw new ey("INVALID_ARGS","connect Metro preparation requires metroPublicBaseUrl.");let i=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,bridgeScope:a,launchUrl:e.launchUrl,companionProfileKey:r,companionConsumerKey:n,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return{runtime:"ios"===e.platform?i.iosRuntime:i.androidRuntime,cleanup:e.metroProxyBaseUrl?{projectRoot:i.projectRoot,profileKey:r,consumerKey:n}:void 0}}async function nK(e){if(e)try{await nM(e)}catch{}}async function nX(e,t){try{await e.leases.release({tenant:t.tenant,runId:t.runId,leaseId:t.leaseId,daemonBaseUrl:t.daemon?.baseUrl,daemonTransport:t.daemon?.transport,daemonServerMode:t.daemon?.serverMode})}catch{}}function nY(e,t){return(e?.baseUrl??void 0)===(t?.baseUrl??void 0)&&(e?.transport??void 0)===(t?.transport??void 0)&&(e?.serverMode??void 0)===(t?.serverMode??void 0)}function nJ(e){return{connected:!0,session:e.session,tenant:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,platform:e.platform,target:e.target,remoteConfig:e.remoteConfigPath,remoteConfigHash:e.remoteConfigHash,daemonBaseUrlFingerprint:function(e){if(e)return y.createHash("sha256").update(e).digest("hex").slice(0,12)}(e.daemon?.baseUrl),metro:e.metro?{prepared:!0,projectRoot:e.metro.projectRoot}:{prepared:!1},connectedAt:e.connectedAt,updatedAt:e.updatedAt}}let nz=async({flags:e,client:t})=>{let r=D(await t.capture.snapshot({...np(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return nm(e,r,()=>(function(e,t={}){var r,n,a;let i,o=e.nodes,s=Array.isArray(o)?o:[],l="string"==typeof e.backend?e.backend:void 0,c=t.raw||"macos-helper"===l?null:G(s),u=!!e.truncated,d="string"==typeof e.appName?e.appName:void 0,p="string"==typeof e.appBundleId?e.appBundleId:void 0,m=[];d&&m.push(`Page: ${d}`),p&&m.push(`App: ${p}`);let f=c?.nodes??s,h=t.raw||"macos-helper"===l?null:function(e,t,r,n){let a=e.visibility;if(a&&"object"==typeof a&&"boolean"==typeof a.partial&&"number"==typeof a.visibleNodeCount&&"number"==typeof a.totalNodeCount&&Array.isArray(a.reasons))return{partial:a.partial,visibleNodeCount:a.visibleNodeCount,totalNodeCount:a.totalNodeCount,reasons:a.reasons.filter(e=>"string"==typeof e)};let i=t?.hiddenCount??0,o=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return i>0?{partial:!0,visibleNodeCount:r,totalNodeCount:n,reasons:["offscreen-nodes"]}:o?{partial:!0,visibleNodeCount:r,totalNodeCount:r,reasons:[]}:null}(e,c,f.length,s.length),g=h?.partial?h.totalNodeCount>h.visibleNodeCount?`Snapshot: ${h.visibleNodeCount} visible nodes (${h.totalNodeCount} total)${u?" (truncated)":""}`:`Snapshot: ${h.visibleNodeCount} visible nodes${u?" (truncated)":""}`:`Snapshot: ${s.length} nodes${u?" (truncated)":""}`,y=m.length>0?`${m.join("\n")}
31
+ `:"",w=(r=e,n=s,a=t,i=tl(r),!a.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let r of e){let e=(r.type??"").toLowerCase(),n=X(r).trim().toLowerCase();if(!n)continue;let a=`${e}|${n}`;t.set(a,(t.get(a)??0)+1)}let r=0;for(let e of t.values())e>1&&(r+=e);return r>=8}(n)&&i.push("Warning: possible repeated nav subtree detected."),i),b=w.length>0?`${w.join("\n")}
30
32
  `:"";if(0===s.length)return`${y}${g}
31
33
  ${b}`;if(t.raw){let e=s.map(e=>JSON.stringify(e));return`${y}${g}
32
34
  ${b}${e.join("\n")}
33
- `}if(t.flatten){let e=V(f,{summarizeTextSurfaces:!0}).flatMap(e=>[eu(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...tn({...e,depth:0})]),t=u&&u.summaryLines.length>0?`
34
- ${u.summaryLines.join("\n")}`:"";return`${y}${g}
35
+ `}if(t.flatten){let e=V(f,{summarizeTextSurfaces:!0}).flatMap(e=>[eu(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...tc({...e,depth:0})]),t=c&&c.summaryLines.length>0?`
36
+ ${c.summaryLines.join("\n")}`:"";return`${y}${g}
35
37
  ${b}${e.join("\n")}${t}
36
- `}let v=V(f,{summarizeTextSurfaces:!0}).flatMap(e=>[e.text,...tn(e)]),x=u&&u.summaryLines.length>0?`
37
- ${u.summaryLines.join("\n")}`:"";return`${y}${g}
38
- ${b}${v.join("\n")}${x}
39
- `})(r,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},nE=[0,187,255,255];function nR(e,t,r,n){if(t<0||t>=e.width||r<0||r>=e.height)return;let a=(r*e.width+t)*4;e.data[a]=n[0],e.data[a+1]=n[1],e.data[a+2]=n[2],e.data[a+3]=n[3]}function n_(e,t,r){return Math.min(Math.max(e,t),r)}let nT={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},nO={leading:20,trailing:20,separator:10,unknown:0,background:-30};function nC(e){return"background"!==e.likelyKind}function nU(e,t){return e.width>=.25*t.width||e.height>=.06*t.height}function nF(e,t){let r,n=0;for(let a of t){let t=nq(e,a.rect);t<=n||(n=t,r=a)}return r}function nj(e){let t=[];for(let r of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>{var t,n;return t=e.rect,nq(t,n=r.rect)>0||Math.abs(nX(t).y-nX(n).y)<=.5*Math.max(t.height,n.height)});if(!e){t.push({rect:r.rect,blocks:[r]});continue}e.blocks.push(r),e.blocks.sort((e,t)=>e.rect.x-t.rect.x),e.rect=function(e){let t=1/0,r=1/0,n=-1/0,a=-1/0;for(let i of e)t=Math.min(t,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x+i.width),a=Math.max(a,i.y+i.height);return{x:t,y:r,width:n-t,height:a-r}}([e.rect,r.rect])}return t}function nV(e,t){let r,n=nX(e);for(let e of t){var a,i;let t=Math.sqrt((a=n,i=nX(e.rect),(a.x-i.x)**2+(a.y-i.y)**2));r&&t>=r.distance||(r={block:e,distance:t})}return r}function nB(e){let t=nG(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function nG(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function nq(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function nX(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function nY(e,t,r){return Math.min(Math.max(e,t),r)}async function nH(e){if(await ec("tesseract"))try{let[t,r]=await Promise.all([nK(e.baselinePath),nK(e.currentPath)]);if(0!==t.exitCode||0!==r.exitCode)return;let n=nJ(t.stdout,e.width,e.height),a=nJ(r.stdout,e.width,e.height),i=function(e,t){let r=new Set,n=[];for(let i of e){var a;let e=n2(i.text),o=function(e,t,r,n){let a=null,i=1/0;for(let l=0;l<r.length;l+=1){var o,s;if(n.has(l))continue;let u=r[l];if(n2(u.text)!==t)continue;let c=(o=nQ(e.normalizedRect),s=nQ(u.normalizedRect),(o.x-s.x)**2+(o.y-s.y)**2);c>=i||(a=l,i=c)}return a}(i,e,t,r);if(null===o)continue;r.add(o);let s=function(e,t){let r={x:t.rect.x-e.rect.x,y:t.rect.y-e.rect.y,width:t.rect.width-e.rect.width,height:t.rect.height-e.rect.height},n=n8(t.rect.width/e.rect.width),a=n8(t.rect.height/e.rect.height),i=Math.abs(n-1)>=.08||Math.abs(a-1)>=.12;return{text:e.text,baselineRect:e.rect,currentRect:t.rect,delta:r,confidence:Math.round(100*Math.min(e.confidence,t.confidence))/100,possibleTextMetricMismatch:i}}(i,t[o]);a=s,(Math.abs(a.delta.x)>=2||Math.abs(a.delta.y)>=2||Math.abs(a.delta.width)>=2||Math.abs(a.delta.height)>=2||a.possibleTextMetricMismatch)&&n.push(s)}return n.sort((e,t)=>nz(t)-nz(e)).slice(0,12)}(n,a),o=function(e){let t=[];for(let r of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>32>=Math.abs(r.delta.x-n3(e.map(e=>e.delta.x))));e?e.push(r):t.push([r])}return t.filter(e=>e.length>=2).map(nW).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>nZ(t)-nZ(e)).slice(0,4)}(i);if(0===n.length&&0===a.length)return;return{provider:"tesseract",baselineBlocks:n.length,currentBlocks:a.length,baselineBlocksRaw:n,currentBlocksRaw:a,matches:i,...o.length>0?{movementClusters:o}:{}}}catch{return}}function nJ(e,t,r){let[n,...a]=e.split(/\r?\n/);if(!n)return[];let i=new Map(n.split(" ").map((e,t)=>[e,t])),o=[];for(let e of a){var s;if(!e.trim())continue;let t=e.split(" "),r=n1(t,i,"level"),n=n0(t,i,"text").trim(),a=n1(t,i,"conf");if(5!==r||(s=n,!/[\p{L}\p{N}]/u.test(s))||a<0)continue;let l=n1(t,i,"left"),u=n1(t,i,"top"),c=n1(t,i,"width"),p=n1(t,i,"height");c<=0||p<=0||o.push({key:[n0(t,i,"page_num"),n0(t,i,"block_num"),n0(t,i,"par_num"),n0(t,i,"line_num")].join(":"),text:n,confidence:a,rect:{x:l,y:u,width:c,height:p}})}let l=new Map;for(let e of o){let t=l.get(e.key);t?t.push(e):l.set(e.key,[e])}return Array.from(l.values()).flatMap(e=>(function(e){let t=[...e].sort((e,t)=>e.rect.x-t.rect.x),r=[],n=[];for(let e of t){let t=n.at(-1);if(!t){n.push(e);continue}if(e.rect.x-(t.rect.x+t.rect.width)>Math.max(48,2.5*Math.max(t.rect.height,e.rect.height))){r.push(n),n=[e];continue}n.push(e)}return n.length>0&&r.push(n),r})(e)).map(e=>(function(e,t,r){if(0===e.length)return null;let n=[...e].sort((e,t)=>e.rect.x-t.rect.x),a=function(e){let t=1/0,r=1/0,n=-1/0,a=-1/0;for(let i of e)t=Math.min(t,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x+i.width),a=Math.max(a,i.y+i.height);return{x:t,y:r,width:n-t,height:a-r}}(n.map(e=>e.rect)),i=Math.round(100*n3(n.map(e=>e.confidence)))/100;return{text:n.map(e=>e.text).join(" "),confidence:i,rect:a,normalizedRect:{x:n5(a.x/t),y:n5(a.y/r),width:n5(a.width/t),height:n5(a.height/r)}}})(e,t,r)).filter(e=>null!==e)}function nK(e){return eh("tesseract",[e,"stdout","-l","eng","tsv"],{allowFailure:!0,timeoutMs:1e4})}function nz(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+25*!!e.possibleTextMetricMismatch}function nW(e){let t=e.map(e=>e.delta.x),r=e.map(e=>e.delta.y);return{texts:e.map(e=>e.text),xRange:{min:Math.min(...t),max:Math.max(...t)},yRange:{min:Math.min(...r),max:Math.max(...r)}}}function nZ(e){return 2*Math.abs((e.xRange.min+e.xRange.max)/2)+Math.abs((e.yRange.min+e.yRange.max)/2)}function nQ(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function n0(e,t,r){let n=t.get(r);return void 0===n?"":e[n]??""}function n1(e,t,r){let n=Number(n0(e,t,r));return Number.isFinite(n)?n:0}function n2(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function n3(e){return e.reduce((e,t)=>e+t,0)/e.length}function n5(e){return Math.round(100*e*100)/100}function n8(e){return Math.round(1e3*e)/1e3}function n4(e,t,r,n){return{r:Math.round(e/n),g:Math.round(t/n),b:Math.round(r/n)}}function n6(e){return .2126*e.r+.7152*e.g+.0722*e.b}function n7(e){return`#${n9(e.r)}${n9(e.g)}${n9(e.b)}`}function n9(e){return e.toString(16).padStart(2,"0")}function ae(e){return Math.round(100*e*100)/100}let at=255*Math.sqrt(3);async function ar(e,t,r={}){let n,a,i,o;await an(e,"Baseline image not found"),await an(t,"Current screenshot not found");let l=r.outputPath,[u,c]=await Promise.all([h.readFile(e),h.readFile(t)]),p=es(u,"baseline screenshot"),d=es(c,"current screenshot"),m=r.threshold??.1;if(p.width!==d.width||p.height!==d.height){let e=p.width*p.height;return await aa(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:p.width,height:p.height},actual:{width:d.width,height:d.height}}}}let f=p.width*p.height,g=m*at,y=new b({width:p.width,height:p.height}),w=new Uint8Array(f),v=0;for(let e=0,t=0;e<p.data.length;e+=4,t+=1){if(Math.sqrt((p.data[e]-d.data[e])**2+(p.data[e+1]-d.data[e+1])**2+(p.data[e+2]-d.data[e+2])**2)>g){v+=1,w[t]=1;let r=ai(d,e);y.data[e]=ao(r,220,.78),y.data[e+1]=ao(r,0,.78),y.data[e+2]=ao(r,0,.78),y.data[e+3]=255;continue}let r=ai(d,e);y.data[e]=r,y.data[e+1]=r,y.data[e+2]=r,y.data[e+3]=255}let x=v>0?(I=(n=function(e){let{diffMask:t,baseline:r,current:n}=e,{width:a,height:i}=r,o=new Uint8Array(t.length),s=new Int32Array(t.length),l=[];for(let e=0;e<t.length;e+=1){if(1!==t[e]||1===o[e])continue;let u=0,c=0;s[0]=e,c+=1,o[e]=1;let p=e%a,d=Math.floor(e/a),m={minX:p,minY:d,maxX:p,maxY:d,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0};for(;u<c;){let e=s[u];u+=1,function(e,t,r,n,a){let i=t%r,o=Math.floor(t/r),s=4*t;e.minX=Math.min(e.minX,i),e.minY=Math.min(e.minY,o),e.maxX=Math.max(e.maxX,i),e.maxY=Math.max(e.maxY,o),e.differentPixels+=1,e.baselineRed+=n.data[s],e.baselineGreen+=n.data[s+1],e.baselineBlue+=n.data[s+2],e.currentRed+=a.data[s],e.currentGreen+=a.data[s+1],e.currentBlue+=a.data[s+2]}(m,e,a,r,n);let l=e%a,p=Math.floor(e/a);for(let e=-1;e<=1;e+=1){let r=p+e;if(!(r<0)&&!(r>=i))for(let n=-1;n<=1;n+=1){if(0===n&&0===e)continue;let i=l+n;if(i<0||i>=a)continue;let u=r*a+i;1===t[u]&&1!==o[u]&&(o[u]=1,s[c]=u,c+=1)}}}l.push(m)}return l}(k={diffMask:w,baseline:p,current:d,totalPixels:f,differentPixels:v,maxRegions:r.maxRegions})).length<=2e3?function(e){let t=[];for(let a of e.sort((e,t)=>{let r=e.minY-t.minY;return 0!==r?r:e.minX-t.minX})){var r,n;let e=t.find(e=>{var t,r,n;return t=e,r=a,n=12,t.minX-n<=r.maxX&&r.minX-n<=t.maxX&&t.minY-n<=r.maxY&&r.minY-n<=t.maxY});if(!e){t.push({...a});continue}r=e,n=a,r.minX=Math.min(r.minX,n.minX),r.minY=Math.min(r.minY,n.minY),r.maxX=Math.max(r.maxX,n.maxX),r.maxY=Math.max(r.maxY,n.maxY),r.differentPixels+=n.differentPixels,r.baselineRed+=n.baselineRed,r.baselineGreen+=n.baselineGreen,r.baselineBlue+=n.baselineBlue,r.currentRed+=n.currentRed,r.currentGreen+=n.currentGreen,r.currentBlue+=n.currentBlue}return t}(n):n,I.flatMap(e=>{var t,r,n;let a;return(t=e,r=k.baseline.width,n=k.baseline.height,a=t.maxX-t.minX+1,t.maxY-t.minY+1>=Math.max(48,Math.round(.07*n))&&a>=.35*r)?function(e,t,r){var n;let a=function(e,t){let r=[],n=null;for(let a=0;a<e.length;a+=1){if(e[a]<=t){n??=a;continue}null!==n&&(a-n>=6&&r.push([n,a-1]),n=null)}return null!==n&&e.length-n>=6&&r.push([n,e.length-1]),r}((n=function(e,t,r){let n=[];for(let a=e.minY;a<=e.maxY;a+=1){let i=0;for(let n=e.minX;n<=e.maxX;n+=1)1===t[a*r+n]&&(i+=1);n.push(i)}return n}(e,t.diffMask,t.baseline.width)).map((e,t)=>{let r=0,a=0,i=Math.max(0,t-3),o=Math.min(n.length-1,t+3);for(let e=i;e<=o;e+=1)r+=n[e],a+=1;return Math.round(r/a)}),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),i=function(e,t,r){let n=[],a=e.minY;for(let[i,o]of t){let t=e.minY+Math.round((i+o)/2);t-a+1<r||e.maxY-t<r||(n.push([a,t]),a=t+1)}return n.push([a,e.maxY]),n}(e,a,r);if(i.length<=1)return[e];let o=i.map(([r,n])=>(function(e,t,r,n){let a=null;for(let s=t;s<=r;s+=1)for(let t=e.minX;t<=e.maxX;t+=1){var i,o;let e=s*n.baseline.width+t;1===n.diffMask[e]&&function(e,t,r,n,a,i){let o=4*t;e.minX=Math.min(e.minX,r),e.minY=Math.min(e.minY,n),e.maxX=Math.max(e.maxX,r),e.maxY=Math.max(e.maxY,n),e.differentPixels+=1,e.baselineRed+=a.data[o],e.baselineGreen+=a.data[o+1],e.baselineBlue+=a.data[o+2],e.currentRed+=i.data[o],e.currentGreen+=i.data[o+1],e.currentBlue+=i.data[o+2]}(a??={minX:i=t,minY:o=s,maxX:i,maxY:o,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0},e,t,s,n.baseline,n.current)}return a})(e,r,n,t)).filter(e=>null!==e);return o.length>1?o:[e]}(e,k,Math.max(24,Math.round(.03*k.baseline.height))):[e]})).sort((e,t)=>{let r=t.differentPixels-e.differentPixels;if(0!==r)return r;let n=e.minY-t.minY;return 0!==n?n:e.minX-t.minX}).slice(0,Math.max(0,k.maxRegions??8)).map((e,t)=>{var r,n,a,i,o,s,l,u,c,p,d;let m,f,h,g,y,w,b,v,x,I,A,D,S,$,M,P,N;return r=e,n=t+1,a={width:k.baseline.width,height:k.baseline.height,totalPixels:k.totalPixels,differentPixels:k.differentPixels},w={x:r.minX,y:r.minY,width:r.maxX-r.minX+1,height:r.maxY-r.minY+1},b={x:Math.round(r.minX+w.width/2),y:Math.round(r.minY+w.height/2)},v=n4(r.baselineRed,r.baselineGreen,r.baselineBlue,r.differentPixels),x=n4(r.currentRed,r.currentGreen,r.currentBlue,r.differentPixels),I=w.width*w.height,A=ae(r.differentPixels/I),D=Math.round(n6(v)),S=Math.round(n6(x)),$=(i=w,o=a.width,s=a.height,i.width>=.55*o&&i.height>=.12*s?"large-area":i.width>=2.5*i.height?"horizontal-band":i.height>=2.5*i.width?"vertical-band":"compact"),M=(m=I/a.totalPixels)>=.04?"large":m>=.01?"medium":"small",P=(l=v,u=x,f=n6(l),Math.abs(h=n6(u)-f)>=12?h>0?"brighter":"darker":Math.max(Math.abs(u.r-l.r),Math.abs(u.g-l.g),Math.abs(u.b-l.b))>=12?"color-shift":"mixed"),N=(c=b,p=a.width,d=a.height,g=c.x<p/3?"left":c.x>2*p/3?"right":"center",y=c.y<d/3?"top":c.y>2*d/3?"bottom":"middle","center"===g&&"middle"===y?"center":`${y}-${g}`),{index:n,rect:w,normalizedRect:{x:ae(w.x/a.width),y:ae(w.y/a.height),width:ae(w.width/a.width),height:ae(w.height/a.height)},differentPixels:r.differentPixels,shareOfDiffPercentage:ae(r.differentPixels/a.differentPixels),densityPercentage:A,shape:$,size:M,location:N,averageBaselineColorHex:n7(v),averageCurrentColorHex:n7(x),baselineLuminance:D,currentLuminance:S,dominantChange:P}}):[];if(v>0&&l){var k,I,A;for(let e of x)e.rect.width<4||e.rect.height<4||function(e,t){let r=n_(t.x,0,e.width-1),n=n_(t.y,0,e.height-1),a=n_(t.x+t.width-1,0,e.width-1),i=n_(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let o=r;o<=a;o+=1)nR(e,o,n+t,nE),nR(e,o,i-t,nE);for(let o=n;o<=i;o+=1)nR(e,r+t,o,nE),nR(e,a-t,o,nE)}}(y,e.rect);await h.mkdir(s.dirname(l),{recursive:!0}),await h.writeFile(l,b.sync.write(y))}else await aa(r.outputPath);let D=v>0?await nH({baselinePath:e,currentPath:t,width:p.width,height:p.height}):void 0,S=D&&(D.matches.length>0||(D.movementClusters?.length??0)>0)?{provider:D.provider,baselineBlocks:D.baselineBlocks,currentBlocks:D.currentBlocks,matches:D.matches,...D.movementClusters?{movementClusters:D.movementClusters}:{}}:void 0,$=v>0&&D?(a=function(e){let t=[];for(let r of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=t.find(e=>{var t,n,a;return t=e,n=r,a=10,t.minX-a<=n.maxX&&n.minX-a<=t.maxX&&t.minY-a<=n.maxY&&n.minY-a<=t.maxY});if(!e){t.push({...r});continue}e.minX=Math.min(e.minX,r.minX),e.minY=Math.min(e.minY,r.minY),e.maxX=Math.max(e.maxX,r.maxX),e.maxY=Math.max(e.maxY,r.maxY),e.differentPixels+=r.differentPixels}return t}(function(e,t,r){let n=new Uint8Array(e.length),a=new Int32Array(e.length),i=[];for(let o=0;o<e.length;o+=1){if(1!==e[o]||1===n[o])continue;let s=0,l=0;a[0]=o,l+=1,n[o]=1;let u=o%t,c=Math.floor(o/t),p={minX:u,minY:c,maxX:u,maxY:c,differentPixels:0};for(;s<l;){let i=a[s];s+=1;let o=i%t,u=Math.floor(i/t);p.minX=Math.min(p.minX,o),p.minY=Math.min(p.minY,u),p.maxX=Math.max(p.maxX,o),p.maxY=Math.max(p.maxY,u),p.differentPixels+=1;for(let i=-1;i<=1;i+=1){let s=u+i;if(!(s<0)&&!(s>=r))for(let r=-1;r<=1;r+=1){if(0===r&&0===i)continue;let u=o+r;if(u<0||u>=t)continue;let c=s*t+u;1===e[c]&&1!==n[c]&&(n[c]=1,a[l]=c,l+=1)}}}i.push(p)}return i}(function(e,t,r,n){let a=new Uint8Array(e);if(!n)return a;for(let e of[...n.baselineBlocksRaw,...n.currentBlocksRaw]){var i;!function(e,t,r,n){let a=nY(Math.floor(n.x),0,t-1),i=nY(Math.floor(n.y),0,r-1),o=nY(Math.ceil(n.x+n.width),0,t),s=nY(Math.ceil(n.y+n.height),0,r);for(let r=i;r<s;r+=1)for(let n=a;n<o;n+=1)e[r*t+n]=0}(a,t,r,{x:(i=e.rect).x-8,y:i.y-8,width:i.width+16,height:i.height+16})}return a}((A={diffMask:w,width:p.width,height:p.height,regions:x,ocr:D}).diffMask,A.width,A.height,A.ocr),A.width,A.height)),i=nj(A.ocr?.currentBlocksRaw??[]),o=nj(A.ocr?.baselineBlocksRaw??[]),a.filter(nB).map(e=>{var t,r,n,a,s,l,u,c,p,d,m;let f,h,g,y,w,b,v,x,k,I;return t=e,r=A,n=i,a=o,y=function(e,t){let r,n=0;for(let a of t){let t=function(e,t){let r=Math.max(e.x,t.x),n=Math.max(e.y,t.y),a=Math.min(e.x+e.width,t.x+t.width),i=Math.min(e.y+e.height,t.y+t.height);return a<=r||i<=n?0:(a-r)*(i-n)}(e,a.rect);t<=n||(n=t,r=a)}return r?.index}(g=nG(t),r.regions),w=function(e,t,r){let n=nF(e,t);if(n)return nV(e,n.blocks);let a=nF(e,r);return a?nV(e,a.blocks):void 0}(g,n,a),b=function(e,t,r){if(e.height<=3&&e.width>=.12*r)return"separator";if(!t)return e.width>=.4*r?"background":"unknown";if(e.width>=.4*r)return"background";let n=e.x+e.width/2,a=t.x+t.width/2;return n<a-t.width/2?"leading":n>a+t.width/2?"trailing":e.width>=.35*r?"background":"unknown"}(g,w?.block.rect,r.width),v=(s=g,l=b,u=t.differentPixels,c=r,f=s.width/s.height,h=u/(s.width*s.height),"separator"===l?"separator":"background"===l?"background":"trailing"===l&&f>=1.5&&f<=3.8&&h>=.35?"toggle":"trailing"===l&&s.width<=.06*c.width&&s.height<=.04*c.height?"chevron":"leading"===l&&f>=.55&&f<=1.8?"icon":nU(s,c)?"background":"visual"),x={...y?{regionIndex:y}:{},slot:b,likelyKind:v,rect:g},{...y?{regionIndex:y}:{},slot:b,likelyKind:v,rect:g,...w?{nearestText:w.block.text.trim().replace(/^[^\p{L}\p{N}]+/u,"").replace(/^\p{L}\s+/u,"")}:{},score:(p=x,d=t.differentPixels,m=r,k=nU(p.rect,m)?-35:0,I=20*!!p.regionIndex,nT[p.likelyKind]+nO[p.slot]+I+k+Math.min(20,d/200))}}).filter(e=>e.rect.y>=.08*A.height).filter(nC).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,A.maxDeltas??12)).map((e,t)=>{var r;return r=e,{index:t+1,...r.regionIndex?{regionIndex:r.regionIndex}:{},slot:r.slot,likelyKind:r.likelyKind,rect:r.rect,...r.nearestText?{nearestText:r.nearestText}:{}}})):[],M=f>0?Math.round(v/f*1e4)/100:0;return{...v>0&&l?{diffPath:l}:{},...x.length>0?{regions:x}:{},...S?{ocr:S}:{},...$.length>0?{nonTextDeltas:$}:{},totalPixels:f,differentPixels:v,mismatchPercentage:M,match:0===v}}async function an(e,t){try{await h.access(e)}catch{throw new eg("INVALID_ARGS",`${t}: ${e}`)}}async function aa(e){if(e)try{await h.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function ai(e,t){return ao(Math.round(.299*e.data[t]+.587*e.data[t+1]+.114*e.data[t+2]),255,.72)}function ao(e,t,r){return Math.round(e*(1-r)+t*r)}function as(e){return e.width*e.height}function al(e){return Math.round(100*e*100)/100}let au=async({positionals:e,flags:t,client:r})=>{let n=await r.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs,...void 0!==t.screenshotFullscreen?{fullscreen:t.screenshotFullscreen}:{}});return nf(t,{path:n.path,...n.overlayRefs?{overlayRefs:n.overlayRefs}:{}},()=>n.overlayRefs?`Annotated ${n.overlayRefs.length} refs onto ${n.path}`:n.path),!0},ac=async({positionals:e,flags:t,client:r})=>{let n;if("snapshot"===e[0]){let e=await r.capture.diff({...nm(t),kind:"snapshot",out:t.out,interactiveOnly:t.snapshotInteractiveOnly,compact:t.snapshotCompact,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw});return nf(t,e,()=>(function(e){var t;let r=!0===e.baselineInitialized,n=e.summary??{},a=te(n.additions),i=te(n.removals),o=te(n.unchanged),s=tt(),u=tr(e),c=u.length>0?`${u.join("\n")}
40
- `:"";if(r)return`${c}Baseline initialized (${o} lines).
41
- `;let p=(function(e){if(0===e.length)return e;let t=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===t.length)return e;let r=Array(e.length).fill(!1);for(let n of t){let t=Math.max(0,n-1),a=Math.min(e.length-1,n+1);for(let e=t;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(e.lines)?e.lines:[]).map(e=>{let t="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=t.startsWith(" ")?`+${t}`:`+ ${t}`;return s?l("green",e):e}if("removed"===e.kind){let e=t.startsWith(" ")?`-${t}`:`- ${t}`;return s?l("red",e):e}return s?l("dim",t):t}),d=p.length>0?`${p.join("\n")}
42
- `:"";if(!s)return`${c}${d}${a} additions, ${i} removals, ${o} unchanged
43
- `;let m=`${(t=String(a),l("green",t))} additions, ${l("red",String(i))} removals, ${l("dim",String(o))} unchanged`;return`${c}${d}${m}
44
- `})(e)),!0}if("screenshot"!==e[0])return!1;let a=t.baseline;if(!a||"string"!=typeof a)throw new eg("INVALID_ARGS","diff screenshot requires --baseline <path>");let i=z(a),o="string"==typeof t.out?z(t.out):void 0,u=.1;if(null!=t.threshold&&""!==t.threshold&&(Number.isNaN(u=Number(t.threshold))||u<0||u>1))throw new eg("INVALID_ARGS","--threshold must be a number between 0 and 1");let c=f.mkdtempSync(s.join(w.tmpdir(),"agent-device-diff-current-")),p=s.join(c,`current-${Date.now()}.png`),d=(await r.capture.screenshot({path:p})).path;try{if(n=await ar(i,d,{threshold:u,outputPath:o}),!t.overlayRefs||n.match||n.dimensionMismatch)t.overlayRefs&&o&&function(e){try{f.unlinkSync(ap(e))}catch(e){var t;if(t=e,"object"!=typeof t||null===t||!("code"in t)||"ENOENT"!==t.code)throw e}}(o);else{var m,h;let e=await r.capture.screenshot({path:o?ap(o):void 0,overlayRefs:!0});n={...n,currentOverlayPath:e.path,...e.overlayRefs?{currentOverlayRefCount:e.overlayRefs.length}:{},...n.regions&&e.overlayRefs?{regions:(m=n.regions,h=e.overlayRefs,m.map(e=>{var t,r;let n,a=(t=e,r=h,n=as(t.rect),r.map(e=>{var r,a;let i,o,s,l,u=e.overlayRect,c=(r=t.rect,a=u,i=Math.max(r.x,a.x),o=Math.max(r.y,a.y),s=Math.min(r.x+r.width,a.x+a.width),l=Math.min(r.y+r.height,a.y+a.height),s<=i||l<=o?0:(s-i)*(l-o));return c<=0?null:{ref:e.ref,...e.label?{label:e.label}:{},rect:u,overlayCoveragePercentage:al(c/as(u)),regionCoveragePercentage:al(c/n)}}).filter(e=>null!==e).sort((e,t)=>{let r=t.regionCoveragePercentage-e.regionCoveragePercentage;return 0!==r?r:t.overlayCoveragePercentage-e.overlayCoveragePercentage}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage})));return a.length>0?{...e,currentOverlayMatches:a}:e}))}:{}}}}finally{try{f.unlinkSync(d)}catch{}try{f.rmSync(c,{recursive:!0,force:!0})}catch{}}return nf(t,n,()=>(function(e){let t=tt(),r=!0===e.match,n=te(e.differentPixels),a=te(e.totalPixels),i=te(e.mismatchPercentage),o=e.diffPath,s=e.dimensionMismatch,u=[];if(r){let e=t?l("green","✓"):"✓";u.push(`${e} Screenshots match.`)}else if(s){let e=t?l("red","✗"):"✗",r=s.expected,n=s.actual;u.push(`${e} Screenshots have different dimensions: expected ${r?.width}x${r?.height}, got ${n?.width}x${n?.height}`)}else{let e=t?l("red","✗"):"✗",r=0===i&&n>0?"<0.01":String(i);u.push(`${e} ${r}% pixels differ`)}if(o&&!r){let e=e9(o),r=t?l("dim","Diff image:"):"Diff image:",n=t?l("green",e):e;u.push(` ${r} ${n}`)}if(e.currentOverlayPath&&!r){let r=e9(e.currentOverlayPath),n=t?l("dim","Current overlay:"):"Current overlay:",a=t?l("green",r):r,i=te(e.currentOverlayRefCount),o=i>0?` (${i} refs)`:"";u.push(` ${n} ${a}${o}`)}if(!r&&!s){let e=t?l("red",String(n)):String(n);u.push(` ${e} different / ${a} total pixels`)}let c=r||s?[]:function(e){let t=[];for(let r of(e.ocr?.movementClusters??[]).slice(0,2))t.push(`text movement cluster: ${function(e){let t=e.slice(0,4).map(e=>JSON.stringify(e)),r=e.length>t.length?` +${e.length-t.length} more`:"";return`${t.join(", ")}${r}`}(r.texts)} dx=${e7(r.xRange)}px dy=${e7(r.yRange)}px`);let r=(e.nonTextDeltas??[]).filter(e=>["icon","toggle","chevron"].includes(e.likelyKind)).slice(0,3);r.length>0&&t.push(`non-text controls: ${r.map(e6).join("; ")}`);let n=(e.nonTextDeltas??[]).filter(e=>"separator"===e.likelyKind).slice(0,2);return n.length>0&&t.push(`non-text boundaries: ${n.map(e6).join("; ")}`),t.slice(0,6)}(e);if(c.length>0)for(let e of(u.push(" Hints:"),c))u.push(` - ${e}`);let p=Array.isArray(e.regions)?e.regions:[];if(!r&&!s&&p.length>0)for(let e of(u.push(" Changed regions:"),p.slice(0,5))){let t=0===e.shareOfDiffPercentage&&e.differentPixels>0?"<0.01":String(e.shareOfDiffPercentage),r=e.rect;u.push(` ${e.index}. ${e.location} x=${r.x} y=${r.y} ${r.width}x${r.height}, ${t}% of diff, change=${e.dominantChange}`);let n=function(e){let t=[e.size?`size=${e.size}`:null,e.shape?`shape=${e.shape}`:null,"number"==typeof e.densityPercentage?`density=${e.densityPercentage}%`:null,e.averageBaselineColorHex&&e.averageCurrentColorHex?`avgColor=${e.averageBaselineColorHex}->${e.averageCurrentColorHex}`:null,"number"==typeof e.baselineLuminance&&"number"==typeof e.currentLuminance?`luminance=${e.baselineLuminance}->${e.currentLuminance}`:null].filter(e=>null!==e);return t.length>0?t.join(" "):null}(e);n&&u.push(` ${n}`);let a=e.currentOverlayMatches?.[0];if(a){let e=a.label?` "${a.label}"`:"";u.push(` overlaps @${a.ref}${e}, ${a.regionCoveragePercentage}% of region`)}}let d=e.ocr?.matches??[];if(!r&&!s&&d.length>0){let t=d.slice(0,8);for(let[r,n]of(u.push(` OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${t.length}/${d.length}; px):`),u.push(" item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint"),t.entries())){let e=n.delta;u.push(` ${r+1} | ${JSON.stringify(n.text)} | ${e4(e.x)},${e4(e.y)} | ${e4(e.width)},${e4(e.height)} | ${e8(n.baselineRect)} | ${e8(n.currentRect)} | ${n.confidence} | ${n.possibleTextMetricMismatch?"ocr-bbox-size-change":"-"}`)}}let m=e.nonTextDeltas??[];if(!r&&!s&&m.length>0){let e=m.slice(0,8);for(let t of(u.push(` Non-text visual deltas (showing ${e.length}/${m.length}; px):`),u.push(" item | region | slot | kind | bboxCurrent | nearestText"),e))u.push(` ${t.index} | ${t.regionIndex?`r${t.regionIndex}`:"-"} | ${t.slot} | ${t.likelyKind} | ${e8(t.rect)} | ${t.nearestText?JSON.stringify(t.nearestText):"-"}`)}return`${u.join("\n")}
45
- `})(n)),!0};function ap(e){let t=s.extname(e),r=t?e.slice(0,-t.length):e;return`${r}.current-overlay${t||".png"}`}function ad(e){return null===e?{}:{timeoutMs:e}}function am(e){let{suite:t,json:r,verbose:n,reportJunit:a}=e;return(a&&function(e,t){let r=s.dirname(e);try{f.mkdirSync(r,{recursive:!0}),f.writeFileSync(e,function(e){let t=['<?xml version="1.0" encoding="UTF-8"?>',"<testsuites>",` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${ag(e.durationMs)}">`];for(let r of e.tests)t.push(...function(e){let t=ay(s.basename(e.file)),r=ay("."===s.dirname(e.file)?e.file:s.dirname(e.file)),n=ay(e.file),a=ag(e.durationMs),i=[` <testcase classname="${r}" name="${t}" file="${n}" time="${a}">`];"failed"===e.status?i.push(` <failure message="${ay(e.error.message)}">${ay(function(e){let t=[e.error.message];e.error.hint&&t.push(`hint: ${e.error.hint}`),e.error.diagnosticId&&t.push(`diagnosticId: ${e.error.diagnosticId}`),e.error.logPath&&t.push(`logPath: ${e.error.logPath}`),e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`);let r=e.error.details?JSON.stringify(e.error.details,null,2):void 0;return r&&t.push(`details: ${r}`),t.join("\n")}(e))}</failure>`):"skipped"===e.status&&i.push(` <skipped message="${ay(e.message)}" />`);let o=function(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return"attempts"in e&&t.push(`attempts: ${e.attempts}`),"session"in e&&t.push(`session: ${e.session}`),"replayed"in e&&t.push(`replayed: ${e.replayed}`),"healed"in e&&t.push(`healed: ${e.healed}`),"artifactsDir"in e&&e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`),"passed"===e.status&&e.attempts>1&&t.push("flaky: true"),t.join("\n")}(e);return o&&i.push(` <system-out>${ay(o)}</system-out>`),i.push(" </testcase>"),i}(r));return t.push(" </testsuite>"),t.push("</testsuites>"),`${t.join("\n")}
46
- `}(t),"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new eg("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(a,t),r)?(e3({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let r=e.tests.filter(ah);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return af(e);let t="passed"===e.status?ah(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",r="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",n=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${r}${n}
38
+ `}let v=V(f,{summarizeTextSurfaces:!0}).flatMap(e=>[e.text,...tc(e)]),I=c&&c.summaryLines.length>0?`
39
+ ${c.summaryLines.join("\n")}`:"";return`${y}${g}
40
+ ${b}${v.join("\n")}${I}
41
+ `})(r,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},nW=[0,187,255,255];function nZ(e,t,r,n){if(t<0||t>=e.width||r<0||r>=e.height)return;let a=(r*e.width+t)*4;e.data[a]=n[0],e.data[a+1]=n[1],e.data[a+2]=n[2],e.data[a+3]=n[3]}function nQ(e,t,r){return Math.min(Math.max(e,t),r)}let n0={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},n1={leading:20,trailing:20,separator:10,unknown:0,background:-30};function n2(e){return"background"!==e.likelyKind}function n3(e,t){return e.width>=.25*t.width||e.height>=.06*t.height}function n5(e,t){let r,n=0;for(let a of t){let t=n9(e,a.rect);t<=n||(n=t,r=a)}return r}function n8(e){let t=[];for(let r of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>{var t,n;return t=e.rect,n9(t,n=r.rect)>0||Math.abs(ae(t).y-ae(n).y)<=.5*Math.max(t.height,n.height)});if(!e){t.push({rect:r.rect,blocks:[r]});continue}e.blocks.push(r),e.blocks.sort((e,t)=>e.rect.x-t.rect.x),e.rect=function(e){let t=1/0,r=1/0,n=-1/0,a=-1/0;for(let i of e)t=Math.min(t,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x+i.width),a=Math.max(a,i.y+i.height);return{x:t,y:r,width:n-t,height:a-r}}([e.rect,r.rect])}return t}function n4(e,t){let r,n=ae(e);for(let e of t){var a,i;let t=Math.sqrt((a=n,i=ae(e.rect),(a.x-i.x)**2+(a.y-i.y)**2));r&&t>=r.distance||(r={block:e,distance:t})}return r}function n6(e){let t=n7(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function n7(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function n9(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function ae(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function at(e,t,r){return Math.min(Math.max(e,t),r)}async function ar(e){if(await ed("tesseract"))try{let[t,r]=await Promise.all([aa(e.baselinePath),aa(e.currentPath)]);if(0!==t.exitCode||0!==r.exitCode)return;let n=an(t.stdout,e.width,e.height),a=an(r.stdout,e.width,e.height),i=function(e,t){let r=new Set,n=[];for(let i of e){var a;let e=ad(i.text),o=function(e,t,r,n){let a=null,i=1/0;for(let l=0;l<r.length;l+=1){var o,s;if(n.has(l))continue;let c=r[l];if(ad(c.text)!==t)continue;let u=(o=al(e.normalizedRect),s=al(c.normalizedRect),(o.x-s.x)**2+(o.y-s.y)**2);u>=i||(a=l,i=u)}return a}(i,e,t,r);if(null===o)continue;r.add(o);let s=function(e,t){let r={x:t.rect.x-e.rect.x,y:t.rect.y-e.rect.y,width:t.rect.width-e.rect.width,height:t.rect.height-e.rect.height},n=af(t.rect.width/e.rect.width),a=af(t.rect.height/e.rect.height),i=Math.abs(n-1)>=.08||Math.abs(a-1)>=.12;return{text:e.text,baselineRect:e.rect,currentRect:t.rect,delta:r,confidence:Math.round(100*Math.min(e.confidence,t.confidence))/100,possibleTextMetricMismatch:i}}(i,t[o]);a=s,(Math.abs(a.delta.x)>=2||Math.abs(a.delta.y)>=2||Math.abs(a.delta.width)>=2||Math.abs(a.delta.height)>=2||a.possibleTextMetricMismatch)&&n.push(s)}return n.sort((e,t)=>ai(t)-ai(e)).slice(0,12)}(n,a),o=function(e){let t=[];for(let r of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>32>=Math.abs(r.delta.x-ap(e.map(e=>e.delta.x))));e?e.push(r):t.push([r])}return t.filter(e=>e.length>=2).map(ao).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>as(t)-as(e)).slice(0,4)}(i);if(0===n.length&&0===a.length)return;return{provider:"tesseract",baselineBlocks:n.length,currentBlocks:a.length,baselineBlocksRaw:n,currentBlocksRaw:a,matches:i,...o.length>0?{movementClusters:o}:{}}}catch{return}}function an(e,t,r){let[n,...a]=e.split(/\r?\n/);if(!n)return[];let i=new Map(n.split(" ").map((e,t)=>[e,t])),o=[];for(let e of a){var s;if(!e.trim())continue;let t=e.split(" "),r=au(t,i,"level"),n=ac(t,i,"text").trim(),a=au(t,i,"conf");if(5!==r||(s=n,!/[\p{L}\p{N}]/u.test(s))||a<0)continue;let l=au(t,i,"left"),c=au(t,i,"top"),u=au(t,i,"width"),d=au(t,i,"height");u<=0||d<=0||o.push({key:[ac(t,i,"page_num"),ac(t,i,"block_num"),ac(t,i,"par_num"),ac(t,i,"line_num")].join(":"),text:n,confidence:a,rect:{x:l,y:c,width:u,height:d}})}let l=new Map;for(let e of o){let t=l.get(e.key);t?t.push(e):l.set(e.key,[e])}return Array.from(l.values()).flatMap(e=>(function(e){let t=[...e].sort((e,t)=>e.rect.x-t.rect.x),r=[],n=[];for(let e of t){let t=n.at(-1);if(!t){n.push(e);continue}if(e.rect.x-(t.rect.x+t.rect.width)>Math.max(48,2.5*Math.max(t.rect.height,e.rect.height))){r.push(n),n=[e];continue}n.push(e)}return n.length>0&&r.push(n),r})(e)).map(e=>(function(e,t,r){if(0===e.length)return null;let n=[...e].sort((e,t)=>e.rect.x-t.rect.x),a=function(e){let t=1/0,r=1/0,n=-1/0,a=-1/0;for(let i of e)t=Math.min(t,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x+i.width),a=Math.max(a,i.y+i.height);return{x:t,y:r,width:n-t,height:a-r}}(n.map(e=>e.rect)),i=Math.round(100*ap(n.map(e=>e.confidence)))/100;return{text:n.map(e=>e.text).join(" "),confidence:i,rect:a,normalizedRect:{x:am(a.x/t),y:am(a.y/r),width:am(a.width/t),height:am(a.height/r)}}})(e,t,r)).filter(e=>null!==e)}function aa(e){return eg("tesseract",[e,"stdout","-l","eng","tsv"],{allowFailure:!0,timeoutMs:1e4})}function ai(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+25*!!e.possibleTextMetricMismatch}function ao(e){let t=e.map(e=>e.delta.x),r=e.map(e=>e.delta.y);return{texts:e.map(e=>e.text),xRange:{min:Math.min(...t),max:Math.max(...t)},yRange:{min:Math.min(...r),max:Math.max(...r)}}}function as(e){return 2*Math.abs((e.xRange.min+e.xRange.max)/2)+Math.abs((e.yRange.min+e.yRange.max)/2)}function al(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function ac(e,t,r){let n=t.get(r);return void 0===n?"":e[n]??""}function au(e,t,r){let n=Number(ac(e,t,r));return Number.isFinite(n)?n:0}function ad(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function ap(e){return e.reduce((e,t)=>e+t,0)/e.length}function am(e){return Math.round(100*e*100)/100}function af(e){return Math.round(1e3*e)/1e3}function ah(e,t,r,n){return{r:Math.round(e/n),g:Math.round(t/n),b:Math.round(r/n)}}function ag(e){return .2126*e.r+.7152*e.g+.0722*e.b}function ay(e){return`#${aw(e.r)}${aw(e.g)}${aw(e.b)}`}function aw(e){return e.toString(16).padStart(2,"0")}function ab(e){return Math.round(100*e*100)/100}let av=255*Math.sqrt(3);async function aI(e,t,r={}){let n,a,i,o;await ak(e,"Baseline image not found"),await ak(t,"Current screenshot not found");let l=r.outputPath,[c,u]=await Promise.all([h.readFile(e),h.readFile(t)]),d=el(c,"baseline screenshot"),p=el(u,"current screenshot"),m=r.threshold??.1;if(d.width!==p.width||d.height!==p.height){let e=d.width*d.height;return await ax(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:d.width,height:d.height},actual:{width:p.width,height:p.height}}}}let f=d.width*d.height,g=m*av,y=new v({width:d.width,height:d.height}),w=new Uint8Array(f),b=0;for(let e=0,t=0;e<d.data.length;e+=4,t+=1){if(Math.sqrt((d.data[e]-p.data[e])**2+(d.data[e+1]-p.data[e+1])**2+(d.data[e+2]-p.data[e+2])**2)>g){b+=1,w[t]=1;let r=aA(p,e);y.data[e]=aS(r,220,.78),y.data[e+1]=aS(r,0,.78),y.data[e+2]=aS(r,0,.78),y.data[e+3]=255;continue}let r=aA(p,e);y.data[e]=r,y.data[e+1]=r,y.data[e+2]=r,y.data[e+3]=255}let I=b>0?(x=(n=function(e){let{diffMask:t,baseline:r,current:n}=e,{width:a,height:i}=r,o=new Uint8Array(t.length),s=new Int32Array(t.length),l=[];for(let e=0;e<t.length;e+=1){if(1!==t[e]||1===o[e])continue;let c=0,u=0;s[0]=e,u+=1,o[e]=1;let d=e%a,p=Math.floor(e/a),m={minX:d,minY:p,maxX:d,maxY:p,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0};for(;c<u;){let e=s[c];c+=1,function(e,t,r,n,a){let i=t%r,o=Math.floor(t/r),s=4*t;e.minX=Math.min(e.minX,i),e.minY=Math.min(e.minY,o),e.maxX=Math.max(e.maxX,i),e.maxY=Math.max(e.maxY,o),e.differentPixels+=1,e.baselineRed+=n.data[s],e.baselineGreen+=n.data[s+1],e.baselineBlue+=n.data[s+2],e.currentRed+=a.data[s],e.currentGreen+=a.data[s+1],e.currentBlue+=a.data[s+2]}(m,e,a,r,n);let l=e%a,d=Math.floor(e/a);for(let e=-1;e<=1;e+=1){let r=d+e;if(!(r<0)&&!(r>=i))for(let n=-1;n<=1;n+=1){if(0===n&&0===e)continue;let i=l+n;if(i<0||i>=a)continue;let c=r*a+i;1===t[c]&&1!==o[c]&&(o[c]=1,s[u]=c,u+=1)}}}l.push(m)}return l}(k={diffMask:w,baseline:d,current:p,totalPixels:f,differentPixels:b,maxRegions:r.maxRegions})).length<=2e3?function(e){let t=[];for(let a of e.sort((e,t)=>{let r=e.minY-t.minY;return 0!==r?r:e.minX-t.minX})){var r,n;let e=t.find(e=>{var t,r,n;return t=e,r=a,n=12,t.minX-n<=r.maxX&&r.minX-n<=t.maxX&&t.minY-n<=r.maxY&&r.minY-n<=t.maxY});if(!e){t.push({...a});continue}r=e,n=a,r.minX=Math.min(r.minX,n.minX),r.minY=Math.min(r.minY,n.minY),r.maxX=Math.max(r.maxX,n.maxX),r.maxY=Math.max(r.maxY,n.maxY),r.differentPixels+=n.differentPixels,r.baselineRed+=n.baselineRed,r.baselineGreen+=n.baselineGreen,r.baselineBlue+=n.baselineBlue,r.currentRed+=n.currentRed,r.currentGreen+=n.currentGreen,r.currentBlue+=n.currentBlue}return t}(n):n,x.flatMap(e=>{var t,r,n;let a;return(t=e,r=k.baseline.width,n=k.baseline.height,a=t.maxX-t.minX+1,t.maxY-t.minY+1>=Math.max(48,Math.round(.07*n))&&a>=.35*r)?function(e,t,r){var n;let a=function(e,t){let r=[],n=null;for(let a=0;a<e.length;a+=1){if(e[a]<=t){n??=a;continue}null!==n&&(a-n>=6&&r.push([n,a-1]),n=null)}return null!==n&&e.length-n>=6&&r.push([n,e.length-1]),r}((n=function(e,t,r){let n=[];for(let a=e.minY;a<=e.maxY;a+=1){let i=0;for(let n=e.minX;n<=e.maxX;n+=1)1===t[a*r+n]&&(i+=1);n.push(i)}return n}(e,t.diffMask,t.baseline.width)).map((e,t)=>{let r=0,a=0,i=Math.max(0,t-3),o=Math.min(n.length-1,t+3);for(let e=i;e<=o;e+=1)r+=n[e],a+=1;return Math.round(r/a)}),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),i=function(e,t,r){let n=[],a=e.minY;for(let[i,o]of t){let t=e.minY+Math.round((i+o)/2);t-a+1<r||e.maxY-t<r||(n.push([a,t]),a=t+1)}return n.push([a,e.maxY]),n}(e,a,r);if(i.length<=1)return[e];let o=i.map(([r,n])=>(function(e,t,r,n){let a=null;for(let s=t;s<=r;s+=1)for(let t=e.minX;t<=e.maxX;t+=1){var i,o;let e=s*n.baseline.width+t;1===n.diffMask[e]&&function(e,t,r,n,a,i){let o=4*t;e.minX=Math.min(e.minX,r),e.minY=Math.min(e.minY,n),e.maxX=Math.max(e.maxX,r),e.maxY=Math.max(e.maxY,n),e.differentPixels+=1,e.baselineRed+=a.data[o],e.baselineGreen+=a.data[o+1],e.baselineBlue+=a.data[o+2],e.currentRed+=i.data[o],e.currentGreen+=i.data[o+1],e.currentBlue+=i.data[o+2]}(a??={minX:i=t,minY:o=s,maxX:i,maxY:o,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0},e,t,s,n.baseline,n.current)}return a})(e,r,n,t)).filter(e=>null!==e);return o.length>1?o:[e]}(e,k,Math.max(24,Math.round(.03*k.baseline.height))):[e]})).sort((e,t)=>{let r=t.differentPixels-e.differentPixels;if(0!==r)return r;let n=e.minY-t.minY;return 0!==n?n:e.minX-t.minX}).slice(0,Math.max(0,k.maxRegions??8)).map((e,t)=>{var r,n,a,i,o,s,l,c,u,d,p;let m,f,h,g,y,w,b,v,I,x,A,S,D,$,M,P,N;return r=e,n=t+1,a={width:k.baseline.width,height:k.baseline.height,totalPixels:k.totalPixels,differentPixels:k.differentPixels},w={x:r.minX,y:r.minY,width:r.maxX-r.minX+1,height:r.maxY-r.minY+1},b={x:Math.round(r.minX+w.width/2),y:Math.round(r.minY+w.height/2)},v=ah(r.baselineRed,r.baselineGreen,r.baselineBlue,r.differentPixels),I=ah(r.currentRed,r.currentGreen,r.currentBlue,r.differentPixels),x=w.width*w.height,A=ab(r.differentPixels/x),S=Math.round(ag(v)),D=Math.round(ag(I)),$=(i=w,o=a.width,s=a.height,i.width>=.55*o&&i.height>=.12*s?"large-area":i.width>=2.5*i.height?"horizontal-band":i.height>=2.5*i.width?"vertical-band":"compact"),M=(m=x/a.totalPixels)>=.04?"large":m>=.01?"medium":"small",P=(l=v,c=I,f=ag(l),Math.abs(h=ag(c)-f)>=12?h>0?"brighter":"darker":Math.max(Math.abs(c.r-l.r),Math.abs(c.g-l.g),Math.abs(c.b-l.b))>=12?"color-shift":"mixed"),N=(u=b,d=a.width,p=a.height,g=u.x<d/3?"left":u.x>2*d/3?"right":"center",y=u.y<p/3?"top":u.y>2*p/3?"bottom":"middle","center"===g&&"middle"===y?"center":`${y}-${g}`),{index:n,rect:w,normalizedRect:{x:ab(w.x/a.width),y:ab(w.y/a.height),width:ab(w.width/a.width),height:ab(w.height/a.height)},differentPixels:r.differentPixels,shareOfDiffPercentage:ab(r.differentPixels/a.differentPixels),densityPercentage:A,shape:$,size:M,location:N,averageBaselineColorHex:ay(v),averageCurrentColorHex:ay(I),baselineLuminance:S,currentLuminance:D,dominantChange:P}}):[];if(b>0&&l){var k,x,A;for(let e of I)e.rect.width<4||e.rect.height<4||function(e,t){let r=nQ(t.x,0,e.width-1),n=nQ(t.y,0,e.height-1),a=nQ(t.x+t.width-1,0,e.width-1),i=nQ(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let o=r;o<=a;o+=1)nZ(e,o,n+t,nW),nZ(e,o,i-t,nW);for(let o=n;o<=i;o+=1)nZ(e,r+t,o,nW),nZ(e,a-t,o,nW)}}(y,e.rect);await h.mkdir(s.dirname(l),{recursive:!0}),await h.writeFile(l,v.sync.write(y))}else await ax(r.outputPath);let S=b>0?await ar({baselinePath:e,currentPath:t,width:d.width,height:d.height}):void 0,D=S&&(S.matches.length>0||(S.movementClusters?.length??0)>0)?{provider:S.provider,baselineBlocks:S.baselineBlocks,currentBlocks:S.currentBlocks,matches:S.matches,...S.movementClusters?{movementClusters:S.movementClusters}:{}}:void 0,$=b>0&&S?(a=function(e){let t=[];for(let r of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=t.find(e=>{var t,n,a;return t=e,n=r,a=10,t.minX-a<=n.maxX&&n.minX-a<=t.maxX&&t.minY-a<=n.maxY&&n.minY-a<=t.maxY});if(!e){t.push({...r});continue}e.minX=Math.min(e.minX,r.minX),e.minY=Math.min(e.minY,r.minY),e.maxX=Math.max(e.maxX,r.maxX),e.maxY=Math.max(e.maxY,r.maxY),e.differentPixels+=r.differentPixels}return t}(function(e,t,r){let n=new Uint8Array(e.length),a=new Int32Array(e.length),i=[];for(let o=0;o<e.length;o+=1){if(1!==e[o]||1===n[o])continue;let s=0,l=0;a[0]=o,l+=1,n[o]=1;let c=o%t,u=Math.floor(o/t),d={minX:c,minY:u,maxX:c,maxY:u,differentPixels:0};for(;s<l;){let i=a[s];s+=1;let o=i%t,c=Math.floor(i/t);d.minX=Math.min(d.minX,o),d.minY=Math.min(d.minY,c),d.maxX=Math.max(d.maxX,o),d.maxY=Math.max(d.maxY,c),d.differentPixels+=1;for(let i=-1;i<=1;i+=1){let s=c+i;if(!(s<0)&&!(s>=r))for(let r=-1;r<=1;r+=1){if(0===r&&0===i)continue;let c=o+r;if(c<0||c>=t)continue;let u=s*t+c;1===e[u]&&1!==n[u]&&(n[u]=1,a[l]=u,l+=1)}}}i.push(d)}return i}(function(e,t,r,n){let a=new Uint8Array(e);if(!n)return a;for(let e of[...n.baselineBlocksRaw,...n.currentBlocksRaw]){var i;!function(e,t,r,n){let a=at(Math.floor(n.x),0,t-1),i=at(Math.floor(n.y),0,r-1),o=at(Math.ceil(n.x+n.width),0,t),s=at(Math.ceil(n.y+n.height),0,r);for(let r=i;r<s;r+=1)for(let n=a;n<o;n+=1)e[r*t+n]=0}(a,t,r,{x:(i=e.rect).x-8,y:i.y-8,width:i.width+16,height:i.height+16})}return a}((A={diffMask:w,width:d.width,height:d.height,regions:I,ocr:S}).diffMask,A.width,A.height,A.ocr),A.width,A.height)),i=n8(A.ocr?.currentBlocksRaw??[]),o=n8(A.ocr?.baselineBlocksRaw??[]),a.filter(n6).map(e=>{var t,r,n,a,s,l,c,u,d,p,m;let f,h,g,y,w,b,v,I,k,x;return t=e,r=A,n=i,a=o,y=function(e,t){let r,n=0;for(let a of t){let t=function(e,t){let r=Math.max(e.x,t.x),n=Math.max(e.y,t.y),a=Math.min(e.x+e.width,t.x+t.width),i=Math.min(e.y+e.height,t.y+t.height);return a<=r||i<=n?0:(a-r)*(i-n)}(e,a.rect);t<=n||(n=t,r=a)}return r?.index}(g=n7(t),r.regions),w=function(e,t,r){let n=n5(e,t);if(n)return n4(e,n.blocks);let a=n5(e,r);return a?n4(e,a.blocks):void 0}(g,n,a),b=function(e,t,r){if(e.height<=3&&e.width>=.12*r)return"separator";if(!t)return e.width>=.4*r?"background":"unknown";if(e.width>=.4*r)return"background";let n=e.x+e.width/2,a=t.x+t.width/2;return n<a-t.width/2?"leading":n>a+t.width/2?"trailing":e.width>=.35*r?"background":"unknown"}(g,w?.block.rect,r.width),v=(s=g,l=b,c=t.differentPixels,u=r,f=s.width/s.height,h=c/(s.width*s.height),"separator"===l?"separator":"background"===l?"background":"trailing"===l&&f>=1.5&&f<=3.8&&h>=.35?"toggle":"trailing"===l&&s.width<=.06*u.width&&s.height<=.04*u.height?"chevron":"leading"===l&&f>=.55&&f<=1.8?"icon":n3(s,u)?"background":"visual"),I={...y?{regionIndex:y}:{},slot:b,likelyKind:v,rect:g},{...y?{regionIndex:y}:{},slot:b,likelyKind:v,rect:g,...w?{nearestText:w.block.text.trim().replace(/^[^\p{L}\p{N}]+/u,"").replace(/^\p{L}\s+/u,"")}:{},score:(d=I,p=t.differentPixels,m=r,k=n3(d.rect,m)?-35:0,x=20*!!d.regionIndex,n0[d.likelyKind]+n1[d.slot]+x+k+Math.min(20,p/200))}}).filter(e=>e.rect.y>=.08*A.height).filter(n2).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,A.maxDeltas??12)).map((e,t)=>{var r;return r=e,{index:t+1,...r.regionIndex?{regionIndex:r.regionIndex}:{},slot:r.slot,likelyKind:r.likelyKind,rect:r.rect,...r.nearestText?{nearestText:r.nearestText}:{}}})):[],M=f>0?Math.round(b/f*1e4)/100:0;return{...b>0&&l?{diffPath:l}:{},...I.length>0?{regions:I}:{},...D?{ocr:D}:{},...$.length>0?{nonTextDeltas:$}:{},totalPixels:f,differentPixels:b,mismatchPercentage:M,match:0===b}}async function ak(e,t){try{await h.access(e)}catch{throw new ey("INVALID_ARGS",`${t}: ${e}`)}}async function ax(e){if(e)try{await h.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function aA(e,t){return aS(Math.round(.299*e.data[t]+.587*e.data[t+1]+.114*e.data[t+2]),255,.72)}function aS(e,t,r){return Math.round(e*(1-r)+t*r)}function aD(e){return e.width*e.height}function a$(e){return Math.round(100*e*100)/100}let aM=async({positionals:e,flags:t,client:r})=>{let n=await r.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs,...void 0!==t.screenshotFullscreen?{fullscreen:t.screenshotFullscreen}:{}});return nm(t,{path:n.path,...n.overlayRefs?{overlayRefs:n.overlayRefs}:{}},()=>n.overlayRefs?`Annotated ${n.overlayRefs.length} refs onto ${n.path}`:n.path),!0},aP=async({positionals:e,flags:t,client:r})=>{let n;if("snapshot"===e[0]){let e=await r.capture.diff({...np(t),kind:"snapshot",out:t.out,interactiveOnly:t.snapshotInteractiveOnly,compact:t.snapshotCompact,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw});return nm(t,e,()=>(function(e){var t;let r=!0===e.baselineInitialized,n=e.summary??{},a=ti(n.additions),i=ti(n.removals),o=ti(n.unchanged),s=to(),c=tl(e),u=c.length>0?`${c.join("\n")}
42
+ `:"";if(r)return`${u}Baseline initialized (${o} lines).
43
+ `;let d=(function(e){if(0===e.length)return e;let t=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===t.length)return e;let r=Array(e.length).fill(!1);for(let n of t){let t=Math.max(0,n-1),a=Math.min(e.length-1,n+1);for(let e=t;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(e.lines)?e.lines:[]).map(e=>{let t="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=t.startsWith(" ")?`+${t}`:`+ ${t}`;return s?l("green",e):e}if("removed"===e.kind){let e=t.startsWith(" ")?`-${t}`:`- ${t}`;return s?l("red",e):e}return s?l("dim",t):t}),p=d.length>0?`${d.join("\n")}
44
+ `:"";if(!s)return`${u}${p}${a} additions, ${i} removals, ${o} unchanged
45
+ `;let m=`${(t=String(a),l("green",t))} additions, ${l("red",String(i))} removals, ${l("dim",String(o))} unchanged`;return`${u}${p}${m}
46
+ `})(e)),!0}if("screenshot"!==e[0])return!1;let a=t.baseline;if(!a||"string"!=typeof a)throw new ey("INVALID_ARGS","diff screenshot requires --baseline <path>");let i=W(a),o="string"==typeof t.out?W(t.out):void 0,c=e[1];if(e.length>2)throw new ey("INVALID_ARGS","diff screenshot accepts at most one current screenshot path");let u=.1;if(null!=t.threshold&&""!==t.threshold&&(Number.isNaN(u=Number(t.threshold))||u<0||u>1))throw new ey("INVALID_ARGS","--threshold must be a number between 0 and 1");if(c){if(t.overlayRefs)throw new ey("INVALID_ARGS","diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs");let e=await aI(i,W(c),{threshold:u,outputPath:o});return nm(t,e,()=>e9(e)),!0}let d=f.mkdtempSync(s.join(b.tmpdir(),"agent-device-diff-current-")),p=s.join(d,`current-${Date.now()}.png`),m=(await r.capture.screenshot({path:p})).path;try{if(n=await aI(i,m,{threshold:u,outputPath:o}),!t.overlayRefs||n.match||n.dimensionMismatch)t.overlayRefs&&o&&function(e){try{f.unlinkSync(aN(e))}catch(e){var t;if(t=e,"object"!=typeof t||null===t||!("code"in t)||"ENOENT"!==t.code)throw e}}(o);else{var h,g;let e=await r.capture.screenshot({path:o?aN(o):void 0,overlayRefs:!0});n={...n,currentOverlayPath:e.path,...e.overlayRefs?{currentOverlayRefCount:e.overlayRefs.length}:{},...n.regions&&e.overlayRefs?{regions:(h=n.regions,g=e.overlayRefs,h.map(e=>{var t,r;let n,a=(t=e,r=g,n=aD(t.rect),r.map(e=>{var r,a;let i,o,s,l,c=e.overlayRect,u=(r=t.rect,a=c,i=Math.max(r.x,a.x),o=Math.max(r.y,a.y),s=Math.min(r.x+r.width,a.x+a.width),l=Math.min(r.y+r.height,a.y+a.height),s<=i||l<=o?0:(s-i)*(l-o));return u<=0?null:{ref:e.ref,...e.label?{label:e.label}:{},rect:c,overlayCoveragePercentage:a$(u/aD(c)),regionCoveragePercentage:a$(u/n)}}).filter(e=>null!==e).sort((e,t)=>{let r=t.regionCoveragePercentage-e.regionCoveragePercentage;return 0!==r?r:t.overlayCoveragePercentage-e.overlayCoveragePercentage}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage})));return a.length>0?{...e,currentOverlayMatches:a}:e}))}:{}}}}finally{try{f.unlinkSync(m)}catch{}try{f.rmSync(d,{recursive:!0,force:!0})}catch{}}return nm(t,n,()=>e9(n)),!0};function aN(e){let t=s.extname(e),r=t?e.slice(0,-t.length):e;return`${r}.current-overlay${t||".png"}`}function aL(e){return null===e?{}:{timeoutMs:e}}function aR(e){let{suite:t,json:r,verbose:n,reportJunit:a}=e;return(a&&function(e,t){let r=s.dirname(e);try{f.mkdirSync(r,{recursive:!0}),f.writeFileSync(e,function(e){let t=['<?xml version="1.0" encoding="UTF-8"?>',"<testsuites>",` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${aT(e.durationMs)}">`];for(let r of e.tests)t.push(...function(e){let t=aC(s.basename(e.file)),r=aC("."===s.dirname(e.file)?e.file:s.dirname(e.file)),n=aC(e.file),a=aT(e.durationMs),i=[` <testcase classname="${r}" name="${t}" file="${n}" time="${a}">`];"failed"===e.status?i.push(` <failure message="${aC(e.error.message)}">${aC(function(e){let t=[e.error.message];e.error.hint&&t.push(`hint: ${e.error.hint}`),e.error.diagnosticId&&t.push(`diagnosticId: ${e.error.diagnosticId}`),e.error.logPath&&t.push(`logPath: ${e.error.logPath}`),e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`);let r=e.error.details?JSON.stringify(e.error.details,null,2):void 0;return r&&t.push(`details: ${r}`),t.join("\n")}(e))}</failure>`):"skipped"===e.status&&i.push(` <skipped message="${aC(e.message)}" />`);let o=function(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return"attempts"in e&&t.push(`attempts: ${e.attempts}`),"session"in e&&t.push(`session: ${e.session}`),"replayed"in e&&t.push(`replayed: ${e.replayed}`),"healed"in e&&t.push(`healed: ${e.healed}`),"artifactsDir"in e&&e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`),"passed"===e.status&&e.attempts>1&&t.push("flaky: true"),t.join("\n")}(e);return o&&i.push(` <system-out>${aC(o)}</system-out>`),i.push(" </testcase>"),i}(r));return t.push(" </testsuite>"),t.push("</testsuites>"),`${t.join("\n")}
47
+ `}(t),"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new ey("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(a,t),r)?(e6({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let r=e.tests.filter(aE);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return a_(e);let t="passed"===e.status?aE(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",r="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",n=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${r}${n}
47
48
  `),"skipped"===e.status&&process.stdout.write(` ${e.message??"skipped"}
48
- `)}(t);else{for(let t of e.failures)af(t);for(let e of r)!function(e){let t=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FLAKY ${e.file} after ${e.attempts} attempts${t}
49
+ `)}(t);else{for(let t of e.failures)a_(t);for(let e of r)!function(e){let t=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FLAKY ${e.file} after ${e.attempts} attempts${t}
49
50
  `)}(e)}let n="number"==typeof e.durationMs?e.durationMs:void 0,a=r.length>0?`, ${r.length} flaky`:"";return process.stdout.write(`Test summary: ${e.passed} passed, ${e.failed} failed${a}${void 0!==n?` in ${n}ms`:""}
50
- `),function(e){return+(e.failed>0)}(e)}(t,{verbose:n})}function af(e){let t=e.attempts>1?` after ${e.attempts} attempts`:"",r=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FAIL ${e.file}${t}${r}
51
+ `),function(e){return+(e.failed>0)}(e)}(t,{verbose:n})}function a_(e){let t=e.attempts>1?` after ${e.attempts} attempts`:"",r=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FAIL ${e.file}${t}${r}
51
52
  `),process.stdout.write(` ${e.error?.message??"Unknown test failure"}
52
53
  `),e.error?.hint&&process.stdout.write(` hint: ${e.error.hint}
53
54
  `),e.artifactsDir&&process.stdout.write(` artifacts: ${e.artifactsDir}
54
55
  `),e.error?.logPath&&process.stdout.write(` log: ${e.error.logPath}
55
56
  `),e.error?.diagnosticId&&process.stdout.write(` diagnostic: ${e.error.diagnosticId}
56
- `)}function ah(e){return"passed"===e.status&&e.attempts>1}function ag(e){return(Math.max(0,e)/1e3).toFixed(3)}function ay(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}let aw={[ry]:ab(ry,({client:e,flags:t})=>e.devices.boot({...nm(t),headless:t.headless})),[rR]:ab(rR,({client:e,positionals:t,flags:r})=>e.apps.push({...nm(r),app:aI(t[0],"push requires bundleOrPackage"),payload:aI(t[1],"push requires payloadOrJson")})),[rN]:ab(rN,({client:e,flags:t})=>e.observability.perf(nm(t))),[rw]:ab(rw,({client:e,positionals:t,flags:r})=>e.interactions.click({...ax(t),...av(r),...nm(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap,button:r.clickButton})),get:ab("get",({client:e,positionals:t,flags:r})=>e.interactions.get({...function(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=e.join(" ").trim();if(!t)throw new eg("INVALID_ARGS","get requires @ref or selector expression");return{selector:t}}(t.slice(1)),...av(r),...nm(r),format:function(e){if("text"===e||"attrs"===e)return e;throw new eg("INVALID_ARGS","get only supports text or attrs")}(t[0])})),[rT]:ab(rT,({client:e,positionals:t,flags:r})=>e.replay.run({...nm(r),path:aI(t[0],"replay requires path"),update:r.replayUpdate})),[rB]:ab(rB,({client:e,positionals:t,flags:r})=>(({json:r.json}).json||process.stderr.write("Running replay suite...\n"),e.replay.test({...nm(r),paths:t,update:r.replayUpdate,failFast:r.failFast,timeoutMs:r.timeoutMs,retries:r.retries,artifactsDir:r.artifactsDir,reportJunit:r.reportJunit}))),[rg]:ab(rg,({client:e,flags:t})=>e.batch.run({...nm(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out})),[rE]:ab(rE,({client:e,positionals:t,flags:r})=>e.interactions.press({...ax(t),...av(r),...nm(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap})),[rM]:ab(rM,({client:e,positionals:t,flags:r})=>e.interactions.longPress({...nm(r),x:Number(t[0]),y:Number(t[1]),durationMs:aA(t[2])})),[rV]:ab(rV,({client:e,positionals:t,flags:r})=>e.interactions.swipe({...nm(r),from:{x:Number(t[0]),y:Number(t[1])},to:{x:Number(t[2]),y:Number(t[3])},durationMs:aA(t[4]),count:r.count,pauseMs:r.pauseMs,pattern:r.pattern})),[rA]:ab(rA,({client:e,positionals:t,flags:r})=>e.interactions.focus({...nm(r),x:Number(t[0]),y:Number(t[1])})),[rX]:ab(rX,({client:e,positionals:t,flags:r})=>e.interactions.type({...nm(r),text:t.join(" "),delayMs:r.delayMs})),[rk]:ab(rk,({client:e,positionals:t,flags:r})=>e.interactions.fill({...function(e){if(e[0]?.startsWith("@")){let t=e.length>=3?e.slice(2).join(" "):e.slice(1).join(" ");return{ref:e[0],label:e.length>=3?e[1]:void 0,text:t}}let t=R(e,{preferTrailingValue:!0});return t?{selector:t.selectorExpression,text:t.rest.join(" ")}:{x:Number(e[0]),y:Number(e[1]),text:e.slice(2).join(" ")}}(t),...av(r),...nm(r),delayMs:r.delayMs})),[rC]:ab(rC,({client:e,positionals:t,flags:r})=>e.interactions.scroll({...nm(r),direction:function(e){if("up"===e||"down"===e||"left"===e||"right"===e)return e;throw new eg("INVALID_ARGS",`Unknown direction: ${String(e)}`)}(t[0]),amount:aA(t[1]),pixels:r.pixels})),[rL]:ab(rL,({client:e,positionals:t,flags:r})=>e.interactions.pinch({...nm(r),scale:Number(t[0]),x:aA(t[1]),y:aA(t[2])})),[rq]:ab(rq,({client:e,positionals:t,flags:r})=>e.apps.triggerEvent({...nm(r),event:aI(t[0],"trigger-app-event requires event"),payload:t[1]?function(e,t){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}throw new eg("INVALID_ARGS",`${t} must be a JSON object`)}(t[1],"trigger-app-event payload"):void 0})),[r_]:ab(r_,({client:e,positionals:t,flags:r})=>e.recording.record({...nm(r),action:ak(t[0],"record"),path:t[1],fps:r.fps,hideTouches:r.hideTouches})),[rG]:ab(rG,({client:e,positionals:t,flags:r})=>e.recording.trace({...nm(r),action:ak(t[0],"trace"),path:t[1]})),[r$]:ab(r$,({client:e,positionals:t,flags:r})=>e.observability.logs({...nm(r),action:function(e){if(void 0!==e){if("path"===e||"start"===e||"stop"===e||"doctor"===e||"mark"===e||"clear"===e)return e;throw new eg("INVALID_ARGS","logs requires path, start, stop, doctor, mark, or clear")}}(t[0]),message:t.slice(1).join(" ")||void 0,restart:r.restart})),[rP]:ab(rP,({client:e,positionals:t,flags:r})=>e.observability.network({...nm(r),action:function(e){if(void 0!==e){if("dump"===e||"log"===e)return e;throw new eg("INVALID_ARGS","network requires dump or log")}}(t[0]),limit:aA(t[1]),include:r.networkInclude??function(e){if(void 0!==e){if("summary"===e||"headers"===e||"body"===e||"all"===e)return e;throw new eg("INVALID_ARGS","network include mode must be summary, headers, body, or all")}}(t[2])})),[rI]:ab(rI,({client:e,positionals:t,flags:r})=>{var n;return e.interactions.find({...function(e){let t=function(e){if("text"===e||"label"===e||"value"===e||"role"===e||"id"===e)return e}(e[0]),r=void 0!==t,n=r?e[1]:e[0],a=r?2:1,i=e[a];if(void 0===i)return{locator:t,query:aI(n,"find requires query")};if("get"===i){let r=e[a+1];if("text"===r)return{locator:t,query:aI(n,"find requires query"),action:"getText"};if("attrs"===r)return{locator:t,query:aI(n,"find requires query"),action:"getAttrs"};throw new eg("INVALID_ARGS","find get only supports text or attrs")}if("wait"===i)return{locator:t,query:aI(n,"find requires query"),action:"wait",timeoutMs:aA(e[a+1])};if("fill"===i||"type"===i)return{locator:t,query:aI(n,"find requires query"),action:i,value:e.slice(a+1).join(" ")};if("click"===i||"focus"===i||"exists"===i)return{locator:t,query:aI(n,"find requires query"),action:i};throw new eg("INVALID_ARGS",`Unsupported find action: ${i}`)}(t),...{depth:(n=r).snapshotDepth,raw:n.snapshotRaw},...nm(r),first:r.findFirst,last:r.findLast})}),is:ab("is",({client:e,positionals:t,flags:r})=>e.interactions.is({...function(e){let t=e[0],r=R(e.slice(1),{preferTrailingValue:"text"===t});if(!r)throw new eg("INVALID_ARGS","is requires a selector expression");if("text"===t)return{predicate:t,selector:r.selectorExpression,value:r.rest.join(" ")};if("visible"===t||"hidden"===t||"exists"===t||"editable"===t||"selected"===t)return{predicate:t,selector:r.selectorExpression};throw new eg("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text")}(t),...av(r),...nm(r)})),[rF]:ab(rF,({client:e,positionals:t,flags:r})=>e.settings.update(function(e,t){let r=nm(t),n=e[0],a=e[1];if(("wifi"===n||"airplane"===n||"location"===n)&&("on"===a||"off"===a)||"appearance"===n&&("light"===a||"dark"===a||"toggle"===a)||("faceid"===n||"touchid"===n)&&("match"===a||"nonmatch"===a||"enroll"===a||"unenroll"===a)||"fingerprint"===n&&("match"===a||"nonmatch"===a))return{...r,setting:n,state:a};if("permission"===n&&("grant"===a||"deny"===a||"reset"===a))return{...r,setting:n,state:a,permission:function(e){switch(e){case"camera":case"microphone":case"photos":case"contacts":case"contacts-limited":case"notifications":case"calendar":case"location":case"location-always":case"media-library":case"motion":case"reminders":case"siri":case"accessibility":case"screen-recording":case"input-monitoring":return e;default:throw new eg("INVALID_ARGS","settings permission requires a permission target.")}}(e[2]),mode:function(e){if(void 0===e||"full"===e||"limited"===e)return e;throw new eg("INVALID_ARGS","settings permission mode must be full or limited.")}(e[3])};throw new eg("INVALID_ARGS","Invalid settings arguments.")}(t,r)))};function ab(e,t){return async({positionals:r,flags:n,client:a})=>{let i=await t({client:a,positionals:r,flags:n}),o=function(e,t,r,n){if(r.json)return e===rB?am({suite:n,json:!0,reportJunit:r.reportJunit}):(e3({success:!0,data:n}),0);if(e===rB)return am({suite:n,verbose:r.verbose,reportJunit:r.reportJunit});if(e===rg)return!function(e){let t="number"==typeof e.total?e.total:0,r="number"==typeof e.executed?e.executed:0,n="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let i of(process.stdout.write(`Batch completed: ${r}/${t} steps${void 0!==n?` in ${n}ms`:""}
57
- `),Array.isArray(e.results)?e.results:[])){var a;if(!i||"object"!=typeof i)continue;let e="number"==typeof i.step?i.step:void 0,t="string"==typeof i.command?i.command:"step",r=!1!==i.ok,n="number"==typeof i.durationMs?i.durationMs:void 0,o=i.data&&"object"==typeof i.data?i.data:void 0,s=i.error&&"object"==typeof i.error?i.error:void 0,l=r?U(o)??t:(a=s,("string"==typeof a?.message&&a.message.length>0?a.message:null)??t),u=void 0!==e?`${e}. `:"- ",c=void 0!==n?` (${n}ms)`:"";process.stdout.write(`${u}${r?"OK":"FAILED"} ${l}${c}
57
+ `)}function aE(e){return"passed"===e.status&&e.attempts>1}function aT(e){return(Math.max(0,e)/1e3).toFixed(3)}function aC(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}let aO={[rA]:aU(rA,({client:e,flags:t})=>e.devices.boot({...np(t),headless:t.headless})),[rj]:aU(rj,({client:e,positionals:t,flags:r})=>e.apps.push({...np(r),app:aV(t[0],"push requires bundleOrPackage"),payload:aV(t[1],"push requires payloadOrJson")})),[rO]:aU(rO,({client:e,flags:t})=>e.observability.perf(np(t))),[rS]:aU(rS,({client:e,positionals:t,flags:r})=>e.interactions.click({...aj(t),...aF(r),...np(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap,button:r.clickButton})),get:aU("get",({client:e,positionals:t,flags:r})=>e.interactions.get({...function(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=e.join(" ").trim();if(!t)throw new ey("INVALID_ARGS","get requires @ref or selector expression");return{selector:t}}(t.slice(1)),...aF(r),...np(r),format:function(e){if("text"===e||"attrs"===e)return e;throw new ey("INVALID_ARGS","get only supports text or attrs")}(t[0])})),[rV]:aU(rV,({client:e,positionals:t,flags:r})=>e.replay.run({...np(r),path:aV(t[0],"replay requires path"),update:r.replayUpdate})),[rJ]:aU(rJ,({client:e,positionals:t,flags:r})=>(({json:r.json}).json||process.stderr.write("Running replay suite...\n"),e.replay.test({...np(r),paths:t,update:r.replayUpdate,failFast:r.failFast,timeoutMs:r.timeoutMs,retries:r.retries,artifactsDir:r.artifactsDir,reportJunit:r.reportJunit}))),[rx]:aU(rx,({client:e,flags:t})=>e.batch.run({...np(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out})),[rF]:aU(rF,({client:e,positionals:t,flags:r})=>e.interactions.press({...aj(t),...aF(r),...np(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap})),[rT]:aU(rT,({client:e,positionals:t,flags:r})=>e.interactions.longPress({...np(r),x:Number(t[0]),y:Number(t[1]),durationMs:aG(t[2])})),[rY]:aU(rY,({client:e,positionals:t,flags:r})=>e.interactions.swipe({...np(r),from:{x:Number(t[0]),y:Number(t[1])},to:{x:Number(t[2]),y:Number(t[3])},durationMs:aG(t[4]),count:r.count,pauseMs:r.pauseMs,pattern:r.pattern})),[rL]:aU(rL,({client:e,positionals:t,flags:r})=>e.interactions.focus({...np(r),x:Number(t[0]),y:Number(t[1])})),[rZ]:aU(rZ,({client:e,positionals:t,flags:r})=>e.interactions.type({...np(r),text:t.join(" "),delayMs:r.delayMs})),[rP]:aU(rP,({client:e,positionals:t,flags:r})=>e.interactions.fill({...function(e){if(e[0]?.startsWith("@")){let t=e.length>=3?e.slice(2).join(" "):e.slice(1).join(" ");return{ref:e[0],label:e.length>=3?e[1]:void 0,text:t}}let t=E(e,{preferTrailingValue:!0});return t?{selector:t.selectorExpression,text:t.rest.join(" ")}:{x:Number(e[0]),y:Number(e[1]),text:e.slice(2).join(" ")}}(t),...aF(r),...np(r),delayMs:r.delayMs})),[rq]:aU(rq,({client:e,positionals:t,flags:r})=>e.interactions.scroll({...np(r),direction:function(e){if("up"===e||"down"===e||"left"===e||"right"===e)return e;throw new ey("INVALID_ARGS",`Unknown direction: ${String(e)}`)}(t[0]),amount:aG(t[1]),pixels:r.pixels})),[rU]:aU(rU,({client:e,positionals:t,flags:r})=>e.interactions.pinch({...np(r),scale:Number(t[0]),x:aG(t[1]),y:aG(t[2])})),[rW]:aU(rW,({client:e,positionals:t,flags:r})=>e.apps.triggerEvent({...np(r),event:aV(t[0],"trigger-app-event requires event"),payload:t[1]?function(e,t){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}throw new ey("INVALID_ARGS",`${t} must be a JSON object`)}(t[1],"trigger-app-event payload"):void 0})),[rB]:aU(rB,({client:e,positionals:t,flags:r})=>e.recording.record({...np(r),action:aB(t[0],"record"),path:t[1],fps:r.fps,hideTouches:r.hideTouches})),[rz]:aU(rz,({client:e,positionals:t,flags:r})=>e.recording.trace({...np(r),action:aB(t[0],"trace"),path:t[1]})),[rE]:aU(rE,({client:e,positionals:t,flags:r})=>e.observability.logs({...np(r),action:function(e){if(void 0!==e){if("path"===e||"start"===e||"stop"===e||"doctor"===e||"mark"===e||"clear"===e)return e;throw new ey("INVALID_ARGS","logs requires path, start, stop, doctor, mark, or clear")}}(t[0]),message:t.slice(1).join(" ")||void 0,restart:r.restart})),[rC]:aU(rC,({client:e,positionals:t,flags:r})=>e.observability.network({...np(r),action:function(e){if(void 0!==e){if("dump"===e||"log"===e)return e;throw new ey("INVALID_ARGS","network requires dump or log")}}(t[0]),limit:aG(t[1]),include:r.networkInclude??function(e){if(void 0!==e){if("summary"===e||"headers"===e||"body"===e||"all"===e)return e;throw new ey("INVALID_ARGS","network include mode must be summary, headers, body, or all")}}(t[2])})),[rN]:aU(rN,({client:e,positionals:t,flags:r})=>{var n;return e.interactions.find({...function(e){let t=function(e){if("text"===e||"label"===e||"value"===e||"role"===e||"id"===e)return e}(e[0]),r=void 0!==t,n=r?e[1]:e[0],a=r?2:1,i=e[a];if(void 0===i)return{locator:t,query:aV(n,"find requires query")};if("get"===i){let r=e[a+1];if("text"===r)return{locator:t,query:aV(n,"find requires query"),action:"getText"};if("attrs"===r)return{locator:t,query:aV(n,"find requires query"),action:"getAttrs"};throw new ey("INVALID_ARGS","find get only supports text or attrs")}if("wait"===i)return{locator:t,query:aV(n,"find requires query"),action:"wait",timeoutMs:aG(e[a+1])};if("fill"===i||"type"===i)return{locator:t,query:aV(n,"find requires query"),action:i,value:e.slice(a+1).join(" ")};if("click"===i||"focus"===i||"exists"===i)return{locator:t,query:aV(n,"find requires query"),action:i};throw new ey("INVALID_ARGS",`Unsupported find action: ${i}`)}(t),...{depth:(n=r).snapshotDepth,raw:n.snapshotRaw},...np(r),first:r.findFirst,last:r.findLast})}),is:aU("is",({client:e,positionals:t,flags:r})=>e.interactions.is({...function(e){let t=e[0],r=E(e.slice(1),{preferTrailingValue:"text"===t});if(!r)throw new ey("INVALID_ARGS","is requires a selector expression");if("text"===t)return{predicate:t,selector:r.selectorExpression,value:r.rest.join(" ")};if("visible"===t||"hidden"===t||"exists"===t||"editable"===t||"selected"===t)return{predicate:t,selector:r.selectorExpression};throw new ey("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text")}(t),...aF(r),...np(r)})),[rK]:aU(rK,({client:e,positionals:t,flags:r})=>e.settings.update(function(e,t){let r=np(t),n=e[0],a=e[1];if(("wifi"===n||"airplane"===n||"location"===n)&&("on"===a||"off"===a)||"appearance"===n&&("light"===a||"dark"===a||"toggle"===a)||("faceid"===n||"touchid"===n)&&("match"===a||"nonmatch"===a||"enroll"===a||"unenroll"===a)||"fingerprint"===n&&("match"===a||"nonmatch"===a))return{...r,setting:n,state:a};if("permission"===n&&("grant"===a||"deny"===a||"reset"===a))return{...r,setting:n,state:a,permission:function(e){switch(e){case"camera":case"microphone":case"photos":case"contacts":case"contacts-limited":case"notifications":case"calendar":case"location":case"location-always":case"media-library":case"motion":case"reminders":case"siri":case"accessibility":case"screen-recording":case"input-monitoring":return e;default:throw new ey("INVALID_ARGS","settings permission requires a permission target.")}}(e[2]),mode:function(e){if(void 0===e||"full"===e||"limited"===e)return e;throw new ey("INVALID_ARGS","settings permission mode must be full or limited.")}(e[3])};throw new ey("INVALID_ARGS","Invalid settings arguments.")}(t,r)))};function aU(e,t){return async({positionals:r,flags:n,client:a})=>{let i=await t({client:a,positionals:r,flags:n}),o=function(e,t,r,n){if(r.json)return e===rJ?aR({suite:n,json:!0,reportJunit:r.reportJunit}):(e6({success:!0,data:n}),0);if(e===rJ)return aR({suite:n,verbose:r.verbose,reportJunit:r.reportJunit});if(e===rx)return!function(e){let t="number"==typeof e.total?e.total:0,r="number"==typeof e.executed?e.executed:0,n="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let i of(process.stdout.write(`Batch completed: ${r}/${t} steps${void 0!==n?` in ${n}ms`:""}
58
+ `),Array.isArray(e.results)?e.results:[])){var a;if(!i||"object"!=typeof i)continue;let e="number"==typeof i.step?i.step:void 0,t="string"==typeof i.command?i.command:"step",r=!1!==i.ok,n="number"==typeof i.durationMs?i.durationMs:void 0,o=i.data&&"object"==typeof i.data?i.data:void 0,s=i.error&&"object"==typeof i.error?i.error:void 0,l=r?F(o)??t:(a=s,("string"==typeof a?.message&&a.message.length>0?a.message:null)??t),c=void 0!==e?`${e}. `:"- ",u=void 0!==n?` (${n}ms)`:"";process.stdout.write(`${c}${r?"OK":"FAILED"} ${l}${u}
58
59
  `)}}(n),0;if("get"===e){let e=t[0];if("text"===e)return process.stdout.write(`${"string"==typeof n.text?n.text:""}
59
60
  `),0;if("attrs"===e)return process.stdout.write(`${JSON.stringify(n.node??{},null,2)}
60
- `),0}if(e===rI){if("string"==typeof n.text)return process.stdout.write(`${n.text}
61
+ `),0}if(e===rN){if("string"==typeof n.text)return process.stdout.write(`${n.text}
61
62
  `),0;if("boolean"==typeof n.found)return process.stdout.write(`Found: ${n.found}
62
63
  `),0;if(n.node)return process.stdout.write(`${JSON.stringify(n.node,null,2)}
63
64
  `),0}if("is"===e)return process.stdout.write(`Passed: is ${n.predicate??"assertion"}
64
- `),0;if(e===ry){let e=n.platform??"unknown",t=n.device??n.id??"unknown";return process.stdout.write(`Boot ready: ${t} (${e})
65
- `),0}if(e===r_){let e="string"==typeof n.outPath?n.outPath:"";return e&&process.stdout.write(`${e}
66
- `),0}if(e===r$)return function(e,t){let r="string"==typeof e.path?e.path:"";if(!r)return;process.stdout.write(`${r}
65
+ `),0;if(e===rA){let e=n.platform??"unknown",t=n.device??n.id??"unknown";return process.stdout.write(`Boot ready: ${t} (${e})
66
+ `),0}if(e===rB){let e="string"==typeof n.outPath?n.outPath:"";return e&&process.stdout.write(`${e}
67
+ `),0}if(e===rE)return function(e,t){let r="string"==typeof e.path?e.path:"";if(!r)return;process.stdout.write(`${r}
67
68
  `);let n=["active","state","backend","sizeBytes"].map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ");n&&!t.json&&process.stderr.write(`${n}
68
69
  `);let a=["started","stopped","marked","cleared","restarted","removedRotatedFiles"].map(t=>{let r=e[t];return!0===r?`${t}=true`:"number"==typeof r?`${t}=${r}`:""}).filter(Boolean).join(" ");if(a&&!t.json&&process.stderr.write(`${a}
69
70
  `),e.hint&&!t.json&&process.stderr.write(`${e.hint}
70
71
  `),Array.isArray(e.notes)&&!t.json)for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
71
- `)}(n,r),0;if(e===rP)return function(e){let t="string"==typeof e.path?e.path:"";t&&process.stdout.write(`${t}
72
+ `)}(n,r),0;if(e===rC)return function(e){let t="string"==typeof e.path?e.path:"";t&&process.stdout.write(`${t}
72
73
  `);let r=Array.isArray(e.entries)?e.entries:[];if(0===r.length)process.stdout.write("No recent HTTP(s) entries found.\n");else for(let e of r){let t="string"==typeof e.method?e.method:"HTTP",r="string"==typeof e.url?e.url:"<unknown-url>",n="number"==typeof e.status?` status=${e.status}`:"",a="string"==typeof e.timestamp?`${e.timestamp} `:"",i="number"==typeof e.durationMs?` durationMs=${e.durationMs}`:"";process.stdout.write(`${a}${t} ${r}${n}${i}
73
74
  `),"string"==typeof e.headers&&process.stdout.write(` headers: ${e.headers}
74
75
  `),"string"==typeof e.requestBody&&process.stdout.write(` request: ${e.requestBody}
75
76
  `),"string"==typeof e.responseBody&&process.stdout.write(` response: ${e.responseBody}
76
77
  `)}let n=["active","state","backend","include","scannedLines","matchedLines"].map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ");if(n&&process.stderr.write(`${n}
77
78
  `),Array.isArray(e.notes))for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
78
- `)}(n),0;if(e===rw||e===rE){let e=n.ref??"",t=n.x,r=n.y;if(e&&"number"==typeof t&&"number"==typeof r)return process.stdout.write(`Tapped @${e} (${t}, ${r})
79
- `),0}if(e===rN)return process.stdout.write(`${JSON.stringify(n,null,2)}
80
- `),0;let a=U(n);return a&&process.stdout.write(`${a}
81
- `),0}(e,r,n,i);return 0!==o&&process.exit(o),!0}}function av(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function ax(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=R(e);return t?{selector:t.selectorExpression}:{x:Number(e[0]),y:Number(e[1])}}function ak(e,t){if("start"===e||"stop"===e)return e;throw new eg("INVALID_ARGS",`${t} requires start|stop`)}function aI(e,t){if(void 0===e||""===e)throw new eg("INVALID_ARGS",t);return e}function aA(e){return void 0===e?void 0:Number(e)}let aD={...{session:ng,[rv]:ny,[rf]:nx,"ensure-simulator":nb,metro:nv,install:nk,reinstall:nI,"install-from-source":nA,open:nP,close:nN,[rj]:nL,[rU]:au,[rx]:ac},...{[rY]:async({positionals:e,flags:t,client:r})=>(nh(t,await r.command.wait(function(e,t){let r=T(e);if(!r)throw new eg("INVALID_ARGS","wait requires <ms>, text <text>, @ref, or <selector> [timeoutMs].");let n={...nm(t),depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw};if("sleep"===r.kind)return{...n,durationMs:r.durationMs};if("text"===r.kind){if(!r.text)throw new eg("INVALID_ARGS","wait requires text.");return{...n,text:r.text,...ad(r.timeoutMs)}}return"ref"===r.kind?{...n,ref:r.rawRef,...ad(r.timeoutMs)}:{...n,selector:r.selectorExpression,...ad(r.timeoutMs)}}(e,t))),!0),[rp]:async({positionals:e,flags:t,client:r})=>(nh(t,await r.command.alert(function(e,t){if(e.length>2)throw new eg("INVALID_ARGS","alert accepts at most action and timeout arguments.");let r=function(e){let t=e?.toLowerCase();if(void 0===t||"get"===t||"accept"===t||"dismiss"===t||"wait"===t)return t;throw new eg("INVALID_ARGS","alert action must be get, accept, dismiss, or wait.")}(e[0]),n=function(e,t){if(void 0===e)return;let r=Number(e);if(Number.isFinite(r))return r;throw new eg("INVALID_ARGS",`${t} must be a finite number.`)}(e[1],"alert timeout");return{...nm(t),...r?{action:r}:{},...void 0!==n?{timeoutMs:n}:{}}}(e,t))),!0),[rd]:async({flags:e,client:t})=>{let r=await t.command.appState(nm(e));return nf(e,r,()=>(function(e){if("ios"===e.platform){let t=[`Foreground app: ${e.appName??e.appBundleId??"unknown"}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.source&&t.push(`Source: ${e.source}`),t.join("\n")}if("android"===e.platform){let t=[`Foreground app: ${e.package??"unknown"}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join("\n")}return null})(r)),!0},[rh]:async({flags:e,client:t})=>(nh(e,await t.command.back({...nm(e),mode:e.backMode})),!0),[rD]:async({flags:e,client:t})=>(nh(e,await t.command.home(nm(e))),!0),[rO]:async({positionals:e,flags:t,client:r})=>(nh(t,await r.command.rotate(function(e,t){if(e.length>1)throw new eg("INVALID_ARGS","rotate accepts exactly one orientation argument.");return{...nm(t),orientation:v(e[0])}}(e,t))),!0),[rm]:async({flags:e,client:t})=>(nh(e,await t.command.appSwitcher(nm(e))),!0),[rS]:async({positionals:e,flags:t,client:r})=>(nh(t,await r.command.keyboard(function(e,t){if(e.length>1)throw new eg("INVALID_ARGS","keyboard accepts at most one action argument.");let r=function(e){let t=e?.toLowerCase();if("get"===t)return"status";if(void 0===t||"status"===t||"dismiss"===t)return t;throw new eg("INVALID_ARGS","keyboard action must be status, get, or dismiss.")}(e[0]);return{...nm(t),...r?{action:r}:{}}}(e,t))),!0),[rb]:async({positionals:e,flags:t,client:r})=>{var n,a;return n=t,a=await r.command.clipboard(function(e,t){let r=e[0]?.toLowerCase();if("read"!==r&&"write"!==r)throw new eg("INVALID_ARGS","clipboard requires a subcommand: read or write.");let n=nm(t);if("read"===r){if(1!==e.length)throw new eg("INVALID_ARGS","clipboard read does not accept additional arguments.");return{...n,action:r}}if(e.length<2)throw new eg("INVALID_ARGS","clipboard write requires text.");return{...n,action:r,text:e.slice(1).join(" ")}}(e,t)),n.json?nf(n,a):"read"===a.action?process.stdout.write(`${a.text}
82
- `):nh(n,a),!0}},...aw};async function aS(e){let t=aD[e.command];return!!t&&await t(e)}function a$(e,t={}){let r=aM(t),n={...e};return r.defaultPlatform&&void 0===n.platform&&(n.platform=r.defaultPlatform),n}function aM(e){var t,r,n,a;let i,o=e.env??process.env,s=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new eg("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(o.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??o.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:s,lockPolicy:(r=e.policyOverrides,n=o,a=l,(i=r?.sessionLock??r?.sessionLockConflicts??aP(n.AGENT_DEVICE_SESSION_LOCK)??aP(n.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||P(n.AGENT_DEVICE_SESSION_LOCKED)||a?"reject":void 0))}}function aP(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new eg("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let aN={sendToDaemon:tm};async function aL(e,t=aN){let r=G(),n=X(),a=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),i=e.includes("--json"),o=function(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(r.startsWith("--session=")){let e=r.slice(10).trim();return e.length>0?e:null}if("--session"===r){let r=e[t+1]?.trim();if(r&&!r.startsWith("-"))return r;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await er({session:o,requestId:r,command:e[0],debug:a},async()=>{var o,l,u,c,p,d,m,h,g,y;let w;try{let t,r,n,a,i,y,b,v,x;o={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,n=[],a=[],i=!0;for(let o=0;o<e.length;o+=1){let s=e[o];if(i&&"--"===s){i=!1;continue}if(!i){r?n.push(s):r=e2(s);continue}let l=s.startsWith("--"),u=s.startsWith("-")&&s.length>1;if(!l&&!u){r?n.push(s):r=e2(s);continue}let[c,p]=l?eQ(s):[s,void 0],d=eE.get(c);if(!d){if(function(e,t,r){var n;if(n=r,!/^-\d+(\.\d+)?$/.test(n)||!e)return!1;let a=e_(e);return!a||!!a.allowsExtraPositionals||0!==a.positionalArgs.length&&(t.length<a.positionalArgs.length||a.positionalArgs.some(e=>e.includes("?")))}(r,n,s)){r?n.push(s):r=s;continue}throw new eg("INVALID_ARGS",`Unknown flag: ${c}`)}let m=function(e,t,r,n){if(void 0!==e.setValue){if(void 0!==r)throw new eg("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==r)throw new eg("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==r){if(0===r.trim().length)throw new eg("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:r,consumeNext:!1}}return void 0===n||e1(n)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(n)?{value:!0,consumeNext:!1}:{value:n,consumeNext:!0}}let a=r??n;if(void 0===a||void 0===r&&e1(a))throw new eg("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:a,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(a))throw new eg("INVALID_ARGS",`Invalid ${e0(t)}: ${a}`);return{value:a,consumeNext:void 0===r}}let i=Number(a);if(!Number.isFinite(i)||"number"==typeof e.min&&i<e.min||"number"==typeof e.max&&i>e.max)throw new eg("INVALID_ARGS",`Invalid ${e0(t)}: ${a}`);return{value:Math.floor(i),consumeNext:void 0===r}}(d,c,p,e[o+1]);m.consumeNext&&(o+=1);let f=t[d.key];if(d.multiple){let e=Array.isArray(f)?[...f,m.value]:void 0===f?[m.value]:[f,m.value];t[d.key]=e}else t[d.key]=m.value;a.push({key:d.key,token:c})}return{command:r,positionals:n,flags:t,warnings:[],providedFlags:a}}(e),r=o?.env??process.env,n=o?.cwd??process.cwd(),a=rQ({remoteConfig:t.flags.remoteConfig,cwd:n,env:r}),b=eS((i=(l={command:t.command,cwd:n,cliFlags:t.flags,env:r}).env??process.env,y=eS({},function(e){let t={};for(let r of e)eS(t,function(e,t){let r,n;if(!f.existsSync(e)){if(t)throw new eg("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{r=f.readFileSync(e,"utf8")}catch(t){throw new eg("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{n=JSON.parse(r)}catch(t){throw new eg("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!n||"object"!=typeof n||Array.isArray(n))throw new eg("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[n,a]of Object.entries(e)){let e=ez.get(n);if(!e)throw new eg("INVALID_ARGS",`Unknown config key "${n}" in ${t}.`);if(!e.config.enabled)throw new eg("INVALID_ARGS",`Unsupported config key "${n}" in ${t}.`);r[n]=eX(eZ(e),a,t,n)}return r}(n,`config file ${e}`)}(r.path,r.required));return t}((u=l.cwd,c=l.cliFlags.config,p=i,(x=c??p.AGENT_DEVICE_CONFIG)?[{path:(d=x,m=u,h=p,z(d,{cwd:m,env:h})),required:!0}]:[{path:(g=p,s.join(O("~",{env:g}),".agent-device","config.json")),required:!1},{path:s.resolve(u,"agent-device.json"),required:!1}]))),eS(y,function(e,t){var r,n,a;let i={};for(let o of eK.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=o.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(i[o.key]=(r=t.value,n=`environment variable ${t.name}`,a=t.name,eX(eZ(o),r,n,a)))}return i}(i,l.command))),a),v=function(e,t){let r=t?.strictFlags??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),n=[...e.warnings],a=eS({json:!1,help:!1,version:!1},t?.defaultFlags??{});eS(a,e.flags);let i=e_(e.command),o=e.providedFlags.filter(t=>!eW(t.key,e.command));if(o.length>0){var s,l;let t=o.map(e=>e.token),i=(s=e.command,l=t,s?1===l.length?`Flag ${l[0]} is not supported for command ${s}.`:`Flags ${l.join(", ")} are not supported for command ${s}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(r)throw new eg("INVALID_ARGS",i);for(let e of(n.push(`${i} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),o))delete a[e.key]}for(let t of Object.keys(a))void 0!==a[t]&&(eW(t,e.command)||delete a[t]);if(function(e){if("back"===e.command&&!(new Set(e.providedFlags.filter(e=>"backMode"===e.key).map(e=>e.token)).size<=1))throw new eg("INVALID_ARGS","back accepts only one explicit mode flag: use either --in-app or --system.")}(e),i?.defaults)for(let[e,t]of Object.entries(i.defaults))void 0===a[e]&&(a[e]=t);if("batch"===e.command&&1!=+!!a.steps+ +!!a.stepsFile)throw new eg("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return function(e){if(e.flags.help)return e;if("snapshot"===e.command&&e.flags.snapshotDiff){let{snapshotDiff:t,...r}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:r,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:a,warnings:n})}(t,{strictFlags:o?.strictFlags,defaultFlags:b}),"open"===t.command&&t.flags.remoteConfig&&function(e,t){for(let[r,n]of Object.entries(t))void 0!==n&&void 0===e[r]&&(e[r]=n)}(v.flags,function(e){let t={};for(let r of rZ){let n=e[r];void 0!==n&&(t[r]=n)}return t}(b)),w=v}catch(t){Z({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=ef(t,{diagnosticId:J().diagnosticId,logPath:ea({force:!0})??void 0});i?e3({success:!1,error:e}):e5(e,{showDetails:a}),process.exit(1);return}for(let e of w.warnings)process.stderr.write(`Warning: ${e}
83
- `);w.flags.version&&(process.stdout.write(`${n}
84
- `),process.exit(0));let b="help"===w.command,v=w.flags.help;if(b||v){b&&w.positionals.length>1&&(e5(new eg("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=b?w.positionals[0]:w.command;e||(process.stdout.write(`${eC}
85
- `),process.exit(0));let t=function(e){var t,r;let n=e_(e);if(!n)return null;let a=(t=e,(r=n).usageOverride?r.usageOverride:[t,...r.positionalArgs.map(eO),...r.allowedFlags.flatMap(e=>(eR.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),i=eU(new Set(n.allowedFlags)),o=eU(eN),s=[];return i.length>0&&s.push(eF("Command flags:",i)),s.push(eF("Global flags:",o)),`agent-device ${a}
79
+ `)}(n),0;if(e===rS||e===rF){let e=n.ref??"",t=n.x,r=n.y;if(e&&"number"==typeof t&&"number"==typeof r)return process.stdout.write(`Tapped @${e} (${t}, ${r})
80
+ `),0}if(e===rO)return process.stdout.write(`${JSON.stringify(n,null,2)}
81
+ `),0;let a=F(n);return a&&process.stdout.write(`${a}
82
+ `),0}(e,r,n,i);return 0!==o&&process.exit(o),!0}}function aF(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function aj(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=E(e);return t?{selector:t.selectorExpression}:{x:Number(e[0]),y:Number(e[1])}}function aB(e,t){if("start"===e||"stop"===e)return e;throw new ey("INVALID_ARGS",`${t} requires start|stop`)}function aV(e,t){if(void 0===e||""===e)throw new ey("INVALID_ARGS",t);return e}function aG(e){return void 0===e?void 0:Number(e)}let aq={...{session:nh,[r$]:ng,[rI]:nv,"ensure-simulator":nw,metro:nb,install:nI,reinstall:nk,"install-from-source":nx,connect:nB,disconnect:nV,connection:nG,open:nD,close:n$,[rX]:nz,[rH]:aM,[rM]:aP},...{[rQ]:async({positionals:e,flags:t,client:r})=>(nf(t,await r.command.wait(function(e,t){let r=C(e);if(!r)throw new ey("INVALID_ARGS","wait requires <ms>, text <text>, @ref, or <selector> [timeoutMs].");let n={...np(t),depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw};if("sleep"===r.kind)return{...n,durationMs:r.durationMs};if("text"===r.kind){if(!r.text)throw new ey("INVALID_ARGS","wait requires text.");return{...n,text:r.text,...aL(r.timeoutMs)}}return"ref"===r.kind?{...n,ref:r.rawRef,...aL(r.timeoutMs)}:{...n,selector:r.selectorExpression,...aL(r.timeoutMs)}}(e,t))),!0),[rw]:async({positionals:e,flags:t,client:r})=>(nf(t,await r.command.alert(function(e,t){if(e.length>2)throw new ey("INVALID_ARGS","alert accepts at most action and timeout arguments.");let r=function(e){let t=e?.toLowerCase();if(void 0===t||"get"===t||"accept"===t||"dismiss"===t||"wait"===t)return t;throw new ey("INVALID_ARGS","alert action must be get, accept, dismiss, or wait.")}(e[0]),n=function(e,t){if(void 0===e)return;let r=Number(e);if(Number.isFinite(r))return r;throw new ey("INVALID_ARGS",`${t} must be a finite number.`)}(e[1],"alert timeout");return{...np(t),...r?{action:r}:{},...void 0!==n?{timeoutMs:n}:{}}}(e,t))),!0),[rb]:async({flags:e,client:t})=>{let r=await t.command.appState(np(e));return nm(e,r,()=>(function(e){if("ios"===e.platform){let t=[`Foreground app: ${e.appName??e.appBundleId??"unknown"}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.source&&t.push(`Source: ${e.source}`),t.join("\n")}if("android"===e.platform){let t=[`Foreground app: ${e.package??"unknown"}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join("\n")}return null})(r)),!0},[rk]:async({flags:e,client:t})=>(nf(e,await t.command.back({...np(e),mode:e.backMode})),!0),[rR]:async({flags:e,client:t})=>(nf(e,await t.command.home(np(e))),!0),[rG]:async({positionals:e,flags:t,client:r})=>(nf(t,await r.command.rotate(function(e,t){if(e.length>1)throw new ey("INVALID_ARGS","rotate accepts exactly one orientation argument.");return{...np(t),orientation:I(e[0])}}(e,t))),!0),[rv]:async({flags:e,client:t})=>(nf(e,await t.command.appSwitcher(np(e))),!0),[r_]:async({positionals:e,flags:t,client:r})=>(nf(t,await r.command.keyboard(function(e,t){if(e.length>1)throw new ey("INVALID_ARGS","keyboard accepts at most one action argument.");let r=function(e){let t=e?.toLowerCase();if("get"===t)return"status";if(void 0===t||"status"===t||"dismiss"===t)return t;throw new ey("INVALID_ARGS","keyboard action must be status, get, or dismiss.")}(e[0]);return{...np(t),...r?{action:r}:{}}}(e,t))),!0),[rD]:async({positionals:e,flags:t,client:r})=>{var n,a;return n=t,a=await r.command.clipboard(function(e,t){let r=e[0]?.toLowerCase();if("read"!==r&&"write"!==r)throw new ey("INVALID_ARGS","clipboard requires a subcommand: read or write.");let n=np(t);if("read"===r){if(1!==e.length)throw new ey("INVALID_ARGS","clipboard read does not accept additional arguments.");return{...n,action:r}}if(e.length<2)throw new ey("INVALID_ARGS","clipboard write requires text.");return{...n,action:r,text:e.slice(1).join(" ")}}(e,t)),n.json?nm(n,a):"read"===a.action?process.stdout.write(`${a.text}
83
+ `):nf(n,a),!0}},...aO};async function aH(e){let t=aq[e.command];return!!t&&await t(e)}function aK(e,t={}){let r=aX(t),n={...e};return r.defaultPlatform&&void 0===n.platform&&(n.platform=r.defaultPlatform),n}function aX(e){var t,r,n,a;let i,o=e.env??process.env,s=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new ey("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(o.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??o.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:s,lockPolicy:(r=e.policyOverrides,n=o,a=l,(i=r?.sessionLock??r?.sessionLockConflicts??aY(n.AGENT_DEVICE_SESSION_LOCK)??aY(n.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||N(n.AGENT_DEVICE_SESSION_LOCKED)||a?"reject":void 0))}}function aY(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new ey("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let aJ=nP.map(e=>e.key),az={sendToDaemon:tb};async function aW(e,t=az){let r=q(),n=K(),a=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),i=e.includes("--json"),o=function(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(r.startsWith("--session=")){let e=r.slice(10).trim();return e.length>0?e:null}if("--session"===r){let r=e[t+1]?.trim();if(r&&!r.startsWith("-"))return r;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await en({session:o,requestId:r,command:e[0],debug:a},async()=>{var o,l,c,u,d,p,m,h,g,y,w,b,v;let I,k,x,A,S,D,$;try{let t,r,n,a,i,b,v,k;o={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,n=[],a=[],i=!0;for(let o=0;o<e.length;o+=1){let s=e[o];if(i&&"--"===s){i=!1;continue}if(!i){r?n.push(s):r=e4(s);continue}let l=s.startsWith("--"),c=s.startsWith("-")&&s.length>1;if(!l&&!c){r?n.push(s):r=e4(s);continue}let[u,d]=l?e3(s):[s,void 0],p=eC.get(u);if(!p){if(function(e,t,r){var n;if(n=r,!/^-\d+(\.\d+)?$/.test(n)||!e)return!1;let a=eU(e);return!a||!!a.allowsExtraPositionals||0!==a.positionalArgs.length&&(t.length<a.positionalArgs.length||a.positionalArgs.some(e=>e.includes("?")))}(r,n,s)){r?n.push(s):r=s;continue}throw new ey("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,r,n){if(void 0!==e.setValue){if(void 0!==r)throw new ey("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==r)throw new ey("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==r){if(0===r.trim().length)throw new ey("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:r,consumeNext:!1}}return void 0===n||e8(n)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(n)?{value:!0,consumeNext:!1}:{value:n,consumeNext:!0}}let a=r??n;if(void 0===a||void 0===r&&e8(a))throw new ey("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:a,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(a))throw new ey("INVALID_ARGS",`Invalid ${e5(t)}: ${a}`);return{value:a,consumeNext:void 0===r}}let i=Number(a);if(!Number.isFinite(i)||"number"==typeof e.min&&i<e.min||"number"==typeof e.max&&i>e.max)throw new ey("INVALID_ARGS",`Invalid ${e5(t)}: ${a}`);return{value:Math.floor(i),consumeNext:void 0===r}}(p,u,d,e[o+1]);m.consumeNext&&(o+=1);let f=t[p.key];if(p.multiple){let e=Array.isArray(f)?[...f,m.value]:void 0===f?[m.value]:[f,m.value];t[p.key]=e}else t[p.key]=m.value;a.push({key:p.key,token:u})}return{command:r,positionals:n,flags:t,warnings:[],providedFlags:a}}(e),r=o?.env??process.env,n=o?.cwd??process.cwd(),u=t.command,a=("connect"===u||"metro"===u)&&(l={remoteConfig:t.flags.remoteConfig,cwd:n,env:r}).remoteConfig?{...function(e){let t={};for(let r of aJ){let n=e[r];void 0!==n&&(t[r]=n)}return t}(nL({configPath:l.remoteConfig,cwd:l.cwd,env:l.env}).profile),remoteConfig:l.remoteConfig}:{},v=eN((i=(c={command:t.command,cwd:n,cliFlags:t.flags,env:r}).env??process.env,b=eN({},function(e){let t={};for(let r of e)eN(t,function(e,t){let r,n;if(!f.existsSync(e)){if(t)throw new ey("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{r=f.readFileSync(e,"utf8")}catch(t){throw new ey("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{n=JSON.parse(r)}catch(t){throw new ey("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!n||"object"!=typeof n||Array.isArray(n))throw new ey("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[n,a]of Object.entries(e)){let e=e0.get(n);if(!e)throw new ey("INVALID_ARGS",`Unknown config key "${n}" in ${t}.`);if(!e.config.enabled)throw new ey("INVALID_ARGS",`Unsupported config key "${n}" in ${t}.`);r[n]=eJ(e2(e),a,t,n)}return r}(n,`config file ${e}`)}(r.path,r.required));return t}((d=c.cwd,p=c.cliFlags.config,m=i,(k=p??m.AGENT_DEVICE_CONFIG)?[{path:(h=k,g=d,y=m,W(h,{cwd:g,env:y})),required:!0}]:[{path:(w=m,s.join(O("~",{env:w}),".agent-device","config.json")),required:!1},{path:s.resolve(d,"agent-device.json"),required:!1}]))),eN(b,function(e,t){var r,n,a;let i={};for(let o of eQ.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=o.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(i[o.key]=(r=t.value,n=`environment variable ${t.name}`,a=t.name,eJ(e2(o),r,n,a)))}return i}(i,c.command))),a),I={...function(e,t){let r=t?.strictFlags??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),n=[...e.warnings],a=eN({json:!1,help:!1,version:!1},t?.defaultFlags??{});eN(a,e.flags);let i=eU(e.command),o=e.providedFlags.filter(t=>!e1(t.key,e.command));if(o.length>0){var s,l;let t=o.map(e=>e.token),i=(s=e.command,l=t,s?1===l.length?`Flag ${l[0]} is not supported for command ${s}.`:`Flags ${l.join(", ")} are not supported for command ${s}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(r)throw new ey("INVALID_ARGS",i);for(let e of(n.push(`${i} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),o))delete a[e.key]}for(let t of Object.keys(a))void 0!==a[t]&&(e1(t,e.command)||delete a[t]);if(function(e){if("back"===e.command&&!(new Set(e.providedFlags.filter(e=>"backMode"===e.key).map(e=>e.token)).size<=1))throw new ey("INVALID_ARGS","back accepts only one explicit mode flag: use either --in-app or --system.")}(e),i?.defaults)for(let[e,t]of Object.entries(i.defaults))void 0===a[e]&&(a[e]=t);if("batch"===e.command&&1!=+!!a.steps+ +!!a.stepsFile)throw new ey("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return function(e){if(e.flags.help)return e;if("snapshot"===e.command&&e.flags.snapshotDiff){let{snapshotDiff:t,...r}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:r,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:a,warnings:n})}(t,{strictFlags:o?.strictFlags,defaultFlags:v}),providedFlags:t.providedFlags}}catch(t){Q({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=eh(t,{diagnosticId:J().diagnosticId,logPath:ei({force:!0})??void 0});i?e6({success:!1,error:e}):e7(e,{showDetails:a}),process.exit(1);return}for(let e of I.warnings)process.stderr.write(`Warning: ${e}
84
+ `);I.flags.version&&(process.stdout.write(`${n}
85
+ `),process.exit(0));let N="help"===I.command,R=I.flags.help;if(N||R){N&&I.positionals.length>1&&(e7(new ey("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=N?I.positionals[0]:I.command;e||(process.stdout.write(`${eB}
86
+ `),process.exit(0));let t=function(e){var t,r;let n=eU(e);if(!n)return null;let a=(t=e,(r=n).usageOverride?r.usageOverride:[t,...r.positionalArgs.map(ej),...r.allowedFlags.flatMap(e=>(eO.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),i=eV(new Set(n.allowedFlags)),o=eV(eE),s=[];return i.length>0&&s.push(eG("Command flags:",i)),s.push(eG("Global flags:",o)),`agent-device ${a}
86
87
 
87
88
  ${n.helpDescription}
88
89
 
@@ -90,9 +91,9 @@ Usage:
90
91
  agent-device ${a}
91
92
 
92
93
  ${s.join("\n\n")}
93
- `}(e2(e));t&&(process.stdout.write(t),process.exit(0)),e5(new eg("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${eC}
94
- `),process.exit(1)}w.command||(process.stdout.write(`${eC}
95
- `),process.exit(1));let{command:x,positionals:k}=w,I=aM({policyOverrides:w.flags,configuredPlatform:w.flags.platform,configuredSession:w.flags.session}),A=I.lockPolicy?{...w.flags}:a$(w.flags,{policyOverrides:w.flags,configuredPlatform:w.flags.platform,configuredSession:w.flags.session}),D=en(A.stateDir),S=A.session??"default";eD({command:x,currentVersion:n,stateDir:D.baseDir,flags:A});let P=A.daemonBaseUrl,L=!A.verbose||A.json||P?null:function(e){try{let t=0,r=!1,n=setInterval(()=>{if(!r&&f.existsSync(e))try{let r=f.statSync(e);if(r.size<t&&(t=0),r.size<=t)return;let n=f.openSync(e,"r");try{let e=Buffer.alloc(r.size-t);f.readSync(n,e,0,e.length,t),t=r.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{f.closeSync(n)}}catch{}},200);return()=>{r=!0,clearInterval(n)}}catch{return null}}(D.logPath),E=function(e={},t={}){var r;let n,a=t.transport??tm,i=nd(e),o=async(t,r=[],n={})=>{let o=np(e,i,n),s=await a({session:ns(o.session),command:t,positionals:r,flags:nn({stateDir:o.stateDir,daemonBaseUrl:o.daemonBaseUrl,daemonAuthToken:o.daemonAuthToken,daemonTransport:o.daemonTransport,daemonServerMode:o.daemonServerMode,tenant:o.tenant,sessionIsolation:o.sessionIsolation,runId:o.runId,leaseId:o.leaseId,platform:o.platform,target:o.target,device:o.device,udid:o.udid,serial:o.serial,iosSimulatorDeviceSet:o.iosSimulatorDeviceSet,androidDeviceAllowlist:o.androidDeviceAllowlist,runtime:o.simulatorRuntimeId,boot:o.boot,reuseExisting:o.reuseExisting,surface:o.surface,activity:o.activity,relaunch:o.relaunch,shutdown:o.shutdown,saveScript:o.saveScript,noRecord:o.noRecord,backMode:o.backMode,metroHost:o.metroHost,metroPort:o.metroPort,bundleUrl:o.bundleUrl,launchUrl:o.launchUrl,snapshotInteractiveOnly:o.interactiveOnly,snapshotCompact:o.compact,snapshotDepth:o.depth,snapshotScope:o.scope,snapshotRaw:o.raw,screenshotFullscreen:o.screenshotFullscreen,overlayRefs:o.overlayRefs,appsFilter:o.appsFilter,out:o.out,count:o.count,fps:o.fps,hideTouches:o.hideTouches,intervalMs:o.intervalMs,delayMs:o.delayMs,holdMs:o.holdMs,jitterPx:o.jitterPx,pixels:o.pixels,doubleTap:o.doubleTap,clickButton:o.clickButton,pauseMs:o.pauseMs,pattern:o.pattern,headless:o.headless,restart:o.restart,replayUpdate:o.replayUpdate,failFast:o.failFast,timeoutMs:o.timeoutMs,retries:o.retries,artifactsDir:o.artifactsDir,reportJunit:o.reportJunit,findFirst:o.findFirst,findLast:o.findLast,networkInclude:o.networkInclude,batchOnError:o.batchOnError,batchMaxSteps:o.batchMaxSteps,batchSteps:o.batchSteps,verbose:o.debug}),runtime:o.runtime,meta:nn({requestId:o.requestId,cwd:o.cwd,debug:o.debug,lockPolicy:o.lockPolicy,lockPlatform:o.lockPlatform,tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId,sessionIsolation:o.sessionIsolation,installSource:o.installSource,retainMaterializedPaths:o.retainMaterializedPaths,materializedPathRetentionMs:o.materializedPathRetentionMs,materializationId:o.materializationId})});return s.ok||function(e){throw new eg(e.code,e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(s.error),s.data??{}},s=async(e={})=>{let t=await o("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(no)},l=async(e,t=[],r={})=>await o(e,t,r),u=(t={})=>ns(np(e,i,t).session);return{command:(r=async e=>await o(e.command,e.positionals,e.options),n=async e=>await r(e),{wait:async e=>await n(function(e){if(1!==[void 0!==e.durationMs?"durationMs":void 0,void 0!==e.text?"text":void 0,void 0!==e.ref?"ref":void 0,void 0!==e.selector?"selector":void 0].filter(Boolean).length)throw new eg("INVALID_ARGS","wait command requires exactly one of durationMs, text, ref, or selector.");if(void 0!==e.durationMs)return{command:rY,positionals:[String(e.durationMs)],options:e};let t=void 0!==e.timeoutMs?[String(e.timeoutMs)]:[];if(void 0!==e.text)return{command:rY,positionals:["text",e.text,...t],options:e};if(void 0!==e.ref)return{command:rY,positionals:[e.ref,...t],options:e};let r=e.selector;return function(e){if(!q(e))throw new eg("INVALID_ARGS",`Invalid wait selector: ${e}`)}(r),{command:rY,positionals:[r,...t],options:e}}(e)),alert:async(e={})=>{var t;return await n({command:rp,positionals:[(t=e).action??"get",...void 0!==t.timeoutMs?[String(t.timeoutMs)]:[]],options:t})},appState:async(e={})=>await n({command:rd,positionals:[],options:e}),back:async(e={})=>await n({command:rh,positionals:[],options:{...e,backMode:e.mode}}),home:async(e={})=>await n({command:rD,positionals:[],options:e}),rotate:async e=>await n({command:rO,positionals:[e.orientation],options:e}),appSwitcher:async(e={})=>await n({command:rm,positionals:[],options:e}),keyboard:async(e={})=>await n({command:rS,positionals:e.action?[e.action]:[],options:e}),clipboard:async e=>{var t;return await n("read"===(t=e).action?{command:rb,positionals:["read"],options:t}:{command:rb,positionals:["write",t.text],options:t})}}),devices:{list:async(e={})=>{let t=await o(rv,[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ni)},boot:async(e={})=>await l(ry,[],e)},sessions:{list:async(e={})=>await s(e),close:async(e={})=>{let t=u(e),r=(await o("close",[],e)).shutdown;return{session:t,shutdown:"object"==typeof r&&null!==r?r:void 0,identifiers:{session:t}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,n=await o("ensure-simulator",[],{...r,simulatorRuntimeId:t}),a=r1(n,"udid"),i=r1(n,"device");return{udid:a,device:i,runtime:r1(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:r3(n,"ios_simulator_device_set"),identifiers:{deviceId:a,deviceName:i,udid:a}}}},apps:{install:async e=>na(await o("install",[e.app,e.appPath],e),u(e)),reinstall:async e=>na(await o("reinstall",[e.app,e.appPath],e),u(e)),installFromSource:async e=>(function(e,t){let r=r2(e,"bundleId"),n=r2(e,"packageName"),a=r??n??r2(e,"appId"),i=r2(e,"launchTarget")??n??r??a;if(!i)throw new eg("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:r2(e,"appName"),appId:a,bundleId:r,packageName:n,launchTarget:i,installablePath:r2(e,"installablePath"),archivePath:r2(e,"archivePath"),materializationId:r2(e,"materializationId"),materializationExpiresAt:r2(e,"materializationExpiresAt"),identifiers:M({session:t,bundleId:r,packageName:n,appId:a})}})(await o("install_source",[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),u(e)),list:async(e={})=>{let t=await o(rf,[],e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=u(e),r=e.app?e.url?[e.app,e.url]:[e.app]:[],n=await o("open",r,e),a=function(e){let t=e.platform,r=r2(e,"id"),n=r2(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!n)return;let a=r8(e,"target"),i=$(t,r,n);return{platform:t,target:a,id:r,name:n,identifiers:i,ios:"ios"===t?{udid:r2(e,"device_udid")??r,simulatorSetPath:r3(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:r2(e,"serial")??r}:void 0}}(n),i=r2(n,"appBundleId");return{session:t,appName:r2(n,"appName"),appBundleId:i,appId:i,startup:function(e){if(nr(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:r2(e,"appTarget"),appBundleId:r2(e,"appBundleId")}}(n.startup),runtime:function(e){if(!nr(e))return;let t=e.platform,r=r2(e,"metroHost"),n="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:n,bundleUrl:r2(e,"bundleUrl"),launchUrl:r2(e,"launchUrl")}}(n.runtime),device:a,identifiers:{session:t,deviceId:a?.id,deviceName:a?.name,udid:a?.ios?.udid,serial:a?.android?.serial,appId:i,appBundleId:i}}},close:async(e={})=>{let t=u(e),r=(await o("close",e.app?[e.app]:[],e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof r&&null!==r?r:void 0,identifiers:{session:t}}},push:async e=>{var t;return await l(rR,[e.app,"string"==typeof(t=e.payload)?t:JSON.stringify(t)],e)},triggerEvent:async e=>{var t;return await l(rq,[(t=e).event,...t.payload?[JSON.stringify(t.payload)]:[]],e)}},materializations:{release:async e=>{var t;return{released:!0===(t=await o("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:r1(t,"materializationId"),identifiers:{}}}},metro:{prepare:async t=>await rc({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath})},capture:{snapshot:async(e={})=>{var t;let r=u(e),n=await o(rj,[],e),a=r2(n,"appBundleId"),i="object"==typeof n.visibility&&null!==n.visibility?n.visibility:void 0;return{nodes:Array.isArray(t=n.nodes)?t:[],truncated:!0===n.truncated,appName:r2(n,"appName"),appBundleId:a,...i?{visibility:i}:{},warnings:Array.isArray(n.warnings)?n.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:r,appId:a,appBundleId:a}}},screenshot:async(e={})=>{let t=u(e),r=await o(rU,e.path?[e.path]:[],{...e,screenshotFullscreen:e.fullscreen});return{path:r1(r,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!nr(e))continue;let t=r2(e,"ref"),n=r4(e,"rect"),a=r4(e,"overlayRect"),i=function(e,t){let r=e[t];if(!nr(r))return;let n="number"==typeof r.x?r.x:void 0,a="number"==typeof r.y?r.y:void 0;if(void 0!==n&&void 0!==a)return{x:n,y:a}}(e,"center");t&&n&&a&&i&&r.push({ref:t,label:r2(e,"label"),rect:n,overlayRect:a,center:i})}return r}(r),identifiers:{session:t}}},diff:async e=>await l(rx,[e.kind],{...e,interactiveOnly:e.interactiveOnly,compact:e.compact,depth:e.depth,scope:e.scope,raw:e.raw})},interactions:{click:async e=>await l(rw,nl(e),{...e,clickButton:e.button}),press:async e=>await l(rE,nl(e),e),longPress:async e=>await l(rM,[String(e.x),String(e.y),...nc(e.durationMs)],e),swipe:async e=>await l(rV,[String(e.from.x),String(e.from.y),String(e.to.x),String(e.to.y),...nc(e.durationMs)],e),focus:async e=>await l(rA,[String(e.x),String(e.y)],e),type:async e=>await l(rX,[e.text],e),fill:async e=>await l(rk,[...nl(e),e.text],e),scroll:async e=>await l(rC,[e.direction,...nc(e.amount)],e),pinch:async e=>await l(rL,[String(e.scale),...nc(e.x),...nc(e.y)],e),get:async e=>{var t;return await l("get",[e.format,...void 0!==(t=e).ref?[t.ref,...nu(t.label)]:[t.selector]],e)},is:async e=>await l("is",[e.predicate,e.selector,..."text"===e.predicate?[e.value]:[]],e),find:async e=>await l(rI,function(e){let t=e.locator&&"any"!==e.locator?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case"click":case"focus":case"exists":return e.action?[...t,e.action]:t;case"getText":return[...t,"get","text"];case"getAttrs":return[...t,"get","attrs"];case"wait":return[...t,"wait",...nc(e.timeoutMs)];case"fill":case"type":return[...t,e.action,e.value]}}(e),{...e,findFirst:e.first,findLast:e.last})},replay:{run:async e=>await l(rT,[e.path],{...e,replayUpdate:e.update}),test:async e=>await l(rB,e.paths,{...e,replayUpdate:e.update})},batch:{run:async e=>await l(rg,[],{...e,batchSteps:e.steps,batchOnError:e.onError,batchMaxSteps:e.maxSteps})},observability:{perf:async(e={})=>await l(rN,[],e),logs:async(e={})=>{var t;return await l(r$,[(t=e).action??"path",...nu(t.message)],e)},network:async(e={})=>{var t;return await l(rP,[...(t=e).action?[t.action]:[],...nc(t.limit)],{...e,networkInclude:e.include})}},recording:{record:async e=>await l(r_,[e.action,...nu(e.path)],e),trace:async e=>await l(rG,[e.action,...nu(e.path)],e)},settings:{update:async e=>await l(rF,[e.setting,e.state,..."permission"in e?[e.permission]:[],..."mode"in e&&e.mode?[e.mode]:[]],e)}}}({session:S,requestId:r,stateDir:A.stateDir,daemonBaseUrl:A.daemonBaseUrl,daemonAuthToken:A.daemonAuthToken,daemonTransport:A.daemonTransport,daemonServerMode:A.daemonServerMode,remoteConfig:A.remoteConfig,tenant:A.tenant,sessionIsolation:A.sessionIsolation,runId:A.runId,leaseId:A.leaseId,lockPolicy:I.lockPolicy,lockPlatform:I.defaultPlatform,cwd:process.cwd(),debug:!!A.verbose},{transport:t.sendToDaemon});try{if("batch"===x){if(k.length>0)throw new eg("INVALID_ARGS","batch does not accept positional arguments.");let e=(function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=f.readFileSync(e.stepsFile,"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new eg("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return N(t)})(A).map((e,t)=>({...e,flags:I.lockPolicy&&void 0===A.platform?{...e.flags??{}}:a$(e.flags??{},{policyOverrides:A,configuredPlatform:A.platform,configuredSession:A.session,inheritedPlatform:A.platform})}));if(await aS({command:x,positionals:k,flags:{...A,batchSteps:e},client:E}))return}else if("runtime"===x)throw new eg("INVALID_ARGS","runtime command was removed. Use open --remote-config <path> --relaunch for remote Metro launches, or metro prepare --remote-config <path> for inspection.");else if(await aS({command:x,positionals:k,flags:A,client:E}))return;throw new eg("INVALID_ARGS",`Unknown command: ${x}`)}catch(r){let e=em(r),t=ef(e,{diagnosticId:J().diagnosticId,logPath:ea({force:!0})??void 0});if("close"===x&&"COMMAND_FAILED"===(y=e).code&&(y.details?.kind==="daemon_startup_failed"||y.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof y.details?.infoPath||"string"==typeof y.details?.lockPath))){A.json&&e3({success:!0,data:{closed:"session",source:"no-daemon"}});return}if(A.json)e3({success:!1,error:t});else if(e5(t,{showDetails:A.verbose}),A.verbose)try{let e=D.logPath;if(f.existsSync(e)){let t=f.readFileSync(e,"utf8").split("\n"),r=t.slice(Math.max(0,t.length-200)).join("\n");r.trim().length>0&&process.stderr.write(`
94
+ `}(e4(e));t&&(process.stdout.write(t),process.exit(0)),e7(new ey("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${eB}
95
+ `),process.exit(1)}I.command||(process.stdout.write(`${eB}
96
+ `),process.exit(1));let{command:_,positionals:E}=I,T=new Set(I.providedFlags.map(e=>e.key));try{if(I.flags.remoteConfig&&"connect"!==_&&"metro"!==_)throw new ey("INVALID_ARGS","--remote-config is only supported by connect and metro prepare. Run agent-device connect first, then use normal commands.");x=(k=aX({policyOverrides:I.flags,configuredPlatform:I.flags.platform,configuredSession:I.flags.session})).lockPolicy?{...I.flags}:aK(I.flags,{policyOverrides:I.flags,configuredPlatform:I.flags.platform,configuredSession:I.flags.session}),A=ea(x.stateDir),S=x.session??"default",b={command:_,explicitFlagKeys:T,stateDir:A.baseDir,session:S},$=(D="connect"===b.command||"connection"===b.command||b.explicitFlagKeys.has("remoteConfig")?null:function(e){let t=e.validateRemoteConfigHash??!0,r=nR(e)??(e.allowActiveFallback?nO({stateDir:e.stateDir}):null);if(!r)return null;if(t&&nE(r.remoteConfigPath)!==r.remoteConfigHash)throw new ey("INVALID_ARGS","Active remote connection config changed. Run agent-device connect --force to refresh it.",{remoteConfig:r.remoteConfigPath});let n=function(e,t){try{return nL({configPath:e.remoteConfigPath,cwd:t.cwd,env:t.env}).profile}catch(e){if(!1===t.validateRemoteConfigHash)return{};throw e}}(r,e);return{runtime:r.runtime,flags:{...n,remoteConfig:r.remoteConfigPath,daemonBaseUrl:r.daemon?.baseUrl??n.daemonBaseUrl,daemonTransport:r.daemon?.transport??n.daemonTransport,daemonServerMode:r.daemon?.serverMode??n.daemonServerMode,tenant:r.tenant,sessionIsolation:"tenant",runId:r.runId,leaseId:r.leaseId,leaseBackend:r.leaseBackend,session:r.session,platform:r.platform??n.platform,target:r.target??n.target}}}({stateDir:b.stateDir,session:b.session,cwd:process.cwd(),env:process.env,allowActiveFallback:!b.explicitFlagKeys.has("session"),validateRemoteConfigHash:"disconnect"!==b.command}))?function(e,t,r){let n={...e};for(let[e,a]of Object.entries(t))void 0!==a&&(r.has(e)||(n[e]=a));return n}(x,D.flags,T):x}catch(t){let e=eh(ef(t),{diagnosticId:J().diagnosticId,logPath:ei({force:!0})??void 0});I.flags.json?e6({success:!1,error:e}):e7(e,{showDetails:I.flags.verbose}),process.exit(1);return}eP({command:_,currentVersion:n,stateDir:A.baseDir,flags:$});let C=$.daemonBaseUrl,U=!$.verbose||$.json||C?null:function(e){try{let t=0,r=!1,n=setInterval(()=>{if(!r&&f.existsSync(e))try{let r=f.statSync(e);if(r.size<t&&(t=0),r.size<=t)return;let n=f.openSync(e,"r");try{let e=Buffer.alloc(r.size-t);f.readSync(n,e,0,e.length,t),t=r.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{f.closeSync(n)}}catch{}},200);return()=>{r=!0,clearInterval(n)}}catch{return null}}(A.logPath),F=function(e={},t={}){var r;let n,a=t.transport??tb,i=async(t,r=[],n={})=>{var i,o;let s=(i=e,o=n,{...i,...o}),l=await a({session:ns(s.session),command:t,positionals:r,flags:nn({stateDir:s.stateDir,daemonBaseUrl:s.daemonBaseUrl,daemonAuthToken:s.daemonAuthToken,daemonTransport:s.daemonTransport,daemonServerMode:s.daemonServerMode,tenant:s.tenant,sessionIsolation:s.sessionIsolation,runId:s.runId,leaseId:s.leaseId,leaseBackend:s.leaseBackend,platform:s.platform,target:s.target,device:s.device,udid:s.udid,serial:s.serial,iosSimulatorDeviceSet:s.iosSimulatorDeviceSet,androidDeviceAllowlist:s.androidDeviceAllowlist,runtime:s.simulatorRuntimeId,boot:s.boot,reuseExisting:s.reuseExisting,surface:s.surface,activity:s.activity,relaunch:s.relaunch,shutdown:s.shutdown,saveScript:s.saveScript,noRecord:s.noRecord,backMode:s.backMode,metroHost:s.metroHost,metroPort:s.metroPort,bundleUrl:s.bundleUrl,launchUrl:s.launchUrl,snapshotInteractiveOnly:s.interactiveOnly,snapshotCompact:s.compact,snapshotDepth:s.depth,snapshotScope:s.scope,snapshotRaw:s.raw,screenshotFullscreen:s.screenshotFullscreen,overlayRefs:s.overlayRefs,appsFilter:s.appsFilter,out:s.out,count:s.count,fps:s.fps,hideTouches:s.hideTouches,intervalMs:s.intervalMs,delayMs:s.delayMs,holdMs:s.holdMs,jitterPx:s.jitterPx,pixels:s.pixels,doubleTap:s.doubleTap,clickButton:s.clickButton,pauseMs:s.pauseMs,pattern:s.pattern,headless:s.headless,restart:s.restart,replayUpdate:s.replayUpdate,failFast:s.failFast,timeoutMs:s.timeoutMs,retries:s.retries,artifactsDir:s.artifactsDir,reportJunit:s.reportJunit,findFirst:s.findFirst,findLast:s.findLast,networkInclude:s.networkInclude,batchOnError:s.batchOnError,batchMaxSteps:s.batchMaxSteps,batchSteps:s.batchSteps,verbose:s.debug}),runtime:s.runtime,meta:nn({requestId:s.requestId,cwd:s.cwd,debug:s.debug,lockPolicy:s.lockPolicy,lockPlatform:s.lockPlatform,tenantId:s.tenant,runId:s.runId,leaseId:s.leaseId,leaseBackend:s.leaseBackend,leaseTtlMs:s.leaseTtlMs,sessionIsolation:s.sessionIsolation,installSource:s.installSource,retainMaterializedPaths:s.retainMaterializedPaths,materializedPathRetentionMs:s.materializedPathRetentionMs,materializationId:s.materializationId})});return l.ok||function(e){throw new ey(e.code,e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(l.error),l.data??{}},o=async(e={})=>{let t=await i("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(no)},s=async(e,t=[],r={})=>await i(e,t,r),l=(t={})=>{var r,n;return ns((r=e,n=t,{...r,...n}).session)};return{command:(r=async e=>await i(e.command,e.positionals,e.options),n=async e=>await r(e),{wait:async e=>await n(function(e){if(1!==[void 0!==e.durationMs?"durationMs":void 0,void 0!==e.text?"text":void 0,void 0!==e.ref?"ref":void 0,void 0!==e.selector?"selector":void 0].filter(Boolean).length)throw new ey("INVALID_ARGS","wait command requires exactly one of durationMs, text, ref, or selector.");if(void 0!==e.durationMs)return{command:rQ,positionals:[String(e.durationMs)],options:e};let t=void 0!==e.timeoutMs?[String(e.timeoutMs)]:[];if(void 0!==e.text)return{command:rQ,positionals:["text",e.text,...t],options:e};if(void 0!==e.ref)return{command:rQ,positionals:[e.ref,...t],options:e};let r=e.selector;return function(e){if(!H(e))throw new ey("INVALID_ARGS",`Invalid wait selector: ${e}`)}(r),{command:rQ,positionals:[r,...t],options:e}}(e)),alert:async(e={})=>{var t;return await n({command:rw,positionals:[(t=e).action??"get",...void 0!==t.timeoutMs?[String(t.timeoutMs)]:[]],options:t})},appState:async(e={})=>await n({command:rb,positionals:[],options:e}),back:async(e={})=>await n({command:rk,positionals:[],options:{...e,backMode:e.mode}}),home:async(e={})=>await n({command:rR,positionals:[],options:e}),rotate:async e=>await n({command:rG,positionals:[e.orientation],options:e}),appSwitcher:async(e={})=>await n({command:rv,positionals:[],options:e}),keyboard:async(e={})=>await n({command:r_,positionals:e.action?[e.action]:[],options:e}),clipboard:async e=>{var t;return await n("read"===(t=e).action?{command:rD,positionals:["read"],options:t}:{command:rD,positionals:["write",t.text],options:t})}}),devices:{list:async(e={})=>{let t=await i(r$,[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ni)},boot:async(e={})=>await s(rA,[],e)},sessions:{list:async(e={})=>await o(e),close:async(e={})=>{let t=l(e),r=(await i("close",[],e)).shutdown;return{session:t,shutdown:"object"==typeof r&&null!==r?r:void 0,identifiers:{session:t}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,n=await i("ensure-simulator",[],{...r,simulatorRuntimeId:t}),a=r1(n,"udid"),o=r1(n,"device");return{udid:a,device:o,runtime:r1(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:r3(n,"ios_simulator_device_set"),identifiers:{deviceId:a,deviceName:o,udid:a}}}},apps:{install:async e=>na(await i("install",[e.app,e.appPath],e),l(e)),reinstall:async e=>na(await i("reinstall",[e.app,e.appPath],e),l(e)),installFromSource:async e=>(function(e,t){let r=r2(e,"bundleId"),n=r2(e,"packageName"),a=r??n??r2(e,"appId"),i=r2(e,"launchTarget")??n??r??a;if(!i)throw new ey("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:r2(e,"appName"),appId:a,bundleId:r,packageName:n,launchTarget:i,installablePath:r2(e,"installablePath"),archivePath:r2(e,"archivePath"),materializationId:r2(e,"materializationId"),materializationExpiresAt:r2(e,"materializationExpiresAt"),identifiers:P({session:t,bundleId:r,packageName:n,appId:a})}})(await i("install_source",[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),l(e)),list:async(e={})=>{let t=await i(rI,[],e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=l(e),r=e.app?e.url?[e.app,e.url]:[e.app]:[],n=await i("open",r,e),a=function(e){let t=e.platform,r=r2(e,"id"),n=r2(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!n)return;let a=r8(e,"target"),i=M(t,r,n);return{platform:t,target:a,id:r,name:n,identifiers:i,ios:"ios"===t?{udid:r2(e,"device_udid")??r,simulatorSetPath:r3(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:r2(e,"serial")??r}:void 0}}(n),o=r2(n,"appBundleId");return{session:t,appName:r2(n,"appName"),appBundleId:o,appId:o,startup:function(e){if(nr(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:r2(e,"appTarget"),appBundleId:r2(e,"appBundleId")}}(n.startup),runtime:function(e){if(!nr(e))return;let t=e.platform,r=r2(e,"metroHost"),n="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:n,bundleUrl:r2(e,"bundleUrl"),launchUrl:r2(e,"launchUrl")}}(n.runtime),device:a,identifiers:{session:t,deviceId:a?.id,deviceName:a?.name,udid:a?.ios?.udid,serial:a?.android?.serial,appId:o,appBundleId:o}}},close:async(e={})=>{let t=l(e),r=(await i("close",e.app?[e.app]:[],e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof r&&null!==r?r:void 0,identifiers:{session:t}}},push:async e=>{var t;return await s(rj,[e.app,"string"==typeof(t=e.payload)?t:JSON.stringify(t)],e)},triggerEvent:async e=>{var t;return await s(rW,[(t=e).event,...t.payload?[JSON.stringify(t.payload)]:[]],e)}},materializations:{release:async e=>{var t;return{released:!0===(t=await i("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:r1(t,"materializationId"),identifiers:{}}}},leases:{allocate:async e=>nd(await i("lease_allocate",[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>nd(await i("lease_heartbeat",[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await i("lease_release",[],e)).released})},metro:{prepare:async t=>await ry({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath})},capture:{snapshot:async(e={})=>{var t;let r=l(e),n=await i(rX,[],e),a=r2(n,"appBundleId"),o="object"==typeof n.visibility&&null!==n.visibility?n.visibility:void 0;return{nodes:Array.isArray(t=n.nodes)?t:[],truncated:!0===n.truncated,appName:r2(n,"appName"),appBundleId:a,...o?{visibility:o}:{},warnings:Array.isArray(n.warnings)?n.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:r,appId:a,appBundleId:a}}},screenshot:async(e={})=>{let t=l(e),r=await i(rH,e.path?[e.path]:[],{...e,screenshotFullscreen:e.fullscreen});return{path:r1(r,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!nr(e))continue;let t=r2(e,"ref"),n=r4(e,"rect"),a=r4(e,"overlayRect"),i=function(e,t){let r=e[t];if(!nr(r))return;let n="number"==typeof r.x?r.x:void 0,a="number"==typeof r.y?r.y:void 0;if(void 0!==n&&void 0!==a)return{x:n,y:a}}(e,"center");t&&n&&a&&i&&r.push({ref:t,label:r2(e,"label"),rect:n,overlayRect:a,center:i})}return r}(r),identifiers:{session:t}}},diff:async e=>await s(rM,[e.kind],{...e,interactiveOnly:e.interactiveOnly,compact:e.compact,depth:e.depth,scope:e.scope,raw:e.raw})},interactions:{click:async e=>await s(rS,nl(e),{...e,clickButton:e.button}),press:async e=>await s(rF,nl(e),e),longPress:async e=>await s(rT,[String(e.x),String(e.y),...nu(e.durationMs)],e),swipe:async e=>await s(rY,[String(e.from.x),String(e.from.y),String(e.to.x),String(e.to.y),...nu(e.durationMs)],e),focus:async e=>await s(rL,[String(e.x),String(e.y)],e),type:async e=>await s(rZ,[e.text],e),fill:async e=>await s(rP,[...nl(e),e.text],e),scroll:async e=>await s(rq,[e.direction,...nu(e.amount)],e),pinch:async e=>await s(rU,[String(e.scale),...nu(e.x),...nu(e.y)],e),get:async e=>{var t;return await s("get",[e.format,...void 0!==(t=e).ref?[t.ref,...nc(t.label)]:[t.selector]],e)},is:async e=>await s("is",[e.predicate,e.selector,..."text"===e.predicate?[e.value]:[]],e),find:async e=>await s(rN,function(e){let t=e.locator&&"any"!==e.locator?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case"click":case"focus":case"exists":return e.action?[...t,e.action]:t;case"getText":return[...t,"get","text"];case"getAttrs":return[...t,"get","attrs"];case"wait":return[...t,"wait",...nu(e.timeoutMs)];case"fill":case"type":return[...t,e.action,e.value]}}(e),{...e,findFirst:e.first,findLast:e.last})},replay:{run:async e=>await s(rV,[e.path],{...e,replayUpdate:e.update}),test:async e=>await s(rJ,e.paths,{...e,replayUpdate:e.update})},batch:{run:async e=>await s(rx,[],{...e,batchSteps:e.steps,batchOnError:e.onError,batchMaxSteps:e.maxSteps})},observability:{perf:async(e={})=>await s(rO,[],e),logs:async(e={})=>{var t;return await s(rE,[(t=e).action??"path",...nc(t.message)],e)},network:async(e={})=>{var t;return await s(rC,[...(t=e).action?[t.action]:[],...nu(t.limit)],{...e,networkInclude:e.include})}},recording:{record:async e=>await s(rB,[e.action,...nc(e.path)],e),trace:async e=>await s(rz,[e.action,...nc(e.path)],e)},settings:{update:async e=>await s(rK,[e.setting,e.state,..."permission"in e?[e.permission]:[],..."mode"in e&&e.mode?[e.mode]:[]],e)}}}({session:$.session??S,requestId:r,stateDir:$.stateDir,daemonBaseUrl:$.daemonBaseUrl,daemonAuthToken:$.daemonAuthToken,daemonTransport:$.daemonTransport,daemonServerMode:$.daemonServerMode,tenant:$.tenant,sessionIsolation:$.sessionIsolation,runId:$.runId,leaseId:$.leaseId,leaseBackend:$.leaseBackend,runtime:D?.runtime,lockPolicy:k.lockPolicy,lockPlatform:k.defaultPlatform,cwd:process.cwd(),debug:!!$.verbose},{transport:t.sendToDaemon});try{if("batch"===_){if(E.length>0)throw new ey("INVALID_ARGS","batch does not accept positional arguments.");let e=(function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=f.readFileSync(e.stepsFile,"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new ey("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return L(t)})(x).map((e,t)=>({...e,flags:k.lockPolicy&&void 0===x.platform?{...e.flags??{}}:aK(e.flags??{},{policyOverrides:$,configuredPlatform:$.platform,configuredSession:$.session,inheritedPlatform:$.platform})}));if(await aH({command:_,positionals:E,flags:{...$,batchSteps:e},client:F}))return}else if("runtime"===_)throw new ey("INVALID_ARGS","runtime command was removed. Use connect --remote-config <path> for remote runs, or metro prepare --remote-config <path> for inspection.");else if(await aH({command:_,positionals:E,flags:$,client:F}))return;throw new ey("INVALID_ARGS",`Unknown command: ${_}`)}catch(r){let e=ef(r),t=eh(e,{diagnosticId:J().diagnosticId,logPath:ei({force:!0})??void 0});if("close"===_&&"COMMAND_FAILED"===(v=e).code&&(v.details?.kind==="daemon_startup_failed"||v.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof v.details?.infoPath||"string"==typeof v.details?.lockPath))){$.json&&e6({success:!0,data:{closed:"session",source:"no-daemon"}});return}if($.json)e6({success:!1,error:t});else if(e7(t,{showDetails:$.verbose}),$.verbose)try{let e=A.logPath;if(f.existsSync(e)){let t=f.readFileSync(e,"utf8").split("\n"),r=t.slice(Math.max(0,t.length-200)).join("\n");r.trim().length>0&&process.stderr.write(`
96
97
  [daemon log]
97
98
  ${r}
98
- `)}}catch{}L&&L(),process.exit(1)}finally{L&&L()}})}c(process.argv[1]??"").href===import.meta.url&&aL(process.argv.slice(2)).catch(e=>{e5(ef(em(e)),{showDetails:!0}),process.exit(1)}),aL(process.argv.slice(2));
99
+ `)}}catch{}U&&U(),process.exit(1)}finally{U&&U()}})}u(process.argv[1]??"").href===import.meta.url&&aW(process.argv.slice(2)).catch(e=>{e7(eh(ef(e)),{showDetails:!0}),process.exit(1)}),aW(process.argv.slice(2));