agent-device 0.12.5 → 0.12.7

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,a,n,o,s;import i from"node:path";import{styleText as l}from"node:util";import{fileURLToPath as c,pathToFileURL as u}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 g from"node:os";import y,{createHash as w,randomUUID as b}from"node:crypto";import{parseDeviceRotation as v,SESSION_SURFACES as I,readProcessCommand as k,waitForProcessExit as A,serializeSessionListEntry as D,serializeSnapshotResult as S,isAgentDeviceDaemonProcess as $,buildDeviceIdentifiers as x,buildAppIdentifiers as N,isEnvTruthy as L,parseBatchStepsJson as P,computeDaemonCodeSignature as _,resolveDaemonTransportPreference as E,splitSelectorFromArgs as M,serializeOpenResult as R,parseWaitArgs as T,expandUserHomePath as O,serializeDeployResult as C,readCommandMessage as U,serializeEnsureSimulatorResult as F,localCommandPolicy as j,serializeDevice as V,buildSnapshotDisplayLines as B,buildMobileSnapshotPresentation as G,createRequestId as q,tryParseSelectorChain as H,readVersion as J,displayNodeLabel as K,findProjectRoot as z,getDiagnosticsMeta as W,withDiagnosticTimer as X,resolveUserPath as Y,serializeCloseResult as Z,emitDiagnostic as Q,SETTINGS_USAGE_OVERRIDE as ee,isProcessAlive as et,readProcessStartTime as er,withDiagnosticsScope as ea,resolveDaemonPaths as en,flushDiagnosticsToSessionFile as eo,resolveDaemonServerMode as es,serializeInstallFromSourceResult as ei,createAgentDevice as el,stopProcessForTakeover as ec,formatSnapshotLine as eu}from"./641.js";import{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 eI,ENV_STATE_PATH as ek,ENV_LAUNCH_URL as eA,ENV_SCOPE_TENANT_ID as eD,ENV_SCOPE_RUN_ID as eS,ENV_BEARER_TOKEN as e$,ENV_SCOPE_LEASE_ID as ex}from"./320.js";import{maybeRunUpgradeNotifier as eN}from"./113.js";function eL(e,t){for(let[r,a]of Object.entries(t))void 0!==a&&(e[r]=a);return e}let eP=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],e_=["snapshotDepth","snapshotScope","snapshotRaw"],eE=[{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:I,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:"quality",names:["--quality"],type:"int",min:5,max:10,usageLabel:"--quality <5-10>",usageDescription:"Record: scale recording resolution from 5 (50%) through 10 (native resolution)"},{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)"}],eM=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"]),eR={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",...eP]},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:[...eP,"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:[...e_]},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",...e_]},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:[...e_]},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",...e_]},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:[...e_,"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>] [--quality <5-10>] [--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","quality","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:[...e_]},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}},eT=new Map,eO=new Map;for(let e of eE){for(let t of e.names)eT.set(t,e);let t=eO.get(e.key);t?t.push(e):eO.set(e.key,[e])}function eC(e){if(e)return eR[e]}function eU(){return Object.keys(eR)}function eF(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let ej=(e=`agent-device <command> [args] [--json]
1
+ let e,t,r,a,n,o,s;import i 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 g from"node:os";import y,{createHash as w,randomUUID as b}from"node:crypto";import{parseDeviceRotation as v,SESSION_SURFACES as I,readProcessCommand as k,waitForProcessExit as A,serializeSessionListEntry as S,serializeSnapshotResult as D,isAgentDeviceDaemonProcess as $,buildDeviceIdentifiers as x,buildAppIdentifiers as N,isEnvTruthy as P,parseBatchStepsJson as L,computeDaemonCodeSignature as _,resolveDaemonTransportPreference as E,splitSelectorFromArgs as M,serializeOpenResult as R,parseWaitArgs as T,expandUserHomePath as C,serializeDeployResult as O,readCommandMessage as U,serializeEnsureSimulatorResult as F,localCommandPolicy as j,serializeDevice as B,buildSnapshotDisplayLines as V,buildMobileSnapshotPresentation as G,createRequestId as q,tryParseSelectorChain as H,readVersion as K,displayNodeLabel as J,findProjectRoot as z,getDiagnosticsMeta as W,withDiagnosticTimer as X,resolveUserPath as Y,serializeCloseResult as Z,emitDiagnostic as Q,SETTINGS_USAGE_OVERRIDE as ee,isProcessAlive as et,readProcessStartTime as er,withDiagnosticsScope as ea,resolveDaemonPaths as en,flushDiagnosticsToSessionFile as eo,resolveDaemonServerMode as es,serializeInstallFromSourceResult as ei,createAgentDevice as el,stopProcessForTakeover as ec,formatSnapshotLine as eu}from"./641.js";import{runCmdDetached as ed,runCmdSync as ep,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 eI,ENV_STATE_PATH as ek,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 ex}from"./320.js";import{maybeRunUpgradeNotifier as eN}from"./113.js";function eP(e,t){for(let[r,a]of Object.entries(t))void 0!==a&&(e[r]=a);return e}let eL=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],e_=["snapshotDepth","snapshotScope","snapshotRaw"],eE=[{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:I,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:"quality",names:["--quality"],type:"int",min:5,max:10,usageLabel:"--quality <5-10>",usageDescription:"Record: scale recording resolution from 5 (50%) through 10 (native resolution)"},{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)"}],eM=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"]),eR={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 and save remote session state",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:[...e_]},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",...e_]},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:[...e_]},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",...e_]},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:[...e_,"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>] [--quality <5-10>] [--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","quality","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:[...e_]},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}},eT=new Map,eC=new Map;for(let e of eE){for(let t of e.names)eT.set(t,e);let t=eC.get(e.key);t?t.push(e):eC.set(e.key,[e])}function eO(e){if(e)return eR[e]}function eU(){return Object.keys(eR)}function eF(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let ej=(e=`agent-device <command> [args] [--json]
2
2
 
3
3
  CLI to control iOS and Android devices for AI agents.
4
- `,t=eG("Commands:",eU().map(e=>{let t=eR[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 a,n,o;let s,i,l,c;return a=e,n=t,i=(s=(o=r).endsWith("?"))?o.slice(0,-1):o,c=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==n.usageOverride&&n.usageOverride.startsWith(`${a} ${i}`),s?l?`[${i}]`:c?i:`[${i}]`:c?i:`<${i}>`});return[e,...r].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),r=eB("Flags:",eV(eM)),a=[eG("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"),n=eq("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),o=eG("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"}]),s=eq("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=eG("Commands:",eU().map(e=>{let t=eR[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 a,n,o;let s,i,l,c;return a=e,n=t,i=(s=(o=r).endsWith("?"))?o.slice(0,-1):o,c=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==n.usageOverride&&n.usageOverride.startsWith(`${a} ${i}`),s?l?`[${i}]`:c?i:`[${i}]`:c?i:`<${i}>`});return[e,...r].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),r=eV("Flags:",eB(eM)),a=[eG("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"),n=eq("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),o=eG("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"}]),s=eq("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,48 +13,48 @@ ${n}
13
13
  ${o}
14
14
 
15
15
  ${s}
16
- `);function eV(e){return eE.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function eB(e,t){return eG(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function eG(e,t){if(0===t.length)return`${e}
16
+ `);function eB(e){return eE.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function eV(e,t){return eG(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function eG(e,t){if(0===t.length)return`${e}
17
17
  (none)`;let r=Math.max(...t.map(e=>e.label.length))+2,a=[e];for(let e of t)a.push(` ${e.label.padEnd(r)}${e.description}`);return a.join("\n")}function eq(e,t){return 0===t.length?`${e}
18
- (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let eH=new Set(["1","true","yes","on"]),eJ=new Set(["0","false","no","off"]);function eK(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function ez(e,t,r,a){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>ez({...e,multiple:!1},t,r,a));if("boolean"===e.type){var n=t,o=r,s=a;if("boolean"==typeof n)return n;if("string"==typeof n){let e=eW(n);if(void 0!==e)return e}throw new eg("INVALID_ARGS",`Invalid value for "${s}" in ${o}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==eW(t))return eW(t);if("string"==typeof t&&t.trim().length>0)return t;throw new eg("INVALID_ARGS",`Invalid value for "${a}" 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 "${a}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var i=e,l=t,c=r,u=a;let n=i.setValue;if(l===n)return n;if("string"==typeof l){let e=l.trim();if(""===e||"true"===e||"1"===e)return n;if("false"===e||"0"===e)return}if(!0===l)return n;if(!1!==l)throw new eg("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 eg("INVALID_ARGS",`Invalid value for "${a}" 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 "${a}" in ${r}. Expected integer.`);if("number"==typeof e.min&&p<e.min)throw new eg("INVALID_ARGS",`Invalid value for "${a}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&p>e.max)throw new eg("INVALID_ARGS",`Invalid value for "${a}" in ${r}. Must be <= ${e.max}.`);return p}function eW(e){let t=e.trim().toLowerCase();return!!eH.has(t)||!eJ.has(t)&&void 0}let eX=new Set(["config","remoteConfig","help","version","batchSteps"]),eY={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eZ=function(){let e=new Map;for(let t of eE){let r=e.get(t.key);r?r.push(t):e.set(t.key,[t])}let t=new Map;for(let e of eM)t.set(e,new Set(["*"]));for(let e of eU()){let r=eC(e);if(r)for(let a of r.allowedFlags){let r=t.get(a);r&&r.has("*")||(r?r.add(e):t.set(a,new Set([e])))}}return[...e.entries()].map(([e,r])=>({key:e,flagDefinitions:r,config:{enabled:!eX.has(e),key:e},env:{names:[eK(e),...eY[e]??[]]},supportsCommand(r){let a=t.get(e);return!!a&&(!!a.has("*")||!!r&&a.has(r))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),eQ=new Map(eZ.map(e=>[e.key,e]));function e0(e,t){return eQ.get(e)?.supportsCommand(t)??!1}function e1(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 e2(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function e3(e){return e.replace(/^-+/,"")}function e5(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?e2(e):[e,void 0];return void 0!==eT.get(t)}function e8(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function e4(e){process.stdout.write(`${JSON.stringify(e,null,2)}
18
+ (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let eH=new Set(["1","true","yes","on"]),eK=new Set(["0","false","no","off"]);function eJ(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function ez(e,t,r,a){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>ez({...e,multiple:!1},t,r,a));if("boolean"===e.type){var n=t,o=r,s=a;if("boolean"==typeof n)return n;if("string"==typeof n){let e=eW(n);if(void 0!==e)return e}throw new eg("INVALID_ARGS",`Invalid value for "${s}" in ${o}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==eW(t))return eW(t);if("string"==typeof t&&t.trim().length>0)return t;throw new eg("INVALID_ARGS",`Invalid value for "${a}" 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 "${a}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var i=e,l=t,c=r,u=a;let n=i.setValue;if(l===n)return n;if("string"==typeof l){let e=l.trim();if(""===e||"true"===e||"1"===e)return n;if("false"===e||"0"===e)return}if(!0===l)return n;if(!1!==l)throw new eg("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 eg("INVALID_ARGS",`Invalid value for "${a}" 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 eg("INVALID_ARGS",`Invalid value for "${a}" in ${r}. Expected integer.`);if("number"==typeof e.min&&d<e.min)throw new eg("INVALID_ARGS",`Invalid value for "${a}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&d>e.max)throw new eg("INVALID_ARGS",`Invalid value for "${a}" in ${r}. Must be <= ${e.max}.`);return d}function eW(e){let t=e.trim().toLowerCase();return!!eH.has(t)||!eK.has(t)&&void 0}let eX=new Set(["config","remoteConfig","help","version","batchSteps"]),eY={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eZ=function(){let e=new Map;for(let t of eE){let r=e.get(t.key);r?r.push(t):e.set(t.key,[t])}let t=new Map;for(let e of eM)t.set(e,new Set(["*"]));for(let e of eU()){let r=eO(e);if(r)for(let a of r.allowedFlags){let r=t.get(a);r&&r.has("*")||(r?r.add(e):t.set(a,new Set([e])))}}return[...e.entries()].map(([e,r])=>({key:e,flagDefinitions:r,config:{enabled:!eX.has(e),key:e},env:{names:[eJ(e),...eY[e]??[]]},supportsCommand(r){let a=t.get(e);return!!a&&(!!a.has("*")||!!r&&a.has(r))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),eQ=new Map(eZ.map(e=>[e.key,e]));function e0(e,t){return eQ.get(e)?.supportsCommand(t)??!1}function e1(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 e2(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function e3(e){return e.replace(/^-+/,"")}function e5(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?e2(e):[e,void 0];return void 0!==eT.get(t)}function e8(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function e4(e){process.stdout.write(`${JSON.stringify(e,null,2)}
19
19
  `)}function e6(e,t={}){let r=e instanceof eg?ef(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 e7(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function e9(e){return e>0?`+${e}`:String(e)}function te(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:"",r=e.regionIndex?` r${e.regionIndex}`:"";return`${e.likelyKind}${t}${r}`}function tt(e){return e.min===e.max?e9(e.min):`${e9(e.min)}..${e9(e.max)}`}function tr(e){let t=process.cwd(),r=i.relative(t,e);return""!==r&&(r.startsWith("..")||i.isAbsolute(r))?e:""===r?".":`.${i.sep}${r}`}function ta(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function tn(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function to(e,t){return t?l("dim",e):e}function ts(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function ti(e){var t;let r="scroll-area"===(t=e.type)||"list"===t||"collection"===t||"table"===t?t:null;if(!r)return[];let a=[];if(e.node.hiddenContentAbove&&a.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&a.push(`[content below ${r} hidden]`),0===a.length)return[];let n=" ".repeat(e.depth+1);return a.map(e=>`${n}${e}`)}let tl="sha256";async function tc(e){let t=await tu(e.localPath,e.platform),r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let a=await tf({normalizedBase:r,token:e.token,artifact:t});if(a?.kind==="cache-hit")return a.uploadId;if(a?.kind==="direct-upload")try{return await th(t.payloadPath,a),await ty({normalizedBase:r,token:e.token,uploadId:a.uploadId})}catch{}return await tm({normalizedBase:r,token:e.token,artifact:t})}finally{t.cleanup()}}async function tu(e,t){var r,a,n;let o,s=f.statSync(e),l=i.basename(e),c=s.isDirectory(),u=("ios"===(r=t)||"android"===r?r:void 0)??(a=e,n=s,o=a.toLowerCase(),n.isDirectory()&&o.endsWith(".app")||o.endsWith(".ipa")?"ios":o.endsWith(".apk")||o.endsWith(".aab")?"android":void 0),p=[];try{let t=c?await tp(e,p):e,r=f.statSync(t);return{payloadPath:t,fileName:l,artifactType:c?"app-bundle":"file",platform:u,contentType:c?"application/gzip":"application/octet-stream",sha256:await tw(t),sizeBytes:r.size,cleanup:()=>td(p)}}catch(e){throw td(p),e}}async function tp(e,t){let r=f.mkdtempSync(i.join(g.tmpdir(),`agent-device-upload-${b()}-`));t.push(r);let a=i.join(r,`${i.basename(e)}.tar.gz`);return await eh("tar",["czf",a,"-C",i.dirname(e),i.basename(e)]),a}function td(e){for(let t of e)f.rmSync(t,{recursive:!0,force:!0})}async function tm(e){let{normalizedBase:t,token:r,artifact:a}=e,n=new URL("upload",t),o={"content-type":a.contentType,"x-artifact-type":a.artifactType,"x-artifact-filename":a.fileName,"x-artifact-hash":a.sha256,"x-artifact-hash-algorithm":tl,"transfer-encoding":"chunked"};r&&(o.authorization=`Bearer ${r}`,o["x-agent-device-token"]=r);let s=await tg({url:n,method:"POST",headers:o,payloadPath:a.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(s.body);if(!e.ok||!e.uploadId)throw new eg("COMMAND_FAILED",`Upload failed: ${s.body}`);return e.uploadId}catch(e){if(e instanceof eg)throw e;throw new eg("COMMAND_FAILED",`Invalid upload response: ${s.body}`)}}async function tf(e){let t=new URL("upload/preflight",e.normalizedBase),r={"content-type":"application/json"};e.token&&(r.authorization=`Bearer ${e.token}`,r["x-agent-device-token"]=e.token);let a=await fetch(t,{method:"POST",headers:r,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(a?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let r=e.upload;if(!r||"string"!=typeof r.url)return;let a=r.headers??{};if(!(!(t=a)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:r.url,headers:a}}(await a.json().catch(()=>void 0))}async function th(e,t){let r=await tg({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(r.statusCode<200||r.statusCode>=300)throw new eg("COMMAND_FAILED","Direct artifact upload failed",{statusCode:r.statusCode,statusMessage:r.statusMessage})}async function tg(e){let t="https:"===e.url.protocol?m:d;return await new Promise((r,a)=>{let n=t.request({protocol:e.url.protocol,host:e.url.hostname,port:e.url.port,method:e.method,path:e.url.pathname+e.url.search,headers:e.headers},e=>{let t="";e.setEncoding("utf8"),e.on("data",e=>{t+=e}),e.on("end",()=>{clearTimeout(o),r({statusCode:e.statusCode??500,statusMessage:e.statusMessage,body:t})})}),o=setTimeout(()=>{n.destroy(),a(new eg("COMMAND_FAILED",e.timeoutMessage,{timeoutMs:3e5,...e.timeoutHint?{hint:e.timeoutHint}:{}}))},3e5);n.on("error",t=>{clearTimeout(o),a(new eg("COMMAND_FAILED",e.errorMessage,e.errorHint?{hint:e.errorHint}:{},t))}),n.on("close",()=>clearTimeout(o));let s=f.createReadStream(e.payloadPath);s.pipe(n),s.on("error",e=>{n.destroy(),a(new eg("COMMAND_FAILED","Failed to read local artifact",{},e))})})}async function ty(e){let t=new URL("upload/finalize",e.normalizedBase),r={"content-type":"application/json"};e.token&&(r.authorization=`Bearer ${e.token}`,r["x-agent-device-token"]=e.token);let a=await fetch(t,{method:"POST",headers:r,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new eg("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!a.ok)throw new eg("COMMAND_FAILED","Direct artifact upload finalize failed",{status:a.status,statusText:a.statusText});let n=await a.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new eg("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function tw(e){let t=w(tl);return await new Promise((r,a)=>{f.createReadStream(e).on("data",e=>t.update(e)).on("error",e=>{a(new eg("COMMAND_FAILED","Failed to read local artifact",{},e))}).on("end",r)}),t.digest("hex")}let tb=tQ(),tv=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}(),tI=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}(),tk=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],tA=new p.BlockList;async function tD(e){let t=e.meta?.requestId??q(),r=!!(e.meta?.debug||e.flags?.verbose),a=function(e){let t,r=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,a=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),n=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var o=a,s=n;if(!(!o||"localhost"===(t=new URL(o).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(p.isIPv4(t)?tA.check(t,"ipv4"):!!p.isIPv6(t)&&tA.check(t,"ipv6")))&&("string"!=typeof s||!(s.trim().length>0)))throw new eg("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:o,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let i=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,l=E(i);if(a&&"socket"===l)throw new eg("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:a});let c=es(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===i?"dual":void 0));return{paths:en(r),transportPreference:l,serverMode:c,remoteBaseUrl:a,remoteAuthToken:n}}(e),n=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return tQ(t)}(e.command),o=await X("daemon_startup",async()=>await tL(a),{requestId:t,session:e.session}),s=await tS(e,o),i={...e,positionals:s.positionals,flags:s.flags,token:o.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,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};return Q({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await X("daemon_request",async()=>await tB(o,i,a.transportPreference,n),{requestId:t,command:e.command})}async function tS(e,t){let r,a=[...e.positionals??[]],n=e.flags?{...e.flags}:void 0,o=e.meta?.installSource,s={};if(tW(t)){let l=function(e,t){if("screenshot"===e.command){let r=tx(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:tN("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:tN("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=tx(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:tN("recording",i.extname(t)||".mp4")}}return null}(e,a);l&&(void 0!==l.positionalPath&&(a[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((n??={}).out=l.flagPath),s[l.field]=l.localPath);let c=await t$(e,t);c&&(o=c.installSource,r=c.uploadedArtifactId??r)}if(!tW(t)||"install"!==e.command&&"reinstall"!==e.command||a.length<2)return{positionals:a,flags:n,installSource:o,uploadedArtifactId:r,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let l=a[1];if(l.startsWith("remote:"))return a[1]=l.slice(7),{positionals:a,flags:n,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let c=i.isAbsolute(l)?l:i.resolve(e.meta?.cwd??process.cwd(),l);return f.existsSync(c)?{positionals:a,flags:n,installSource:o,uploadedArtifactId:r=await tc({localPath:c,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform}),...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}:{positionals:a,flags:n,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}}async function t$(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let a=r.path.trim();if(!a)return{installSource:r};if(a.startsWith("remote:"))return{installSource:{...r,path:a.slice(7)}};let n=i.isAbsolute(a)?a:i.resolve(e.meta?.cwd??process.cwd(),a);if(!f.existsSync(n))return{installSource:{...r,path:n}};let o=await tc({localPath:n,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform});return{installSource:{...r,path:n},uploadedArtifactId:o}}function tx(e,t,r,a=0){let n=e.positionals?.[a]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,s=n&&n.trim().length>0?n:o;return i.isAbsolute(s)?s:i.resolve(e.meta?.cwd??process.cwd(),s)}function tN(e,t){let r=t.startsWith(".")?t:`.${t}`;return i.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function tL(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await tF(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=tR(e.paths.infoPath),a=J(),n=_((t=tV()).useSrc?t.srcPath:t.distPath,t.root),o=!!r&&await tF(r,e.transportPreference);if(r&&r.version===a&&r.codeSignature===n&&o)return r;r&&(r.version!==a||r.codeSignature!==n||!o)&&(await tM(r),tU(e.paths.infoPath)),function(e){let t=tO(e);if(!t.hasLock||t.hasInfo)return;let r=tT(e.lockPath);if(!r)return tU(e.lockPath);$(r.pid,r.processStartTime)||tU(e.lockPath)}(e.paths);let s=0;for(let t=1;t<=tI;t+=1){await tj(e);let r=await tP(tv,e);if(r)return r;if(await tE(e.paths)){s+=1;continue}let a=tO(e.paths);if(!(t<tI))break;if(!a.hasInfo&&!a.hasLock){await t_(150);continue}}let i=tO(e.paths);throw new eg("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:tv,startupAttempts:tI,lockRecoveryCount:s,metadataState:i,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.`}(i,e.paths)})}async function tP(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=tR(t.paths.infoPath);if(e&&await tF(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function t_(e){await new Promise(t=>setTimeout(t,e))}async function tE(e){let t=tO(e);if(!t.hasLock||t.hasInfo)return!1;let r=tT(e.lockPath);return r&&$(r.pid,r.processStartTime)&&await ec(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),tU(e.lockPath),!0}async function tM(e){await ec(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function tR(e){let t=tC(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 a=Number.isInteger(t.port)&&Number(t.port)>0,n=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!a&&!n)return null;let o=t.transport,s="string"==typeof t.version?t.version:void 0,i="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:a?Number(t.port):void 0,httpPort:n?Number(t.httpPort):void 0,transport:"socket"===o||"http"===o||"dual"===o?o:void 0,pid:c?Number(t.pid):0,version:s,codeSignature:i,processStartTime:l}}function tT(e){let t=tC(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}tA.addSubnet("127.0.0.0",8,"ipv4"),tA.addAddress("::1","ipv6"),tA.addSubnet("::ffff:127.0.0.0",104,"ipv6");function tO(e){return{hasInfo:f.existsSync(e.infoPath),hasLock:f.existsSync(e.lockPath)}}function tC(e){if(!f.existsSync(e))return null;try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}}function tU(e){try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}async function tF(e,t){var r;return"http"===tG(e,t)?await function(e){let t=e.baseUrl?tX(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),a="https:"===r.protocol?m:d,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=a.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:n},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 tj(e){let t=tV(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],a={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};ep(process.execPath,r,{env:a})}function tV(){let e=z(),t=i.join(e,"dist","src","daemon.js"),r=i.join(e,"src","daemon.ts"),a=f.existsSync(t),n=f.existsSync(r);if(!a&&!n)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")?n:!a&&n}}async function tB(e,t,r,a){return"http"===tG(e,r)?await tz(e,t,a):await tK(e,t,a)}function tG(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,a=t;if(tq(r,a))return a;throw new eg("COMMAND_FAILED","http"===a?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tq(e,t));if(n)return n;throw new eg("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tq(e,t){return"http"===t?!!e.httpPort:!!e.port}function tH(e,t,r,a,n,o){let s=n?{terminated:0}:function(){let e=0;try{for(let t of tk){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)}}}(),i=n?{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{tU(t.infoPath),tU(t.lockPath)}return{forcedKill:r}}(e,t);return Q({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:o,requestId:r,command:a,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:n?void 0:e.pid,daemonPidForceKilled:n?void 0:i.forcedKill,daemonBaseUrl:e.baseUrl}}),new eg("COMMAND_FAILED","Daemon request timed out",{timeoutMs:o,requestId:r,hint:n?"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 tJ(e,t,r){return Q({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 tK(e,t,r){let a=e.port;if(!a)throw new eg("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((n,o)=>{let s=p.createConnection({host:"127.0.0.1",port:a},()=>{s.write(`${JSON.stringify(t)}
25
- `)}),i=en(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{s.destroy(),o(tH(e,i,t.meta?.requestId,t.command,!1,r))},r):void 0,c="";s.setEncoding("utf8"),s.on("data",e=>{let r=(c+=e).indexOf("\n");if(-1===r)return;let a=c.slice(0,r).trim();if(a)try{let e=JSON.parse(a);s.end(),l&&clearTimeout(l),n(e)}catch(e){l&&clearTimeout(l),o(new eg("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:a},e instanceof Error?e:void 0))}}),s.on("error",e=>{l&&clearTimeout(l),o(tJ(e,t.meta?.requestId,!1))})})}async function tz(e,t,r){var a,n,o;let s,i=e.baseUrl?new URL(tX(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!i)throw new eg("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let l=JSON.stringify((a=t,n={includeTokenParam:!e.baseUrl},s=a.meta?.requestId??q(),"lease_allocate"!==(o=a.command)&&"lease_heartbeat"!==o&&"lease_release"!==o?{jsonrpc:"2.0",id:s,method:"agent_device.command",params:a}:{jsonrpc:"2.0",id:s,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"}}(a.command),params:function(e,t,r){let a={...r.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...a,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...a,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...a,leaseId:e.meta?.leaseId}}}(a,a.command,n)})),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((a,n)=>{let o=en(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),s=("https:"===i.protocol?m:d).request({protocol:i.protocol,host:i.hostname,port:i.port,method:"POST",path:i.pathname+i.search,headers:c},r=>{let o="";r.setEncoding("utf8"),r.on("data",e=>{o+=e}),r.on("end",()=>{p&&clearTimeout(p);try{let r=JSON.parse(o);if(r.error){let e=r.error.data??{};n(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 n(new eg("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void tY(e,t,r.result).then(a).catch(n);a(r.result)}catch(e){p&&clearTimeout(p),n(new eg("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:o},e instanceof Error?e:void 0))}})}),u=tW(e),p="number"==typeof r?setTimeout(()=>{s.destroy(),n(tH(e,o,t.meta?.requestId,t.command,u,r))},r):void 0;s.on("error",e=>{p&&clearTimeout(p),n(tJ(e,t.meta?.requestId,u))}),s.write(l),s.end()})}function tW(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function tX(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function tY(e,t,r){let a=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===a.length||!e.baseUrl)return r;let n=r.data?{...r.data}:{},o=[];for(let r of a){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){o.push(r);continue}let a=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return i.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await tZ({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:a,requestId:t.meta?.requestId}),n[r.field]=a,o.push({...r,localPath:a})}return n.artifacts=o,{ok:!0,data:n}}async function tZ(e){var t,r;let a,n=new URL((t=e.baseUrl,r=e.artifactId,a=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,a).toString())),o="https:"===n.protocol?m:d;await f.promises.mkdir(i.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let a=!1,s=e.timeoutMs??tb,i=n=>{if(!a){if(a=!0,clearTimeout(c),n)return void f.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(n));t()}},l=o.request({protocol:n.protocol,host:n.hostname,port:n.port,method:"GET",path:n.pathname+n.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",()=>{i(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=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new eg("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),c=setTimeout(()=>{l.destroy(new eg("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:s}))},s);l.on("error",t=>{t instanceof eg?i(t):i(new eg("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:s},t instanceof Error?t:void 0))}),l.end()})}function tQ(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 t0="metro-companion";function t1(e){return w("sha256").update(e).digest("hex")}function t2(e){return e?.trim()?e.trim():void 0}function t3(e,t){let r=i.join(e,".agent-device");if(!t)return{statePath:i.join(r,"metro-companion.json"),logPath:i.join(r,"metro-companion.log")};let a=t1(t).slice(0,12),n=i.join(r,t0);return{statePath:i.join(n,`metro-companion-${a}.json`),logPath:i.join(n,`metro-companion-${a}.log`)}}function t5(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:t2("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 t8(e,t){f.mkdirSync(i.dirname(e),{recursive:!0}),f.writeFileSync(e,`${JSON.stringify(t,null,2)}
26
- `,"utf8")}function t4(e){try{let t=f.readdirSync(e);0===t.length&&f.rmdirSync(e)}catch{}}function t6(e){let t=i.dirname(e.statePath),r=i.dirname(e.logPath);var a=e.statePath;try{f.unlinkSync(a)}catch{}var n=e.logPath;try{f.unlinkSync(n)}catch{}t4(t),r!==t&&t4(r),i.basename(t)===t0&&t4(i.dirname(t))}function t7(e){return e.includes(ey)}function t9(e){return t2(e.consumerKey)??t2(e.profileKey)??null}function re(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function rt(e){if(!et(e.pid))return;let t=k(e.pid);if(t&&t7(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 rr(e){let t=t9(e),r=t3(e.projectRoot,e.profileKey),a=t5(r.statePath);if(a&&function(e,t){var r,a;if(!et(e.pid))return!1;if(e.startTime){let t=er(e.pid);if(!t||t!==e.startTime)return!1}let n=k(e.pid);return!!n&&!!t7(n)&&!!e.bridgeScope&&e.serverBaseUrl===ew(t.serverBaseUrl)&&e.localBaseUrl===ew(t.localBaseUrl)&&e.launchUrl===t2(t.launchUrl)&&(r=e.bridgeScope,a=t.bridgeScope,r.tenantId===a.tenantId&&r.runId===a.runId&&r.leaseId===a.leaseId)&&e.tokenHash===t1(t.bearerToken)}(a,e)){let e=re(a,t);return e!==a&&t8(r.statePath,e),{pid:a.pid,spawned:!1,statePath:r.statePath,logPath:r.logPath}}a&&(await rt(a),t6(r));let n=function(e,t){let r=function(){let e=c(import.meta.url),t=i.extname(e)||".js",r=i.join(i.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}(),a=r.endsWith(".ts")?["--experimental-strip-types"]:[];f.mkdirSync(i.dirname(t),{recursive:!0});let n=f.openSync(t,"a"),o=0;try{let t;o=ep(process.execPath,[...a,r,ey],{env:((t={...e.env??process.env,[ev]:ew(e.serverBaseUrl),[e$]:e.bearerToken,[eI]:ew(e.localBaseUrl),[ek]:t3(e.projectRoot,e.profileKey).statePath})[eD]=e.bridgeScope.tenantId,t[eS]=e.bridgeScope.runId,t[ex]=e.bridgeScope.leaseId,e.launchUrl?.trim()?t[eA]=e.launchUrl.trim():delete t[eA],t),stdio:["ignore",n,n]})}finally{f.closeSync(n)}if(!Number.isInteger(o)||o<=0)throw Error("Failed to start Metro companion process.");return{pid:o,startTime:er(o)??void 0,command:k(o)??void 0,serverBaseUrl:ew(e.serverBaseUrl),localBaseUrl:ew(e.localBaseUrl),launchUrl:t2(e.launchUrl),bridgeScope:e.bridgeScope,tokenHash:t1(e.bearerToken),consumers:[]}}(e,r.logPath);return t8(r.statePath,re(n,t)),{pid:n.pid,spawned:!0,statePath:r.statePath,logPath:r.logPath}}async function ra(e){let t=t9(e),r=t3(e.projectRoot,e.profileKey),a=t5(r.statePath);if(!a)return t6(r),{stopped:!1,statePath:r.statePath};let n=t?{...a,consumers:a.consumers.filter(e=>e!==t)}:{...a,consumers:[]};return n.consumers.length>0?(t8(r.statePath,n),{stopped:!1,statePath:r.statePath}):(await rt(a),t6(r),{stopped:!0,statePath:r.statePath})}function rn(e){return"string"==typeof e&&e.trim()?ew(e.trim()):""}function ro(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function rs(e,t,r){return Y(e,{env:t,cwd:r})}function ri(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}function rl(e,t,r){if(null==e||""===e)return t;let a=Number.parseInt(String(e),10);return Number.isInteger(a)?Math.max(a,r):t}function rc(e,t){return{platform:t,bundleUrl:eb(e,t)}}function ru(e,t){return{platform:t,metroHost:ro(e?.metro_host),metroPort:e?.metro_port,bundleUrl:ro(e?.metro_bundle_url),launchUrl:ro(e?.launch_url)}}async function rp(e){await new Promise(t=>setTimeout(t,e))}async function rd(e,t,r={}){try{let a=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:a.ok,status:a.status,body:await a.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function rm(e,t){try{let r=await rd(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function rf(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 rh(e,t){let r=Error(e);return r.retryable=t,r}function rg(e,t){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(t).includes("Metro companion is not connected"))}function ry(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function rw(e){let t;try{var r,a;t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(r=e.baseUrl,a=e.bearerToken,{Authorization:`Bearer ${a}`,"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 rh(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw rh(t instanceof Error?t.message:String(t),!0)}let n=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(o){let a=e.slice(0,200),n=o instanceof Error?o.message:String(o);throw rh(`/api/metro/bridge returned invalid JSON (${t}) from ${r}: ${n}. body=${JSON.stringify(a)}`,rg(t,e))}}(await t.text(),t.status,e.baseUrl);if(!t.ok)throw rh(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(n)}`,rg(t.status,n));var o=n;let s=o.data??o;if(!s||"object"!=typeof s||Array.isArray(s))throw rh("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:s.enabled,baseUrl:s.base_url,statusUrl:s.status_url??"",bundleUrl:s.bundle_url??"",iosRuntime:ru(s.ios_runtime,"ios"),androidRuntime:ru(s.android_runtime,"android"),upstream:{bundleUrl:s.upstream.bundle_url??"",host:s.upstream.host??"",port:s.upstream.port??0,statusUrl:s.upstream.status_url??""},probe:{reachable:s.probe.reachable,statusCode:s.probe.status_code,latencyMs:s.probe.latency_ms,detail:s.probe.detail}}}catch(e){throw rh(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function rb(e,t,r,a,n){let o=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&o.push(`bridgeError=${t}`),r?.probe.reachable===!1&&o.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),a&&a!==t&&o.push(`initialBridgeError=${a}`),n&&o.push(`metroCompanionLog=${n}`),o.join(" ")}async function rv(e,t,r){let a=Date.now()+t;for(;Date.now()<a;){let t=Math.min(r,Math.max(a-Date.now(),1));if(await rm(e,t))return!0;let n=Math.min(500,Math.max(a-Date.now(),0));n>0&&await rp(n)}return!1}async function rI(e){let t=Date.now()+e.startupTimeoutMs,r=null,a=null;for(;Date.now()<t;){try{let t=await rw({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,a=null}catch(e){if(a=e instanceof Error?e.message:String(e),!ry(e))break}let n=Math.min(1e3,Math.max(t-Date.now(),0));n>0&&await rp(n)}throw Error(rb(e.baseUrl,a,r,e.initialBridgeError,e.companionLogPath))}async function rk(e={}){let t=e.env??process.env,r=process.cwd(),a=rs(e.projectRoot??r,t,r),n=function(e,t){if("auto"!==t)return t;let r=function(e){let t=i.join(e,"package.json");if(!ri(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"}(a,e.kind??"auto"),o=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),s=ro(e.listenHost)??"0.0.0.0",l=ro(e.statusHost)??"127.0.0.1",c=rn(e.publicBaseUrl),u=rl(e.startupTimeoutMs,18e4,3e4),p=rl(e.probeTimeoutMs,1e4,1e3),d=e.reuseExisting??!0,m=e.installDependenciesIfNeeded??!0,h=e.runtimeFilePath?rs(e.runtimeFilePath,t,r):null,g=rs(e.logPath??i.join(a,".agent-device","metro.log"),t,r);if(!c)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}}(rn(e.proxyBaseUrl),ro(e.proxyBearerToken)??""),v=y?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new eg("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}}(i.join(e,"node_modules")))return{installed:!1};let r=ri(i.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:ri(i.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}}(a,t):{installed:!1},k=`http://${l}:${o}/status`,A=!1,D=!1,S=0;if(d&&await rm(k,p))D=!0;else if(A=!0,S=function(e,t,r,a,n,o){let s="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",a,"--port",String(r)]};f.mkdirSync(i.dirname(n),{recursive:!0});let l=f.openSync(n,"a"),c=0;try{c=ep(s.command,s.installArgs,{cwd:e,env:o,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}}(a,n,o,s,g,t).pid,!await rv(k,u,p))throw await rf(S).catch(()=>{}),Error(`Metro did not become ready at ${k} within ${u}ms. Check ${g}.`);let $=rc(c,"ios"),x=rc(c,"android"),N=null,L=null;if(v)try{N=await rw({baseUrl:w,bearerToken:b,scope:v,runtime:{metro_bundle_url:$.bundleUrl},timeoutMs:p})}catch(e){if(!ry(e))throw e;L=e instanceof Error?e.message:String(e)}if(v&&(!N||!1===N.probe.reachable)){let r;try{r=(await rr({projectRoot:a,serverBaseUrl:w,bearerToken:b,bridgeScope:v,localBaseUrl:`http://${l}:${o}`,launchUrl:ro(e.launchUrl),profileKey:ro(e.companionProfileKey),consumerKey:ro(e.companionConsumerKey),env:t})).logPath}catch(e){throw Error(rb(w,e instanceof Error?e.message:String(e),N,L))}try{N=await rI({baseUrl:w,bearerToken:b,scope:v,runtime:{metro_bundle_url:$.bundleUrl},probeTimeoutMs:p,startupTimeoutMs:u,initialBridgeError:L,companionLogPath:r})}catch(e){throw e instanceof Error?e:Error(String(e))}}let P=N?.iosRuntime??$,_=N?.androidRuntime??x,E={projectRoot:a,kind:n,dependenciesInstalled:I.installed,packageManager:I.packageManager??null,started:A,reused:D,pid:S,logPath:g,statusUrl:k,runtimeFilePath:h,iosRuntime:P,androidRuntime:_,bridge:N};return h&&(f.mkdirSync(i.dirname(h),{recursive:!0}),f.writeFileSync(h,JSON.stringify(E,null,2))),E}let rA="alert",rD="appstate",rS="app-switcher",r$="apps",rx="back",rN="batch",rL="boot",rP="click",r_="clipboard",rE="devices",rM="diff",rR="fill",rT="find",rO="focus",rC="home",rU="keyboard",rF="logs",rj="longpress",rV="network",rB="perf",rG="pinch",rq="press",rH="push",rJ="record",rK="replay",rz="rotate",rW="scroll",rX="screenshot",rY="settings",rZ="snapshot",rQ="swipe",r0="test",r1="trace",r2="trigger-app-event",r3="type",r5="wait";function r8(e,t,r,a){let n=r(e[t]);if(void 0===n)throw new eg("COMMAND_FAILED",a,{response:e});return n}function r4(e,t){return r8(e,t,ar,`Daemon response is missing "${t}".`)}function r6(e,t){return ar(e[t])}function r7(e,t){var r;let a;return r=ar,null===(a=e[t])?null:r(a)}function r9(e,t){return r8(e,t,an,`Daemon response has invalid "${t}".`)}function ae(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function at(e,t){let r=e[t];if(!ai(r))return;let a="number"==typeof r.x?r.x:void 0,n="number"==typeof r.y?r.y:void 0,o="number"==typeof r.width?r.width:void 0,s="number"==typeof r.height?r.height:void 0;if(void 0!==a&&void 0!==n&&void 0!==o&&void 0!==s)return{x:a,y:n,width:o,height:s}}function ar(e){return"string"==typeof e&&e.length>0?e:void 0}function aa(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function an(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function ao(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function as(e){if(!ai(e))throw new eg("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function ai(e){return"object"==typeof e&&null!==e}function al(e){let t={};for(let[r,a]of Object.entries(e))void 0!==a&&(t[r]=a);return t}function ac(e,t){let r=r6(e,"bundleId"),a=r6(e,"package");return{app:r4(e,"app"),appPath:r4(e,"appPath"),platform:r9(e,"platform"),appId:r??a,bundleId:r,package:a,identifiers:N({session:t,bundleId:r,packageName:a})}}function au(e){let t=as(e),r=r9(t,"platform"),a=r4(t,"id"),n=r4(t,"name");return{platform:r,target:ae(t,"target"),kind:r8(t,"kind",ao,'Daemon response has invalid "kind".'),id:a,name:n,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:x(r,a,n),ios:"ios"===r?{udid:a}:void 0,android:"android"===r?{serial:a}:void 0}}function ap(e){let t=as(e),r=r9(t,"platform"),a=r4(t,"id"),n=r4(t,"name"),o=ae(t,"target"),s=r4(t,"device"),i={session:n,...x(r,a,s)};return{name:n,createdAt:r8(t,"createdAt",aa,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:o,id:a,name:s,identifiers:i,ios:"ios"===r?{udid:a,simulatorSetPath:r7(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:a}:void 0},identifiers:i}}function ad(e){return e??"default"}function am(e){return void 0!==e.ref?[e.ref,...af(e.label)]:void 0!==e.selector?[e.selector]:[String(e.x),String(e.y)]}function af(e){return void 0===e?[]:[e]}function ah(e){return void 0===e?[]:[String(e)]}function ag(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:r4(t,"leaseId"),tenantId:r4(t,"tenantId"),runId:r4(t,"runId"),backend:r4(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 ay(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function aw(e,t,r){var a;if(e.json)return void e4({success:!0,data:t});let n=r?.();n&&(a=n,process.stdout.write(a.endsWith("\n")?a:`${a}
27
- `))}function ab(e,t){aw(e,t,()=>U(t))}let av=async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new eg("INVALID_ARGS","session only supports list");let a={sessions:(await r.sessions.list()).map(D)};return aw(t,a,()=>JSON.stringify(a,null,2)),!0},aI=async({flags:e,client:t})=>{let r=await t.devices.list(ay(e));return aw(e,{devices:r.map(V)},()=>r.map(ak).join("\n")),!0};function ak(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",a="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${a}`}let aA=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 aw(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},aD=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 a=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 aw(t,a,()=>JSON.stringify(a,null,2)),!0},aS=async({flags:e,client:t})=>{let r=await t.apps.list({...ay(e),appsFilter:e.appsFilter});return aw(e,{apps:r},()=>r.join("\n")),!0},a$=async({positionals:e,flags:t,client:r})=>{let a=C(await aL("install",e,t,r));return ab(t,a),!0},ax=async({positionals:e,flags:t,client:r})=>{let a=C(await aL("reinstall",e,t,r));return ab(t,a),!0},aN=async({positionals:e,flags:t,client:r})=>{let a=ei(await aP(e,t,r));return ab(t,a),!0};async function aL(e,t,r,a){let n=t[0],o=t[1];if(!n||!o)throw new eg("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let s={app:n,appPath:o,...ay(r)};return"install"===e?await a.apps.install(s):await a.apps.reinstall(s)}async function aP(e,t,r){let a=e[0]?.trim();if(!a)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({...ay(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:a,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 a=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!a)throw new eg("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[a]=n}return t}(t.header)}})}let a_=async({positionals:e,flags:t,client:r})=>{let a=R(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,...ay(t)}));return ab(t,a),!0},aE=async({positionals:e,flags:t,client:r})=>{let a=Z(e[0]?await r.apps.close({app:e[0],shutdown:t.shutdown}):await r.sessions.close({shutdown:t.shutdown}));return ab(t,a),!0};async function aM(e){await ra(e)}let aR=[{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"}],aT=new Map(aR.map(e=>[e.key,e]));function aO(e){let t=function(e){var t;let r,a,n,o=e.env??process.env,s=(r=(t=e).env??process.env,Y(t.configPath,{cwd:t.cwd,env:r}));if(!f.existsSync(s))throw new eg("INVALID_ARGS",`Remote config file not found: ${s}`);try{a=f.readFileSync(s,"utf8")}catch(e){throw new eg("INVALID_ARGS",`Failed to read remote config file: ${s}`,{cause:e instanceof Error?e.message:String(e)})}try{n=JSON.parse(a)}catch(e){throw new eg("INVALID_ARGS",`Invalid JSON in remote config file: ${s}`,{cause:e instanceof Error?e.message:String(e)})}if(!n||"object"!=typeof n||Array.isArray(n))throw new eg("INVALID_ARGS",`Remote config file must contain a JSON object: ${s}`);let l={},c=n,u=i.dirname(s);for(let[e,t]of Object.entries(c)){let r=aT.get(e);if(!r)throw new eg("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${s}.`);let a=ez(r,t,`remote config file ${s}`,e);l[r.key]="string"==typeof a&&"path"in r&&r.path?Y(a,{cwd:u,env:o}):a}return{resolvedPath:s,profile:l}}(e);return{resolvedPath:t.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of aR){let a=r[e.key];void 0!==a&&(t[e.key]=a)}return t}(function(e=process.env){let t={};for(let r of aR){let a=(function(e){let t=aT.get(e);return[eK(e),...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);a&&(t[r.key]=ez(r,a.value,`environment variable ${a.name}`,a.name))}return t}(e.env),t.profile)}}function aC(e){var t;let r,a=aj(e);if(!f.existsSync(a))return null;try{r=JSON.parse(f.readFileSync(a,"utf8"))}catch(t){return aH(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:(aH(e),null)}function aU(e){f.rmSync(aj(e),{force:!0});let t=aV(e.stateDir);aG(e.stateDir)===e.session&&f.rmSync(t,{force:!0})}function aF(e){try{return y.createHash("sha256").update(f.readFileSync(e)).digest("hex")}catch(t){throw new eg("INVALID_ARGS",`Remote config file not found: ${e}`,{cause:t instanceof Error?t.message:String(t)})}}function aj(e){return i.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 aV(e){return i.join(e,"remote-connections",".active-session.json")}function aB(e){let t=aG(e.stateDir);return t?aC({stateDir:e.stateDir,session:t}):null}function aG(e){let t=aV(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 aq(e,t){f.writeFileSync(e,`${JSON.stringify(t,null,2)}
29
- `,{encoding:"utf8",mode:384}),f.chmodSync(e,384)}function aH(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}}),aU(e)}let aJ=async({flags:e,client:t})=>{var r,a,n,o;let s,l;if(!e.remoteConfig)throw new eg("INVALID_ARGS","connect requires --remote-config <path>.");let c=e.session??"default",u=e.tenant,p=e.runId;if(!u)throw new eg("INVALID_ARGS","connect requires tenant in remote config or via --tenant <id>.");if(!p)throw new eg("INVALID_ARGS","connect requires runId in remote config or via --run-id <id>.");if(!e.daemonBaseUrl)throw new eg("INVALID_ARGS","connect requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.");let d=aO({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),m=aF(d.resolvedPath),h=e.leaseBackend??function(e){if("android"===e)return"android-instance";if("ios"===e)return"ios-instance";throw new eg("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=en(e.stateDir).baseDir,w=aC({stateDir:y,session:c});if(w&&(a=w,n={flags:e,remoteConfigPath:d.resolvedPath,remoteConfigHash:m,leaseBackend:h,daemon:g},!(a.remoteConfigPath===n.remoteConfigPath&&a.remoteConfigHash===n.remoteConfigHash&&a.session===(n.flags.session??"default")&&a.tenant===n.flags.tenant&&a.runId===n.flags.runId&&a.leaseBackend===n.leaseBackend&&a.platform===n.flags.platform&&a.target===n.flags.target&&aQ(a.daemon,n.daemon)))&&!e.force)throw new eg("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;(s=w&&w.leaseId&&!e.force?await aW(t,w.leaseId,{tenant:u,runId:p,leaseBackend:h}):void 0)||(s=await t.leases.allocate({tenant:u,runId:p,leaseBackend:h}),b=!0);let a=await aX(e,t,d.resolvedPath,c,{tenantId:s.tenantId,runId:s.runId,leaseId:s.leaseId});l=a.cleanup;let n=new Date().toISOString(),I={version:1,session:c,remoteConfigPath:d.resolvedPath,remoteConfigHash:m,daemon:g,tenant:u,runId:p,leaseId:s.leaseId,leaseBackend:h,platform:e.platform,target:e.target,runtime:a.runtime,metro:l,connectedAt:w&&!e.force?w.connectedAt:n,updatedAt:n};o={stateDir:y,state:I},r=aj({stateDir:o.stateDir,session:o.state.session}),f.mkdirSync(i.dirname(r),{recursive:!0}),aq(r,o.state),aq(aV(o.stateDir),{session:o.state.session}),v=!0,w&&e.force&&(w.metro?.projectRoot!==l?.projectRoot||w.metro?.profileKey!==l?.profileKey||w.metro?.consumerKey!==l?.consumerKey)&&await aY(w.metro),w&&e.force&&(w.tenant!==I.tenant||w.runId!==I.runId||w.leaseId!==I.leaseId||!aQ(w.daemon,I.daemon))&&await aZ(t,w),aw(e,a0(I),()=>`Connected remote session "${c}" tenant "${u}" run "${p}" lease ${I.leaseId}`)}catch(e){if(v||await aY(l),b&&s)try{await t.leases.release({tenant:u,runId:p,leaseId:s.leaseId})}catch{}throw e}return!0},aK=async({flags:e,client:t})=>{let r=e.session??"default",a=en(e.stateDir).baseDir,n=aC({stateDir:a,session:r})??(e.session?null:aB({stateDir:a}));if(!n)return aw(e,{connected:!1,session:r},()=>`No remote connection for "${r}".`),!0;let o=n.session;try{await t.sessions.close({shutdown:e.shutdown})}catch{}await aY(n.metro);let s=!1;try{s=(await t.leases.release({tenant:n.tenant,runId:n.runId,leaseId:n.leaseId})).released}catch{}return aU({stateDir:a,session:o}),aw(e,{connected:!1,session:o,released:s},()=>`Disconnected remote session "${o}".`),!0},az=async({positionals:e,flags:t})=>{if("status"!==e[0])throw new eg("INVALID_ARGS","connection accepts only: status");let r=t.session??"default",a=en(t.stateDir).baseDir,n=aC({stateDir:a,session:r})??(t.session?null:aB({stateDir:a}));return n?aw(t,a0(n),()=>[`Connected remote session "${n.session}".`,`tenant=${n.tenant} runId=${n.runId} leaseId=${n.leaseId} backend=${n.leaseBackend}`,`remoteConfig=${n.remoteConfigPath}`,n.runtime?"metro=prepared":"metro=not-prepared"].join("\n")):aw(t,{connected:!1,session:r},()=>`No remote connection for "${r}".`),!0};async function aW(e,t,r){try{return await e.leases.heartbeat({tenant:r.tenant,runId:r.runId,leaseId:t,leaseBackend:r.leaseBackend})}catch(e){var a;if((a=e)instanceof eg&&"UNAUTHORIZED"===a.code&&(a.details?.reason==="LEASE_NOT_FOUND"||a.details?.reason==="LEASE_EXPIRED"||a.details?.reason==="LEASE_REVOKED"))return;throw e}}async function aX(e,t,r,a,n){if(!e.metroProjectRoot&&!e.metroPublicBaseUrl&&!e.metroProxyBaseUrl)return{};if("ios"!==e.platform&&"android"!==e.platform)throw new eg("INVALID_ARGS",'connect Metro preparation requires platform "ios" or "android".');if(!e.metroPublicBaseUrl)throw new eg("INVALID_ARGS","connect Metro preparation requires metroPublicBaseUrl.");let o=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,bridgeScope:n,launchUrl:e.launchUrl,companionProfileKey:r,companionConsumerKey:a,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?o.iosRuntime:o.androidRuntime,cleanup:e.metroProxyBaseUrl?{projectRoot:o.projectRoot,profileKey:r,consumerKey:a}:void 0}}async function aY(e){if(e)try{await aM(e)}catch{}}async function aZ(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 aQ(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 a0(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 a1=async({flags:e,client:t})=>{let r=S(await t.capture.snapshot({...ay(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return aw(e,r,()=>(function(e,t={}){var r,a,n;let o,s=e.nodes,i=Array.isArray(s)?s:[],l="string"==typeof e.backend?e.backend:void 0,c=t.raw||"macos-helper"===l?null:G(i),u=!!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=c?.nodes??i,h=t.raw||"macos-helper"===l?null:function(e,t,r,a){let n=e.visibility;if(n&&"object"==typeof n&&"boolean"==typeof n.partial&&"number"==typeof n.visibleNodeCount&&"number"==typeof n.totalNodeCount&&Array.isArray(n.reasons))return{partial:n.partial,visibleNodeCount:n.visibleNodeCount,totalNodeCount:n.totalNodeCount,reasons:n.reasons.filter(e=>"string"==typeof e)};let o=t?.hiddenCount??0,s=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return o>0?{partial:!0,visibleNodeCount:r,totalNodeCount:a,reasons:["offscreen-nodes"]}:s?{partial:!0,visibleNodeCount:r,totalNodeCount:r,reasons:[]}:null}(e,c,f.length,i.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: ${i.length} nodes${u?" (truncated)":""}`,y=m.length>0?`${m.join("\n")}
30
- `:"",w=(r=e,a=i,n=t,o=ts(r),!n.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let r of e){let e=(r.type??"").toLowerCase(),a=K(r).trim().toLowerCase();if(!a)continue;let n=`${e}|${a}`;t.set(n,(t.get(n)??0)+1)}let r=0;for(let e of t.values())e>1&&(r+=e);return r>=8}(a)&&o.push("Warning: possible repeated nav subtree detected."),o),b=w.length>0?`${w.join("\n")}
24
+ `)}function e7(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function e9(e){return e>0?`+${e}`:String(e)}function te(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:"",r=e.regionIndex?` r${e.regionIndex}`:"";return`${e.likelyKind}${t}${r}`}function tt(e){return e.min===e.max?e9(e.min):`${e9(e.min)}..${e9(e.max)}`}function tr(e){let t=process.cwd(),r=i.relative(t,e);return""!==r&&(r.startsWith("..")||i.isAbsolute(r))?e:""===r?".":`.${i.sep}${r}`}function ta(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function tn(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function to(e,t){return t?l("dim",e):e}function ts(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function ti(e){var t;let r="scroll-area"===(t=e.type)||"list"===t||"collection"===t||"table"===t?t:null;if(!r)return[];let a=[];if(e.node.hiddenContentAbove&&a.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&a.push(`[content below ${r} hidden]`),0===a.length)return[];let n=" ".repeat(e.depth+1);return a.map(e=>`${n}${e}`)}let tl="sha256";async function tc(e){let t=await tu(e.localPath,e.platform),r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let a=await tf({normalizedBase:r,token:e.token,artifact:t});if(a?.kind==="cache-hit")return a.uploadId;if(a?.kind==="direct-upload")try{return await th(t.payloadPath,a),await ty({normalizedBase:r,token:e.token,uploadId:a.uploadId})}catch{}return await tm({normalizedBase:r,token:e.token,artifact:t})}finally{t.cleanup()}}async function tu(e,t){var r,a,n;let o,s=f.statSync(e),l=i.basename(e),c=s.isDirectory(),u=("ios"===(r=t)||"android"===r?r:void 0)??(a=e,n=s,o=a.toLowerCase(),n.isDirectory()&&o.endsWith(".app")||o.endsWith(".ipa")?"ios":o.endsWith(".apk")||o.endsWith(".aab")?"android":void 0),d=[];try{let t=c?await td(e,d):e,r=f.statSync(t);return{payloadPath:t,fileName:l,artifactType:c?"app-bundle":"file",platform:u,contentType:c?"application/gzip":"application/octet-stream",sha256:await tw(t),sizeBytes:r.size,cleanup:()=>tp(d)}}catch(e){throw tp(d),e}}async function td(e,t){let r=f.mkdtempSync(i.join(g.tmpdir(),`agent-device-upload-${b()}-`));t.push(r);let a=i.join(r,`${i.basename(e)}.tar.gz`);return await eh("tar",["czf",a,"-C",i.dirname(e),i.basename(e)]),a}function tp(e){for(let t of e)f.rmSync(t,{recursive:!0,force:!0})}async function tm(e){let{normalizedBase:t,token:r,artifact:a}=e,n=new URL("upload",t),o={"content-type":a.contentType,"x-artifact-type":a.artifactType,"x-artifact-filename":a.fileName,"x-artifact-hash":a.sha256,"x-artifact-hash-algorithm":tl,"transfer-encoding":"chunked"};r&&(o.authorization=`Bearer ${r}`,o["x-agent-device-token"]=r);let s=await tg({url:n,method:"POST",headers:o,payloadPath:a.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(s.body);if(!e.ok||!e.uploadId)throw new eg("COMMAND_FAILED",`Upload failed: ${s.body}`);return e.uploadId}catch(e){if(e instanceof eg)throw e;throw new eg("COMMAND_FAILED",`Invalid upload response: ${s.body}`)}}async function tf(e){let t=new URL("upload/preflight",e.normalizedBase),r={"content-type":"application/json"};e.token&&(r.authorization=`Bearer ${e.token}`,r["x-agent-device-token"]=e.token);let a=await fetch(t,{method:"POST",headers:r,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(a?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let r=e.upload;if(!r||"string"!=typeof r.url)return;let a=r.headers??{};if(!(!(t=a)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:r.url,headers:a}}(await a.json().catch(()=>void 0))}async function th(e,t){let r=await tg({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(r.statusCode<200||r.statusCode>=300)throw new eg("COMMAND_FAILED","Direct artifact upload failed",{statusCode:r.statusCode,statusMessage:r.statusMessage})}async function tg(e){let t="https:"===e.url.protocol?m:p;return await new Promise((r,a)=>{let n=t.request({protocol:e.url.protocol,host:e.url.hostname,port:e.url.port,method:e.method,path:e.url.pathname+e.url.search,headers:e.headers},e=>{let t="";e.setEncoding("utf8"),e.on("data",e=>{t+=e}),e.on("end",()=>{clearTimeout(o),r({statusCode:e.statusCode??500,statusMessage:e.statusMessage,body:t})})}),o=setTimeout(()=>{n.destroy(),a(new eg("COMMAND_FAILED",e.timeoutMessage,{timeoutMs:3e5,...e.timeoutHint?{hint:e.timeoutHint}:{}}))},3e5);n.on("error",t=>{clearTimeout(o),a(new eg("COMMAND_FAILED",e.errorMessage,e.errorHint?{hint:e.errorHint}:{},t))}),n.on("close",()=>clearTimeout(o));let s=f.createReadStream(e.payloadPath);s.pipe(n),s.on("error",e=>{n.destroy(),a(new eg("COMMAND_FAILED","Failed to read local artifact",{},e))})})}async function ty(e){let t=new URL("upload/finalize",e.normalizedBase),r={"content-type":"application/json"};e.token&&(r.authorization=`Bearer ${e.token}`,r["x-agent-device-token"]=e.token);let a=await fetch(t,{method:"POST",headers:r,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new eg("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!a.ok)throw new eg("COMMAND_FAILED","Direct artifact upload finalize failed",{status:a.status,statusText:a.statusText});let n=await a.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new eg("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function tw(e){let t=w(tl);return await new Promise((r,a)=>{f.createReadStream(e).on("data",e=>t.update(e)).on("error",e=>{a(new eg("COMMAND_FAILED","Failed to read local artifact",{},e))}).on("end",r)}),t.digest("hex")}let tb=tQ(),tv=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}(),tI=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}(),tk=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],tA=new d.BlockList;async function tS(e){let t=e.meta?.requestId??q(),r=!!(e.meta?.debug||e.flags?.verbose),a=function(e){let t,r=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,a=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),n=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var o=a,s=n;if(!(!o||"localhost"===(t=new URL(o).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(d.isIPv4(t)?tA.check(t,"ipv4"):!!d.isIPv6(t)&&tA.check(t,"ipv6")))&&("string"!=typeof s||!(s.trim().length>0)))throw new eg("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:o,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let i=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,l=E(i);if(a&&"socket"===l)throw new eg("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:a});let c=es(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===i?"dual":void 0));return{paths:en(r),transportPreference:l,serverMode:c,remoteBaseUrl:a,remoteAuthToken:n}}(e),n=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return tQ(t)}(e.command),o=await X("daemon_startup",async()=>await tP(a),{requestId:t,session:e.session}),s=await tD(e,o),i={...e,positionals:s.positionals,flags:s.flags,token:o.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,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};return Q({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await X("daemon_request",async()=>await tV(o,i,a.transportPreference,n),{requestId:t,command:e.command})}async function tD(e,t){let r,a=[...e.positionals??[]],n=e.flags?{...e.flags}:void 0,o=e.meta?.installSource,s={};if(tW(t)){let l=function(e,t){if("screenshot"===e.command){let r=tx(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:tN("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:tN("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=tx(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:tN("recording",i.extname(t)||".mp4")}}return null}(e,a);l&&(void 0!==l.positionalPath&&(a[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((n??={}).out=l.flagPath),s[l.field]=l.localPath);let c=await t$(e,t);c&&(o=c.installSource,r=c.uploadedArtifactId??r)}if(!tW(t)||"install"!==e.command&&"reinstall"!==e.command||a.length<2)return{positionals:a,flags:n,installSource:o,uploadedArtifactId:r,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let l=a[1];if(l.startsWith("remote:"))return a[1]=l.slice(7),{positionals:a,flags:n,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let c=i.isAbsolute(l)?l:i.resolve(e.meta?.cwd??process.cwd(),l);return f.existsSync(c)?{positionals:a,flags:n,installSource:o,uploadedArtifactId:r=await tc({localPath:c,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform}),...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}:{positionals:a,flags:n,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}}async function t$(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let a=r.path.trim();if(!a)return{installSource:r};if(a.startsWith("remote:"))return{installSource:{...r,path:a.slice(7)}};let n=i.isAbsolute(a)?a:i.resolve(e.meta?.cwd??process.cwd(),a);if(!f.existsSync(n))return{installSource:{...r,path:n}};let o=await tc({localPath:n,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform});return{installSource:{...r,path:n},uploadedArtifactId:o}}function tx(e,t,r,a=0){let n=e.positionals?.[a]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,s=n&&n.trim().length>0?n:o;return i.isAbsolute(s)?s:i.resolve(e.meta?.cwd??process.cwd(),s)}function tN(e,t){let r=t.startsWith(".")?t:`.${t}`;return i.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function tP(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await tF(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=tR(e.paths.infoPath),a=K(),n=_((t=tB()).useSrc?t.srcPath:t.distPath,t.root),o=!!r&&await tF(r,e.transportPreference);if(r&&r.version===a&&r.codeSignature===n&&o)return r;r&&(r.version!==a||r.codeSignature!==n||!o)&&(await tM(r),tU(e.paths.infoPath)),function(e){let t=tC(e);if(!t.hasLock||t.hasInfo)return;let r=tT(e.lockPath);if(!r)return tU(e.lockPath);$(r.pid,r.processStartTime)||tU(e.lockPath)}(e.paths);let s=0;for(let t=1;t<=tI;t+=1){await tj(e);let r=await tL(tv,e);if(r)return r;if(await tE(e.paths)){s+=1;continue}let a=tC(e.paths);if(!(t<tI))break;if(!a.hasInfo&&!a.hasLock){await t_(150);continue}}let i=tC(e.paths);throw new eg("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:tv,startupAttempts:tI,lockRecoveryCount:s,metadataState:i,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.`}(i,e.paths)})}async function tL(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=tR(t.paths.infoPath);if(e&&await tF(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function t_(e){await new Promise(t=>setTimeout(t,e))}async function tE(e){let t=tC(e);if(!t.hasLock||t.hasInfo)return!1;let r=tT(e.lockPath);return r&&$(r.pid,r.processStartTime)&&await ec(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),tU(e.lockPath),!0}async function tM(e){await ec(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function tR(e){let t=tO(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 a=Number.isInteger(t.port)&&Number(t.port)>0,n=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!a&&!n)return null;let o=t.transport,s="string"==typeof t.version?t.version:void 0,i="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:a?Number(t.port):void 0,httpPort:n?Number(t.httpPort):void 0,transport:"socket"===o||"http"===o||"dual"===o?o:void 0,pid:c?Number(t.pid):0,version:s,codeSignature:i,processStartTime:l}}function tT(e){let t=tO(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}tA.addSubnet("127.0.0.0",8,"ipv4"),tA.addAddress("::1","ipv6"),tA.addSubnet("::ffff:127.0.0.0",104,"ipv6");function tC(e){return{hasInfo:f.existsSync(e.infoPath),hasLock:f.existsSync(e.lockPath)}}function tO(e){if(!f.existsSync(e))return null;try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}}function tU(e){try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}async function tF(e,t){var r;return"http"===tG(e,t)?await function(e){let t=e.baseUrl?tX(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),a="https:"===r.protocol?m:p,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=a.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:n},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 tj(e){let t=tB(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],a={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};ed(process.execPath,r,{env:a})}function tB(){let e=z(),t=i.join(e,"dist","src","daemon.js"),r=i.join(e,"src","daemon.ts"),a=f.existsSync(t),n=f.existsSync(r);if(!a&&!n)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")?n:!a&&n}}async function tV(e,t,r,a){return"http"===tG(e,r)?await tz(e,t,a):await tJ(e,t,a)}function tG(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,a=t;if(tq(r,a))return a;throw new eg("COMMAND_FAILED","http"===a?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tq(e,t));if(n)return n;throw new eg("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tq(e,t){return"http"===t?!!e.httpPort:!!e.port}function tH(e,t,r,a,n,o){let s=n?{terminated:0}:function(){let e=0;try{for(let t of tk){let r=ep("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)}}}(),i=n?{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{tU(t.infoPath),tU(t.lockPath)}return{forcedKill:r}}(e,t);return Q({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:o,requestId:r,command:a,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:n?void 0:e.pid,daemonPidForceKilled:n?void 0:i.forcedKill,daemonBaseUrl:e.baseUrl}}),new eg("COMMAND_FAILED","Daemon request timed out",{timeoutMs:o,requestId:r,hint:n?"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 tK(e,t,r){return Q({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 tJ(e,t,r){let a=e.port;if(!a)throw new eg("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((n,o)=>{let s=d.createConnection({host:"127.0.0.1",port:a},()=>{s.write(`${JSON.stringify(t)}
25
+ `)}),i=en(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{s.destroy(),o(tH(e,i,t.meta?.requestId,t.command,!1,r))},r):void 0,c="";s.setEncoding("utf8"),s.on("data",e=>{let r=(c+=e).indexOf("\n");if(-1===r)return;let a=c.slice(0,r).trim();if(a)try{let e=JSON.parse(a);s.end(),l&&clearTimeout(l),n(e)}catch(e){l&&clearTimeout(l),o(new eg("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:a},e instanceof Error?e:void 0))}}),s.on("error",e=>{l&&clearTimeout(l),o(tK(e,t.meta?.requestId,!1))})})}async function tz(e,t,r){var a,n,o;let s,i=e.baseUrl?new URL(tX(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!i)throw new eg("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let l=JSON.stringify((a=t,n={includeTokenParam:!e.baseUrl},s=a.meta?.requestId??q(),"lease_allocate"!==(o=a.command)&&"lease_heartbeat"!==o&&"lease_release"!==o?{jsonrpc:"2.0",id:s,method:"agent_device.command",params:a}:{jsonrpc:"2.0",id:s,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"}}(a.command),params:function(e,t,r){let a={...r.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...a,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...a,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...a,leaseId:e.meta?.leaseId}}}(a,a.command,n)})),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((a,n)=>{let o=en(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),s=("https:"===i.protocol?m:p).request({protocol:i.protocol,host:i.hostname,port:i.port,method:"POST",path:i.pathname+i.search,headers:c},r=>{let o="";r.setEncoding("utf8"),r.on("data",e=>{o+=e}),r.on("end",()=>{d&&clearTimeout(d);try{let r=JSON.parse(o);if(r.error){let e=r.error.data??{};n(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 n(new eg("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void tY(e,t,r.result).then(a).catch(n);a(r.result)}catch(e){d&&clearTimeout(d),n(new eg("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:o},e instanceof Error?e:void 0))}})}),u=tW(e),d="number"==typeof r?setTimeout(()=>{s.destroy(),n(tH(e,o,t.meta?.requestId,t.command,u,r))},r):void 0;s.on("error",e=>{d&&clearTimeout(d),n(tK(e,t.meta?.requestId,u))}),s.write(l),s.end()})}function tW(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function tX(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function tY(e,t,r){let a=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===a.length||!e.baseUrl)return r;let n=r.data?{...r.data}:{},o=[];for(let r of a){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){o.push(r);continue}let a=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return i.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await tZ({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:a,requestId:t.meta?.requestId}),n[r.field]=a,o.push({...r,localPath:a})}return n.artifacts=o,{ok:!0,data:n}}async function tZ(e){var t,r;let a,n=new URL((t=e.baseUrl,r=e.artifactId,a=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,a).toString())),o="https:"===n.protocol?m:p;await f.promises.mkdir(i.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let a=!1,s=e.timeoutMs??tb,i=n=>{if(!a){if(a=!0,clearTimeout(c),n)return void f.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(n));t()}},l=o.request({protocol:n.protocol,host:n.hostname,port:n.port,method:"GET",path:n.pathname+n.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",()=>{i(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=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new eg("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),c=setTimeout(()=>{l.destroy(new eg("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:s}))},s);l.on("error",t=>{t instanceof eg?i(t):i(new eg("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:s},t instanceof Error?t:void 0))}),l.end()})}function tQ(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 t0="metro-companion";function t1(e){return w("sha256").update(e).digest("hex")}function t2(e){return e?.trim()?e.trim():void 0}function t3(e,t){let r=i.join(e,".agent-device");if(!t)return{statePath:i.join(r,"metro-companion.json"),logPath:i.join(r,"metro-companion.log")};let a=t1(t).slice(0,12),n=i.join(r,t0);return{statePath:i.join(n,`metro-companion-${a}.json`),logPath:i.join(n,`metro-companion-${a}.log`)}}function t5(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:t2("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 t8(e,t){f.mkdirSync(i.dirname(e),{recursive:!0}),f.writeFileSync(e,`${JSON.stringify(t,null,2)}
26
+ `,"utf8")}function t4(e){try{let t=f.readdirSync(e);0===t.length&&f.rmdirSync(e)}catch{}}function t6(e){let t=i.dirname(e.statePath),r=i.dirname(e.logPath);var a=e.statePath;try{f.unlinkSync(a)}catch{}var n=e.logPath;try{f.unlinkSync(n)}catch{}t4(t),r!==t&&t4(r),i.basename(t)===t0&&t4(i.dirname(t))}function t7(e){return e.includes(ey)}function t9(e){return t2(e.consumerKey)??t2(e.profileKey)??null}function re(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function rt(e){if(!et(e.pid))return;let t=k(e.pid);if(t&&t7(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 rr(e){let t=t9(e),r=t3(e.projectRoot,e.profileKey),a=t5(r.statePath);if(a&&function(e,t){var r,a;if(!et(e.pid))return!1;if(e.startTime){let t=er(e.pid);if(!t||t!==e.startTime)return!1}let n=k(e.pid);return!!n&&!!t7(n)&&!!e.bridgeScope&&e.serverBaseUrl===ew(t.serverBaseUrl)&&e.localBaseUrl===ew(t.localBaseUrl)&&e.launchUrl===t2(t.launchUrl)&&(r=e.bridgeScope,a=t.bridgeScope,r.tenantId===a.tenantId&&r.runId===a.runId&&r.leaseId===a.leaseId)&&e.tokenHash===t1(t.bearerToken)}(a,e)){let e=re(a,t);return e!==a&&t8(r.statePath,e),{pid:a.pid,spawned:!1,statePath:r.statePath,logPath:r.logPath}}a&&(await rt(a),t6(r));let n=function(e,t){let r=function(){let e=c(import.meta.url),t=i.extname(e)||".js",r=i.join(i.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}(),a=r.endsWith(".ts")?["--experimental-strip-types"]:[];f.mkdirSync(i.dirname(t),{recursive:!0});let n=f.openSync(t,"a"),o=0;try{let t;o=ed(process.execPath,[...a,r,ey],{env:((t={...e.env??process.env,[ev]:ew(e.serverBaseUrl),[e$]:e.bearerToken,[eI]:ew(e.localBaseUrl),[ek]:t3(e.projectRoot,e.profileKey).statePath})[eS]=e.bridgeScope.tenantId,t[eD]=e.bridgeScope.runId,t[ex]=e.bridgeScope.leaseId,e.launchUrl?.trim()?t[eA]=e.launchUrl.trim():delete t[eA],t),stdio:["ignore",n,n]})}finally{f.closeSync(n)}if(!Number.isInteger(o)||o<=0)throw Error("Failed to start Metro companion process.");return{pid:o,startTime:er(o)??void 0,command:k(o)??void 0,serverBaseUrl:ew(e.serverBaseUrl),localBaseUrl:ew(e.localBaseUrl),launchUrl:t2(e.launchUrl),bridgeScope:e.bridgeScope,tokenHash:t1(e.bearerToken),consumers:[]}}(e,r.logPath);return t8(r.statePath,re(n,t)),{pid:n.pid,spawned:!0,statePath:r.statePath,logPath:r.logPath}}async function ra(e){let t=t9(e),r=t3(e.projectRoot,e.profileKey),a=t5(r.statePath);if(!a)return t6(r),{stopped:!1,statePath:r.statePath};let n=t?{...a,consumers:a.consumers.filter(e=>e!==t)}:{...a,consumers:[]};return n.consumers.length>0?(t8(r.statePath,n),{stopped:!1,statePath:r.statePath}):(await rt(a),t6(r),{stopped:!0,statePath:r.statePath})}function rn(e){return"string"==typeof e&&e.trim()?ew(e.trim()):""}function ro(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function rs(e,t,r){return Y(e,{env:t,cwd:r})}function ri(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}function rl(e,t,r){if(null==e||""===e)return t;let a=Number.parseInt(String(e),10);return Number.isInteger(a)?Math.max(a,r):t}function rc(e,t){return{platform:t,bundleUrl:eb(e,t)}}function ru(e,t){return{platform:t,metroHost:ro(e?.metro_host),metroPort:e?.metro_port,bundleUrl:ro(e?.metro_bundle_url),launchUrl:ro(e?.launch_url)}}async function rd(e){await new Promise(t=>setTimeout(t,e))}async function rp(e,t,r={}){try{let a=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:a.ok,status:a.status,body:await a.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function rm(e,t){try{let r=await rp(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function rf(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 rh(e,t){let r=Error(e);return r.retryable=t,r}function rg(e,t){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(t).includes("Metro companion is not connected"))}function ry(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function rw(e){let t;try{var r,a;t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(r=e.baseUrl,a=e.bearerToken,{Authorization:`Bearer ${a}`,"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 rh(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw rh(t instanceof Error?t.message:String(t),!0)}let n=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(o){let a=e.slice(0,200),n=o instanceof Error?o.message:String(o);throw rh(`/api/metro/bridge returned invalid JSON (${t}) from ${r}: ${n}. body=${JSON.stringify(a)}`,rg(t,e))}}(await t.text(),t.status,e.baseUrl);if(!t.ok)throw rh(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(n)}`,rg(t.status,n));var o=n;let s=o.data??o;if(!s||"object"!=typeof s||Array.isArray(s))throw rh("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:s.enabled,baseUrl:s.base_url,statusUrl:s.status_url??"",bundleUrl:s.bundle_url??"",iosRuntime:ru(s.ios_runtime,"ios"),androidRuntime:ru(s.android_runtime,"android"),upstream:{bundleUrl:s.upstream.bundle_url??"",host:s.upstream.host??"",port:s.upstream.port??0,statusUrl:s.upstream.status_url??""},probe:{reachable:s.probe.reachable,statusCode:s.probe.status_code,latencyMs:s.probe.latency_ms,detail:s.probe.detail}}}catch(e){throw rh(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function rb(e,t,r,a,n){let o=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&o.push(`bridgeError=${t}`),r?.probe.reachable===!1&&o.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),a&&a!==t&&o.push(`initialBridgeError=${a}`),n&&o.push(`metroCompanionLog=${n}`),o.join(" ")}async function rv(e,t,r){let a=Date.now()+t;for(;Date.now()<a;){let t=Math.min(r,Math.max(a-Date.now(),1));if(await rm(e,t))return!0;let n=Math.min(500,Math.max(a-Date.now(),0));n>0&&await rd(n)}return!1}async function rI(e){let t=Date.now()+e.startupTimeoutMs,r=null,a=null;for(;Date.now()<t;){try{let t=await rw({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,a=null}catch(e){if(a=e instanceof Error?e.message:String(e),!ry(e))break}let n=Math.min(1e3,Math.max(t-Date.now(),0));n>0&&await rd(n)}throw Error(rb(e.baseUrl,a,r,e.initialBridgeError,e.companionLogPath))}async function rk(e={}){let t=e.env??process.env,r=process.cwd(),a=rs(e.projectRoot??r,t,r),n=function(e,t){if("auto"!==t)return t;let r=function(e){let t=i.join(e,"package.json");if(!ri(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"}(a,e.kind??"auto"),o=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),s=ro(e.listenHost)??"0.0.0.0",l=ro(e.statusHost)??"127.0.0.1",c=rn(e.publicBaseUrl),u=rl(e.startupTimeoutMs,18e4,3e4),d=rl(e.probeTimeoutMs,1e4,1e3),p=e.reuseExisting??!0,m=e.installDependenciesIfNeeded??!0,h=e.runtimeFilePath?rs(e.runtimeFilePath,t,r):null,g=rs(e.logPath??i.join(a,".agent-device","metro.log"),t,r);if(!c)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}}(rn(e.proxyBaseUrl),ro(e.proxyBearerToken)??""),v=y?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new eg("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}}(i.join(e,"node_modules")))return{installed:!1};let r=ri(i.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:ri(i.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return ep(r.command,r.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:r.command}}(a,t):{installed:!1},k=`http://${l}:${o}/status`,A=!1,S=!1,D=0;if(p&&await rm(k,d))S=!0;else if(A=!0,D=function(e,t,r,a,n,o){let s="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",a,"--port",String(r)]};f.mkdirSync(i.dirname(n),{recursive:!0});let l=f.openSync(n,"a"),c=0;try{c=ed(s.command,s.installArgs,{cwd:e,env:o,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}}(a,n,o,s,g,t).pid,!await rv(k,u,d))throw await rf(D).catch(()=>{}),Error(`Metro did not become ready at ${k} within ${u}ms. Check ${g}.`);let $=rc(c,"ios"),x=rc(c,"android"),N=null,P=null;if(v)try{N=await rw({baseUrl:w,bearerToken:b,scope:v,runtime:{metro_bundle_url:$.bundleUrl},timeoutMs:d})}catch(e){if(!ry(e))throw e;P=e instanceof Error?e.message:String(e)}if(v&&(!N||!1===N.probe.reachable)){let r;try{r=(await rr({projectRoot:a,serverBaseUrl:w,bearerToken:b,bridgeScope:v,localBaseUrl:`http://${l}:${o}`,launchUrl:ro(e.launchUrl),profileKey:ro(e.companionProfileKey),consumerKey:ro(e.companionConsumerKey),env:t})).logPath}catch(e){throw Error(rb(w,e instanceof Error?e.message:String(e),N,P))}try{N=await rI({baseUrl:w,bearerToken:b,scope:v,runtime:{metro_bundle_url:$.bundleUrl},probeTimeoutMs:d,startupTimeoutMs:u,initialBridgeError:P,companionLogPath:r})}catch(e){throw e instanceof Error?e:Error(String(e))}}let L=N?.iosRuntime??$,_=N?.androidRuntime??x,E={projectRoot:a,kind:n,dependenciesInstalled:I.installed,packageManager:I.packageManager??null,started:A,reused:S,pid:D,logPath:g,statusUrl:k,runtimeFilePath:h,iosRuntime:L,androidRuntime:_,bridge:N};return h&&(f.mkdirSync(i.dirname(h),{recursive:!0}),f.writeFileSync(h,JSON.stringify(E,null,2))),E}let rA="alert",rS="appstate",rD="app-switcher",r$="apps",rx="back",rN="batch",rP="boot",rL="click",r_="clipboard",rE="devices",rM="diff",rR="fill",rT="find",rC="focus",rO="home",rU="keyboard",rF="logs",rj="longpress",rB="network",rV="perf",rG="pinch",rq="press",rH="push",rK="record",rJ="replay",rz="rotate",rW="scroll",rX="screenshot",rY="settings",rZ="snapshot",rQ="swipe",r0="test",r1="trace",r2="trigger-app-event",r3="type",r5="wait";function r8(e,t,r,a){let n=r(e[t]);if(void 0===n)throw new eg("COMMAND_FAILED",a,{response:e});return n}function r4(e,t){return r8(e,t,ar,`Daemon response is missing "${t}".`)}function r6(e,t){return ar(e[t])}function r7(e,t){var r;let a;return r=ar,null===(a=e[t])?null:r(a)}function r9(e,t){return r8(e,t,an,`Daemon response has invalid "${t}".`)}function ae(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function at(e,t){let r=e[t];if(!ai(r))return;let a="number"==typeof r.x?r.x:void 0,n="number"==typeof r.y?r.y:void 0,o="number"==typeof r.width?r.width:void 0,s="number"==typeof r.height?r.height:void 0;if(void 0!==a&&void 0!==n&&void 0!==o&&void 0!==s)return{x:a,y:n,width:o,height:s}}function ar(e){return"string"==typeof e&&e.length>0?e:void 0}function aa(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function an(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function ao(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function as(e){if(!ai(e))throw new eg("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function ai(e){return"object"==typeof e&&null!==e}function al(e){let t={};for(let[r,a]of Object.entries(e))void 0!==a&&(t[r]=a);return t}function ac(e,t){let r=r6(e,"bundleId"),a=r6(e,"package");return{app:r4(e,"app"),appPath:r4(e,"appPath"),platform:r9(e,"platform"),appId:r??a,bundleId:r,package:a,identifiers:N({session:t,bundleId:r,packageName:a})}}function au(e){let t=as(e),r=r9(t,"platform"),a=r4(t,"id"),n=r4(t,"name");return{platform:r,target:ae(t,"target"),kind:r8(t,"kind",ao,'Daemon response has invalid "kind".'),id:a,name:n,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:x(r,a,n),ios:"ios"===r?{udid:a}:void 0,android:"android"===r?{serial:a}:void 0}}function ad(e){let t=as(e),r=r9(t,"platform"),a=r4(t,"id"),n=r4(t,"name"),o=ae(t,"target"),s=r4(t,"device"),i={session:n,...x(r,a,s)};return{name:n,createdAt:r8(t,"createdAt",aa,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:o,id:a,name:s,identifiers:i,ios:"ios"===r?{udid:a,simulatorSetPath:r7(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:a}:void 0},identifiers:i}}function ap(e){return e??"default"}function am(e={},t={}){var r;let a,n=t.transport??tS,o=async(t,r=[],a={})=>{var o,s;let i=(o=e,s=a,{...o,...s}),l=await n({session:ap(i.session),command:t,positionals:r,flags:al({stateDir:i.stateDir,daemonBaseUrl:i.daemonBaseUrl,daemonAuthToken:i.daemonAuthToken,daemonTransport:i.daemonTransport,daemonServerMode:i.daemonServerMode,tenant:i.tenant,sessionIsolation:i.sessionIsolation,runId:i.runId,leaseId:i.leaseId,leaseBackend:i.leaseBackend,platform:i.platform,target:i.target,device:i.device,udid:i.udid,serial:i.serial,iosSimulatorDeviceSet:i.iosSimulatorDeviceSet,androidDeviceAllowlist:i.androidDeviceAllowlist,runtime:i.simulatorRuntimeId,boot:i.boot,reuseExisting:i.reuseExisting,surface:i.surface,activity:i.activity,relaunch:i.relaunch,shutdown:i.shutdown,saveScript:i.saveScript,noRecord:i.noRecord,backMode:i.backMode,metroHost:i.metroHost,metroPort:i.metroPort,bundleUrl:i.bundleUrl,launchUrl:i.launchUrl,snapshotInteractiveOnly:i.interactiveOnly,snapshotCompact:i.compact,snapshotDepth:i.depth,snapshotScope:i.scope,snapshotRaw:i.raw,screenshotFullscreen:i.screenshotFullscreen,overlayRefs:i.overlayRefs,appsFilter:i.appsFilter,out:i.out,count:i.count,fps:i.fps,quality:i.quality,hideTouches:i.hideTouches,intervalMs:i.intervalMs,delayMs:i.delayMs,holdMs:i.holdMs,jitterPx:i.jitterPx,pixels:i.pixels,doubleTap:i.doubleTap,clickButton:i.clickButton,pauseMs:i.pauseMs,pattern:i.pattern,headless:i.headless,restart:i.restart,replayUpdate:i.replayUpdate,failFast:i.failFast,timeoutMs:i.timeoutMs,retries:i.retries,artifactsDir:i.artifactsDir,reportJunit:i.reportJunit,findFirst:i.findFirst,findLast:i.findLast,networkInclude:i.networkInclude,batchOnError:i.batchOnError,batchMaxSteps:i.batchMaxSteps,batchSteps:i.batchSteps,verbose:i.debug}),runtime:i.runtime,meta:al({requestId:i.requestId,cwd:i.cwd,debug:i.debug,lockPolicy:i.lockPolicy,lockPlatform:i.lockPlatform,tenantId:i.tenant,runId:i.runId,leaseId:i.leaseId,leaseBackend:i.leaseBackend,leaseTtlMs:i.leaseTtlMs,sessionIsolation:i.sessionIsolation,installSource:i.installSource,retainMaterializedPaths:i.retainMaterializedPaths,materializedPathRetentionMs:i.materializedPathRetentionMs,materializationId:i.materializationId})});return l.ok||function(e){throw new eg(e.code,e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(l.error),l.data??{}},s=async(e={})=>{let t=await o("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(ad)},i=async(e,t=[],r={})=>await o(e,t,r),l=(t={})=>{var r,a;return ap((r=e,a=t,{...r,...a}).session)};return{command:(r=async e=>await o(e.command,e.positionals,e.options),a=async e=>await r(e),{wait:async e=>await a(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:r5,positionals:[String(e.durationMs)],options:e};let t=void 0!==e.timeoutMs?[String(e.timeoutMs)]:[];if(void 0!==e.text)return{command:r5,positionals:["text",e.text,...t],options:e};if(void 0!==e.ref)return{command:r5,positionals:[e.ref,...t],options:e};let r=e.selector;return function(e){if(!H(e))throw new eg("INVALID_ARGS",`Invalid wait selector: ${e}`)}(r),{command:r5,positionals:[r,...t],options:e}}(e)),alert:async(e={})=>{var t;return await a({command:rA,positionals:[(t=e).action??"get",...void 0!==t.timeoutMs?[String(t.timeoutMs)]:[]],options:t})},appState:async(e={})=>await a({command:rS,positionals:[],options:e}),back:async(e={})=>await a({command:rx,positionals:[],options:{...e,backMode:e.mode}}),home:async(e={})=>await a({command:rO,positionals:[],options:e}),rotate:async e=>await a({command:rz,positionals:[e.orientation],options:e}),appSwitcher:async(e={})=>await a({command:rD,positionals:[],options:e}),keyboard:async(e={})=>await a({command:rU,positionals:e.action?[e.action]:[],options:e}),clipboard:async e=>{var t;return await a("read"===(t=e).action?{command:r_,positionals:["read"],options:t}:{command:r_,positionals:["write",t.text],options:t})}}),devices:{list:async(e={})=>{let t=await o(rE,[],e);return(Array.isArray(t.devices)?t.devices:[]).map(au)},boot:async(e={})=>await i(rP,[],e)},sessions:{list:async(e={})=>await s(e),close:async(e={})=>{let t=l(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,a=await o("ensure-simulator",[],{...r,simulatorRuntimeId:t}),n=r4(a,"udid"),s=r4(a,"device");return{udid:n,device:s,runtime:r4(a,"runtime"),created:!0===a.created,booted:!0===a.booted,iosSimulatorDeviceSet:r7(a,"ios_simulator_device_set"),identifiers:{deviceId:n,deviceName:s,udid:n}}}},apps:{install:async e=>ac(await o("install",[e.app,e.appPath],e),l(e)),reinstall:async e=>ac(await o("reinstall",[e.app,e.appPath],e),l(e)),installFromSource:async e=>(function(e,t){let r=r6(e,"bundleId"),a=r6(e,"packageName"),n=r??a??r6(e,"appId"),o=r6(e,"launchTarget")??a??r??n;if(!o)throw new eg("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:r6(e,"appName"),appId:n,bundleId:r,packageName:a,launchTarget:o,installablePath:r6(e,"installablePath"),archivePath:r6(e,"archivePath"),materializationId:r6(e,"materializationId"),materializationExpiresAt:r6(e,"materializationExpiresAt"),identifiers:N({session:t,bundleId:r,packageName:a,appId:n})}})(await o("install_source",[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),l(e)),list:async(e={})=>{let t=await o(r$,[],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]:[],a=await o("open",r,e),n=function(e){let t=e.platform,r=r6(e,"id"),a=r6(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!a)return;let n=ae(e,"target"),o=x(t,r,a);return{platform:t,target:n,id:r,name:a,identifiers:o,ios:"ios"===t?{udid:r6(e,"device_udid")??r,simulatorSetPath:r7(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:r6(e,"serial")??r}:void 0}}(a),s=r6(a,"appBundleId");return{session:t,appName:r6(a,"appName"),appBundleId:s,appId:s,startup:function(e){if(ai(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:r6(e,"appTarget"),appBundleId:r6(e,"appBundleId")}}(a.startup),runtime:function(e){if(!ai(e))return;let t=e.platform,r=r6(e,"metroHost"),a="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:a,bundleUrl:r6(e,"bundleUrl"),launchUrl:r6(e,"launchUrl")}}(a.runtime),device:n,identifiers:{session:t,deviceId:n?.id,deviceName:n?.name,udid:n?.ios?.udid,serial:n?.android?.serial,appId:s,appBundleId:s}}},close:async(e={})=>{let t=l(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 i(rH,[e.app,"string"==typeof(t=e.payload)?t:JSON.stringify(t)],e)},triggerEvent:async e=>{var t;return await i(r2,[(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:r4(t,"materializationId"),identifiers:{}}}},leases:{allocate:async e=>ay(await o("lease_allocate",[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>ay(await o("lease_heartbeat",[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await o("lease_release",[],e)).released})},metro:{prepare:async t=>await rk({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),a=await o(rZ,[],e),n=r6(a,"appBundleId"),s="object"==typeof a.visibility&&null!==a.visibility?a.visibility:void 0;return{nodes:Array.isArray(t=a.nodes)?t:[],truncated:!0===a.truncated,appName:r6(a,"appName"),appBundleId:n,...s?{visibility:s}:{},warnings:Array.isArray(a.warnings)?a.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:r,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=l(e),r=await o(rX,e.path?[e.path]:[],{...e,screenshotFullscreen:e.fullscreen});return{path:r4(r,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!ai(e))continue;let t=r6(e,"ref"),a=at(e,"rect"),n=at(e,"overlayRect"),o=function(e,t){let r=e[t];if(!ai(r))return;let a="number"==typeof r.x?r.x:void 0,n="number"==typeof r.y?r.y:void 0;if(void 0!==a&&void 0!==n)return{x:a,y:n}}(e,"center");t&&a&&n&&o&&r.push({ref:t,label:r6(e,"label"),rect:a,overlayRect:n,center:o})}return r}(r),identifiers:{session:t}}},diff:async e=>await i(rM,[e.kind],{...e,interactiveOnly:e.interactiveOnly,compact:e.compact,depth:e.depth,scope:e.scope,raw:e.raw})},interactions:{click:async e=>await i(rL,af(e),{...e,clickButton:e.button}),press:async e=>await i(rq,af(e),e),longPress:async e=>await i(rj,[String(e.x),String(e.y),...ag(e.durationMs)],e),swipe:async e=>await i(rQ,[String(e.from.x),String(e.from.y),String(e.to.x),String(e.to.y),...ag(e.durationMs)],e),focus:async e=>await i(rC,[String(e.x),String(e.y)],e),type:async e=>await i(r3,[e.text],e),fill:async e=>await i(rR,[...af(e),e.text],e),scroll:async e=>await i(rW,[e.direction,...ag(e.amount)],e),pinch:async e=>await i(rG,[String(e.scale),...ag(e.x),...ag(e.y)],e),get:async e=>{var t;return await i("get",[e.format,...void 0!==(t=e).ref?[t.ref,...ah(t.label)]:[t.selector]],e)},is:async e=>await i("is",[e.predicate,e.selector,..."text"===e.predicate?[e.value]:[]],e),find:async e=>await i(rT,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",...ag(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 i(rJ,[e.path],{...e,replayUpdate:e.update}),test:async e=>await i(r0,e.paths,{...e,replayUpdate:e.update})},batch:{run:async e=>await i(rN,[],{...e,batchSteps:e.steps,batchOnError:e.onError,batchMaxSteps:e.maxSteps})},observability:{perf:async(e={})=>await i(rV,[],e),logs:async(e={})=>{var t;return await i(rF,[(t=e).action??"path",...ah(t.message)],e)},network:async(e={})=>{var t;return await i(rB,[...(t=e).action?[t.action]:[],...ag(t.limit)],{...e,networkInclude:e.include})}},recording:{record:async e=>await i(rK,[e.action,...ah(e.path)],e),trace:async e=>await i(r1,[e.action,...ah(e.path)],e)},settings:{update:async e=>await i(rY,[e.setting,e.state,..."permission"in e?[e.permission]:[],..."mode"in e&&e.mode?[e.mode]:[]],e)}}}function af(e){return void 0!==e.ref?[e.ref,...ah(e.label)]:void 0!==e.selector?[e.selector]:[String(e.x),String(e.y)]}function ah(e){return void 0===e?[]:[e]}function ag(e){return void 0===e?[]:[String(e)]}function ay(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:r4(t,"leaseId"),tenantId:r4(t,"tenantId"),runId:r4(t,"runId"),backend:r4(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}}async function aw(e){await ra(e)}let ab=[{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"}],av=new Map(ab.map(e=>[e.key,e]));function aI(e){let t=e.env??process.env;return Y(e.configPath,{cwd:e.cwd,env:t})}function ak(e){let t=function(e){let t,r,a=e.env??process.env,n=aI(e);if(!f.existsSync(n))throw new eg("INVALID_ARGS",`Remote config file not found: ${n}`);try{t=f.readFileSync(n,"utf8")}catch(e){throw new eg("INVALID_ARGS",`Failed to read remote config file: ${n}`,{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: ${n}`,{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: ${n}`);let o={},s=r,l=i.dirname(n);for(let[e,t]of Object.entries(s)){let r=av.get(e);if(!r)throw new eg("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${n}.`);let s=ez(r,t,`remote config file ${n}`,e);o[r.key]="string"==typeof s&&"path"in r&&r.path?Y(s,{cwd:l,env:a}):s}return{resolvedPath:n,profile:o}}(e);return{resolvedPath:t.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of ab){let a=r[e.key];void 0!==a&&(t[e.key]=a)}return t}(function(e=process.env){let t={};for(let r of ab){let a=(function(e){let t=av.get(e);return[eJ(e),...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);a&&(t[r.key]=ez(r,a.value,`environment variable ${a.name}`,a.name))}return t}(e.env),t.profile)}}function aA(e){var t;let r,a=aN(e);if(!f.existsSync(a))return null;try{r=JSON.parse(f.readFileSync(a,"utf8"))}catch(t){return aM(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&&(void 0===t.leaseId||"string"==typeof t.leaseId)&&(void 0===t.leaseBackend||"string"==typeof t.leaseBackend)&&"string"==typeof t.connectedAt&&"string"==typeof t.updatedAt?r:(aM(e),null)}function aS(e){let t=aN({stateDir:e.stateDir,session:e.state.session});f.mkdirSync(i.dirname(t),{recursive:!0}),aE(t,e.state),aE(aP(e.stateDir),{session:e.state.session})}function aD(e){return{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(/\/+$/,"")}(e.daemonBaseUrl),transport:e.daemonTransport,serverMode:e.daemonServerMode}}function a$(e){f.rmSync(aN(e),{force:!0});let t=aP(e.stateDir);a_(e.stateDir)===e.session&&f.rmSync(t,{force:!0})}function ax(e){try{return y.createHash("sha256").update(f.readFileSync(e)).digest("hex")}catch(t){throw new eg("INVALID_ARGS",`Remote config file not found: ${e}`,{cause:t instanceof Error?t.message:String(t)})}}function aN(e){return i.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 aP(e){return i.join(e,"remote-connections",".active-session.json")}function aL(e){let t=a_(e.stateDir);return t?aA({stateDir:e.stateDir,session:t}):null}function a_(e){let t=aP(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 aE(e,t){f.writeFileSync(e,`${JSON.stringify(t,null,2)}
27
+ `,{encoding:"utf8",mode:384}),f.chmodSync(e,384)}function aM(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}}),a$(e)}let aR=new Set(["connect","connection","close","devices","disconnect","ensure-simulator","metro","session"]),aT=new Set(["open"]);async function aC(e){let t,r,{command:a,flags:n,client:o}=e;if(!n.remoteConfig)return{flags:n,runtime:e.runtime};let s=en(n.stateDir).baseDir,i=ak({configPath:n.remoteConfig,cwd:process.cwd(),env:process.env}),l={...function(e){let t={};for(let r of ab){let a=e[r.key];void 0!==a&&(t[r.key]=a)}return t}(i.profile),...n,remoteConfig:i.resolvedPath},c=aA({stateDir:s,session:l.session??"default"});if(c&&c.remoteConfigPath!==i.resolvedPath)throw new eg("INVALID_ARGS","A different remote connection is already active for this session. Run connect --force or disconnect before using a different --remote-config.",{session:c.session,activeRemoteConfig:c.remoteConfigPath,requestedRemoteConfig:i.resolvedPath});let u=c??function(e,t){if(!e.tenant)throw new eg("INVALID_ARGS","remote command requires tenant in remote config or via --tenant <id>.");if(!e.runId)throw new eg("INVALID_ARGS","remote command requires runId in remote config or via --run-id <id>.");if(!e.daemonBaseUrl)throw new eg("INVALID_ARGS","remote command requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.");let r=new Date().toISOString();return{version:1,session:e.session??"default",remoteConfigPath:t,remoteConfigHash:ax(t),daemon:aD(e),tenant:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend??aj(e),platform:e.platform,target:e.target,connectedAt:r,updatedAt:r}}(l,i.resolvedPath),d={...l,session:u.session},p=function(e,t){if(e)return aV(e,t)?e:void 0}(u.runtime,d.platform)??e.runtime,m=u,f=!c;if(h=a,!aR.has(h)){let e=u.leaseBackend??function(e,t){let r=aj(e);if(r)return r;throw new eg("INVALID_ARGS",`${t} requires --platform ios|android or --lease-backend when the remote connection has not resolved a lease yet.`)}(n,a);var h,g,y,w,b,v=u,I=n,k=e;if(v.leaseBackend&&v.leaseBackend!==k)throw new eg("INVALID_ARGS","Active remote connection is already bound to a different lease backend. Re-run connect --force to replace it.",{session:v.session,leaseBackend:v.leaseBackend});if(v.platform&&I.platform&&v.platform!==I.platform)throw new eg("INVALID_ARGS","Active remote connection is already bound to a different platform. Re-run connect --force to replace it.",{session:v.session,platform:v.platform});if(v.target&&I.target&&v.target!==I.target)throw new eg("INVALID_ARGS","Active remote connection is already bound to a different target. Re-run connect --force to replace it.",{session:v.session,target:v.target});let t=await aG(o,m,e);d.leaseId=t.leaseId,d.leaseBackend=e,d.platform=m.platform??d.platform,d.target=m.target??d.target,(m.leaseId!==t.leaseId||m.leaseBackend!==e)&&(m={...m,leaseId:t.leaseId,leaseBackend:e,platform:m.platform??n.platform,target:m.target??n.target,updatedAt:new Date().toISOString()},f=!0)}if(g=a,y=e.batchSteps,(aT.has(g)||"batch"===g&&y&&y.some(e=>{let t=e.command.trim().toLowerCase();return aT.has(t)&&void 0===e.runtime}))&&aB(d)&&(!m.leaseId&&d.leaseId&&(m={...m,leaseId:d.leaseId,leaseBackend:d.leaseBackend}),e.forceRuntimePrepare||!p||!aV(p,d.platform))){if(!m.leaseId)throw new eg("INVALID_ARGS",`${a} requires a resolved remote lease before Metro runtime can be prepared.`);let e=await aO(d,o,u.remoteConfigPath,u.session,{tenantId:u.tenant,runId:u.runId,leaseId:m.leaseId});p=e.runtime;let n=(w=m.metro,b=e.cleanup,w?.projectRoot!==b?.projectRoot||w?.profileKey!==b?.profileKey||w?.consumerKey!==b?.consumerKey);t=n?m.metro:void 0,r=n?e.cleanup:void 0,m={...m,runtime:e.runtime,metro:e.cleanup,updatedAt:new Date().toISOString()},f=!0}if(f)try{aS({stateDir:s,state:m})}catch(e){throw await aU(r),e}return await aU(t),{flags:{...d,session:m.session,leaseId:m.leaseId,leaseBackend:m.leaseBackend,platform:m.platform??d.platform,target:m.target??d.target},runtime:p}}async function aO(e,t,r,a,n){if(!e.metroProjectRoot&&!e.metroPublicBaseUrl&&!e.metroProxyBaseUrl)return{};if("ios"!==e.platform&&"android"!==e.platform)throw new eg("INVALID_ARGS",'Deferred Metro preparation requires platform "ios" or "android".');if(!e.metroPublicBaseUrl)throw new eg("INVALID_ARGS","Deferred Metro preparation requires metroPublicBaseUrl when Metro settings are provided.");let o=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,bridgeScope:n,launchUrl:e.launchUrl,companionProfileKey:r,companionConsumerKey:a,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?o.iosRuntime:o.androidRuntime,cleanup:e.metroProxyBaseUrl?{projectRoot:o.projectRoot,profileKey:r,consumerKey:a}:void 0}}async function aU(e){if(e)try{await aw(e)}catch{}}async function aF(e,t){if(t.leaseId)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 aj(e){return e.leaseBackend?e.leaseBackend:"android"===e.platform?"android-instance":"ios"===e.platform?"ios-instance":void 0}function aB(e){return!!(e.metroPublicBaseUrl||e.metroProxyBaseUrl||e.metroProjectRoot||e.metroKind)}function aV(e,t){return!e.platform||!t||"ios"!==t&&"android"!==t||e.platform===t}async function aG(e,t,r){if(t.leaseId&&t.leaseBackend===r){let a=await aq(e,t.leaseId,{tenant:t.tenant,runId:t.runId,leaseBackend:r});if(a)return a}return await e.leases.allocate({tenant:t.tenant,runId:t.runId,leaseBackend:r})}async function aq(e,t,r){try{return await e.leases.heartbeat({tenant:r.tenant,runId:r.runId,leaseId:t,leaseBackend:r.leaseBackend})}catch(e){var a;if((a=e)instanceof eg&&"UNAUTHORIZED"===a.code&&(a.details?.reason==="LEASE_NOT_FOUND"||a.details?.reason==="LEASE_EXPIRED"||a.details?.reason==="LEASE_REVOKED"))return;throw e}}function aH(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function aK(e,t,r){var a;if(e.json)return void e4({success:!0,data:t});let n=r?.();n&&(a=n,process.stdout.write(a.endsWith("\n")?a:`${a}
28
+ `))}function aJ(e,t){aK(e,t,()=>U(t))}let az=async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new eg("INVALID_ARGS","session only supports list");let a={sessions:(await r.sessions.list()).map(S)};return aK(t,a,()=>JSON.stringify(a,null,2)),!0},aW=async({flags:e,client:t})=>{let r=await t.devices.list(aH(e));return aK(e,{devices:r.map(B)},()=>r.map(aX).join("\n")),!0};function aX(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",a="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${a}`}let aY=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 aK(e,F(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},aZ=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 a=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 aK(t,a,()=>JSON.stringify(a,null,2)),!0},aQ=async({flags:e,client:t})=>{let r=await t.apps.list({...aH(e),appsFilter:e.appsFilter});return aK(e,{apps:r},()=>r.join("\n")),!0},a0=async({positionals:e,flags:t,client:r})=>{let a=O(await a3("install",e,t,r));return aJ(t,a),!0},a1=async({positionals:e,flags:t,client:r})=>{let a=O(await a3("reinstall",e,t,r));return aJ(t,a),!0},a2=async({positionals:e,flags:t,client:r})=>{let a=ei(await a5(e,t,r));return aJ(t,a),!0};async function a3(e,t,r,a){let n=t[0],o=t[1];if(!n||!o)throw new eg("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let s={app:n,appPath:o,...aH(r)};return"install"===e?await a.apps.install(s):await a.apps.reinstall(s)}async function a5(e,t,r){let a=e[0]?.trim();if(!a)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({...aH(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:a,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 a=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!a)throw new eg("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[a]=n}return t}(t.header)}})}let a8=async({positionals:e,flags:t,client:r})=>{let a=R(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,...aH(t)}));return aJ(t,a),!0},a4=async({positionals:e,flags:t,client:r})=>{let a=Z(e[0]?await r.apps.close({app:e[0],shutdown:t.shutdown}):await r.sessions.close({shutdown:t.shutdown}));return aJ(t,a),!0},a6=async({flags:e,client:t})=>{var r,a,n,o;if(!e.remoteConfig)throw new eg("INVALID_ARGS","connect requires --remote-config <path>.");let s=e.tenant,i=e.runId;if(!s)throw new eg("INVALID_ARGS","connect requires tenant in remote config or via --tenant <id>.");if(!i)throw new eg("INVALID_ARGS","connect requires runId in remote config or via --run-id <id>.");if(!e.daemonBaseUrl)throw new eg("INVALID_ARGS","connect requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.");let l=en(e.stateDir).baseDir,c=e.session?null:aL({stateDir:l}),u=e.session??c?.session??function(e){for(let t=0;t<8;t+=1){let t=`adc-${y.randomBytes(3).toString("hex")}`;if(!aA({stateDir:e,session:t}))return t}return`adc-${Date.now().toString(36)}-${y.randomBytes(2).toString("hex")}`}(l),d=ak({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),p=ax(d.resolvedPath),m=aD(e),f=c?.session===u?c:aA({stateDir:l,session:u});if(f&&(r=f,a={flags:e,session:u,remoteConfigPath:d.resolvedPath,remoteConfigHash:p,desiredLeaseBackend:aj(e),daemon:m},r.remoteConfigPath!==a.remoteConfigPath||r.remoteConfigHash!==a.remoteConfigHash||r.session!==a.session||r.tenant!==a.flags.tenant||r.runId!==a.flags.runId||void 0!==a.desiredLeaseBackend&&r.leaseBackend!==a.desiredLeaseBackend||void 0!==a.flags.platform&&r.platform!==a.flags.platform||void 0!==a.flags.target&&r.target!==a.flags.target||(n=r.daemon,o=a.daemon,(n?.baseUrl??void 0)!==(o?.baseUrl??void 0)||(n?.transport??void 0)!==(o?.transport??void 0)||(n?.serverMode??void 0)!==(o?.serverMode??void 0)))&&!e.force)throw new eg("INVALID_ARGS","A different remote connection is already active for this session. Re-run connect with --force to replace it.",{session:u,remoteConfig:f.remoteConfigPath});let h=new Date().toISOString(),g={version:1,session:u,remoteConfigPath:d.resolvedPath,remoteConfigHash:p,daemon:m,tenant:s,runId:i,leaseId:f&&!e.force?f.leaseId:void 0,leaseBackend:f&&!e.force?f.leaseBackend:aj(e),platform:e.platform??(f&&!e.force?f.platform:void 0),target:e.target??(f&&!e.force?f.target:void 0),runtime:f&&!e.force?f.runtime:void 0,metro:f&&!e.force?f.metro:void 0,connectedAt:f&&!e.force?f.connectedAt:h,updatedAt:h};aS({stateDir:l,state:g}),f&&e.force&&(await aU(f.metro),await aF(t,f));let w=function(e,t){if(!t.runtime&&(aB(e)||nt(t.remoteConfigPath)))return ne(t.remoteConfigPath)}(e,g);return aK(e,nr(g,w),()=>[`Connected remote session "${u}" tenant "${s}" run "${i}" ${g.leaseId?`lease ${g.leaseId}`:"lease pending"}`,w?.message].filter(e=>!!e).join("\n")),!0},a7=async({flags:e,client:t})=>{let r=e.session??"default",a=en(e.stateDir).baseDir,n=aA({stateDir:a,session:r})??(e.session?null:aL({stateDir:a}));if(!n)return aK(e,{connected:!1,session:r},()=>`No remote connection for "${r}".`),!0;let o=n.session;try{await t.sessions.close({shutdown:e.shutdown})}catch{}await aU(n.metro);let s=!1;if(n.leaseId)try{s=(await t.leases.release({tenant:n.tenant,runId:n.runId,leaseId:n.leaseId})).released}catch{}return a$({stateDir:a,session:o}),aK(e,{connected:!1,session:o,released:s},()=>`Disconnected remote session "${o}".`),!0},a9=async({positionals:e,flags:t})=>{if("status"!==e[0])throw new eg("INVALID_ARGS","connection accepts only: status");let r=t.session??"default",a=en(t.stateDir).baseDir,n=aA({stateDir:a,session:r})??(t.session?null:aL({stateDir:a}));if(!n)return aK(t,{connected:!1,session:r},()=>`No remote connection for "${r}".`),!0;let o=function(e){if(!e.runtime&&nt(e.remoteConfigPath))return ne(e.remoteConfigPath)}(n);return aK(t,nr(n,o),()=>[`Connected remote session "${n.session}".`,`tenant=${n.tenant} runId=${n.runId} leaseId=${n.leaseId??"pending"} backend=${n.leaseBackend??"pending"}`,`remoteConfig=${n.remoteConfigPath}`,n.runtime?"metro=prepared":"metro=not-prepared",o?.message].filter(e=>!!e).join("\n")),!0};function ne(e){let t=`agent-device metro prepare --remote-config ${e}`;return{status:"deferred",nextStep:t,message:`Metro runtime is not prepared yet; it will be prepared automatically on first open, or run "${t}" to inspect it before launch.`}}function nt(e){try{let t=ak({configPath:e,cwd:process.cwd(),env:process.env}).profile;return!!(t.metroPublicBaseUrl||t.metroProxyBaseUrl||t.metroProjectRoot||t.metroKind)}catch{return!1}}function nr(e,t){return{connected:!0,session:e.session,tenant:e.tenant,runId:e.runId,leaseAllocated:!!e.leaseId,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},...t?{runtimePreparation:t}:{},connectedAt:e.connectedAt,updatedAt:e.updatedAt}}let na=async({flags:e,client:t})=>{let r=D(await t.capture.snapshot({...aH(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return aK(e,r,()=>(function(e,t={}){var r,a,n;let o,s=e.nodes,i=Array.isArray(s)?s:[],l="string"==typeof e.backend?e.backend:void 0,c=t.raw||"macos-helper"===l?null:G(i),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??i,h=t.raw||"macos-helper"===l?null:function(e,t,r,a){let n=e.visibility;if(n&&"object"==typeof n&&"boolean"==typeof n.partial&&"number"==typeof n.visibleNodeCount&&"number"==typeof n.totalNodeCount&&Array.isArray(n.reasons))return{partial:n.partial,visibleNodeCount:n.visibleNodeCount,totalNodeCount:n.totalNodeCount,reasons:n.reasons.filter(e=>"string"==typeof e)};let o=t?.hiddenCount??0,s=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return o>0?{partial:!0,visibleNodeCount:r,totalNodeCount:a,reasons:["offscreen-nodes"]}:s?{partial:!0,visibleNodeCount:r,totalNodeCount:r,reasons:[]}:null}(e,c,f.length,i.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: ${i.length} nodes${u?" (truncated)":""}`,y=m.length>0?`${m.join("\n")}
30
+ `:"",w=(r=e,a=i,n=t,o=ts(r),!n.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let r of e){let e=(r.type??"").toLowerCase(),a=J(r).trim().toLowerCase();if(!a)continue;let n=`${e}|${a}`;t.set(n,(t.get(n)??0)+1)}let r=0;for(let e of t.values())e>1&&(r+=e);return r>=8}(a)&&o.push("Warning: possible repeated nav subtree detected."),o),b=w.length>0?`${w.join("\n")}
31
31
  `:"";if(0===i.length)return`${y}${g}
32
32
  ${b}`;if(t.raw){let e=i.map(e=>JSON.stringify(e));return`${y}${g}
33
33
  ${b}${e.join("\n")}
34
- `}if(t.flatten){let e=B(f,{summarizeTextSurfaces:!0}).flatMap(e=>[eu(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...ti({...e,depth:0})]),t=c&&c.summaryLines.length>0?`
34
+ `}if(t.flatten){let e=V(f,{summarizeTextSurfaces:!0}).flatMap(e=>[eu(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...ti({...e,depth:0})]),t=c&&c.summaryLines.length>0?`
35
35
  ${c.summaryLines.join("\n")}`:"";return`${y}${g}
36
36
  ${b}${e.join("\n")}${t}
37
- `}let v=B(f,{summarizeTextSurfaces:!0}).flatMap(e=>[e.text,...ti(e)]),I=c&&c.summaryLines.length>0?`
37
+ `}let v=V(f,{summarizeTextSurfaces:!0}).flatMap(e=>[e.text,...ti(e)]),I=c&&c.summaryLines.length>0?`
38
38
  ${c.summaryLines.join("\n")}`:"";return`${y}${g}
39
39
  ${b}${v.join("\n")}${I}
40
- `})(r,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0};function a2(e,t,r){var a,n;let o,s=i.isAbsolute(e)?e:i.resolve(t,e);if(r&&(a=s,n=r,""!==(o=i.relative(n,a))&&(o.startsWith("..")||i.isAbsolute(o))))throw new eg("INVALID_ARGS","Local path is outside the artifact adapter root",{path:s,rootDir:r});return s}let a3=async({positionals:e,flags:t,client:r})=>{let a=await r.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs,...void 0!==t.screenshotFullscreen?{fullscreen:t.screenshotFullscreen}:{}});return aw(t,{path:a.path,...a.overlayRefs?{overlayRefs:a.overlayRefs}:{}},()=>a.overlayRefs?`Annotated ${a.overlayRefs.length} refs onto ${a.path}`:a.path),!0},a5=async({positionals:e,flags:t,client:r})=>{var a;if("snapshot"===e[0]){let e=await r.capture.diff({...ay(t),kind:"snapshot",out:t.out,interactiveOnly:t.snapshotInteractiveOnly,compact:t.snapshotCompact,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw});return aw(t,e,()=>(function(e){var t;let r=!0===e.baselineInitialized,a=e.summary??{},n=ta(a.additions),o=ta(a.removals),s=ta(a.unchanged),i=tn(),c=ts(e),u=c.length>0?`${c.join("\n")}
40
+ `})(r,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0};function nn(e,t,r){var a,n;let o,s=i.isAbsolute(e)?e:i.resolve(t,e);if(r&&(a=s,n=r,""!==(o=i.relative(n,a))&&(o.startsWith("..")||i.isAbsolute(o))))throw new eg("INVALID_ARGS","Local path is outside the artifact adapter root",{path:s,rootDir:r});return s}let no=async({positionals:e,flags:t,client:r})=>{let a=await r.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs,...void 0!==t.screenshotFullscreen?{fullscreen:t.screenshotFullscreen}:{}});return aK(t,{path:a.path,...a.overlayRefs?{overlayRefs:a.overlayRefs}:{}},()=>a.overlayRefs?`Annotated ${a.overlayRefs.length} refs onto ${a.path}`:a.path),!0},ns=async({positionals:e,flags:t,client:r})=>{var a;if("snapshot"===e[0]){let e=await r.capture.diff({...aH(t),kind:"snapshot",out:t.out,interactiveOnly:t.snapshotInteractiveOnly,compact:t.snapshotCompact,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw});return aK(t,e,()=>(function(e){var t;let r=!0===e.baselineInitialized,a=e.summary??{},n=ta(a.additions),o=ta(a.removals),s=ta(a.unchanged),i=tn(),c=ts(e),u=c.length>0?`${c.join("\n")}
41
41
  `:"";if(r)return`${u}Baseline initialized (${s} lines).
42
- `;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 a of t){let t=Math.max(0,a-1),n=Math.min(e.length-1,a+1);for(let e=t;e<=n;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 i?l("green",e):e}if("removed"===e.kind){let e=t.startsWith(" ")?`-${t}`:`- ${t}`;return i?l("red",e):e}return i?l("dim",t):t}),d=p.length>0?`${p.join("\n")}
43
- `:"";if(!i)return`${u}${d}${n} additions, ${o} removals, ${s} unchanged
44
- `;let m=`${(t=String(n),l("green",t))} additions, ${l("red",String(o))} removals, ${l("dim",String(s))} unchanged`;return`${u}${d}${m}
45
- `})(e)),!0}if("screenshot"!==e[0])return!1;let n=t.baseline;if(!n||"string"!=typeof n)throw new eg("INVALID_ARGS","diff screenshot requires --baseline <path>");let o=Y(n),s="string"==typeof t.out?Y(t.out):void 0,c=e[1];if(e.length>2)throw new eg("INVALID_ARGS","diff screenshot accepts at most one current screenshot path");let u=el({backend:(a=r,{platform:function(e){switch(e.platform){case"android":case"linux":case"macos":return e.platform;default:return"ios"}}(t),captureScreenshot:async(e,t,r)=>{let n=await a.capture.screenshot({path:t,session:e.session,overlayRefs:r?.overlayRefs,fullscreen:r?.fullscreen,surface:r?.surface});return{path:n.path,...n.overlayRefs?{overlayRefs:n.overlayRefs}:{}}}}),artifacts:function(e={}){let t=e.cwd??process.cwd(),r=e.tempDir??g.tmpdir(),a=e.rootDir?a2(e.rootDir,t):void 0;return{resolveInput:async e=>{if("uploadedArtifact"===e.kind)throw new eg("UNSUPPORTED_OPERATION","Uploaded artifact inputs require a custom artifact adapter");return{path:a2(e.path,t,a)}},reserveOutput:async(e,n)=>{let o,s=n.visibility??"client-visible",l=e?.kind==="path"?a2(e.path,t,a):i.join(o=await h.mkdtemp(i.join(r,`agent-device-${n.field}-`)),`${n.field}${n.ext}`);return await h.mkdir(i.dirname(l),{recursive:!0}),{path:l,visibility:s,...o?{cleanup:async()=>{await h.rm(o,{recursive:!0,force:!0})}}:{},publish:async()=>e?.kind==="downloadableArtifact"?{kind:"localPath",field:n.field,path:l,fileName:e.fileName??i.basename(e.clientPath??l)}:void 0}},createTempFile:async e=>{let t=await h.mkdtemp(i.join(r,`${e.prefix}-`));return{path:i.join(t,`file${e.ext}`),visibility:"internal",cleanup:async()=>{await h.rm(t,{recursive:!0,force:!0})}}}}}(),sessions:{get:e=>({name:e}),set:()=>{}},policy:j()}),p=await u.capture.diffScreenshot({session:t.session,baseline:{kind:"path",path:o},current:c?{kind:"path",path:Y(c)}:{kind:"live"},...s?{out:{kind:"path",path:s}}:{},threshold:function(e){if(null!=e&&""!==e)return Number(e)}(t.threshold),overlayRefs:t.overlayRefs,surface:t.surface});return aw(t,p,()=>(function(e){let t=tn(),r=!0===e.match,a=ta(e.differentPixels),n=ta(e.totalPixels),o=ta(e.mismatchPercentage),s=e.diffPath,i=e.dimensionMismatch,c=[];if(r){let e=t?l("green","✓"):"✓";c.push(`${e} Screenshots match.`)}else if(i){let e=t?l("red","✗"):"✗",r=i.expected,a=i.actual;c.push(`${e} Screenshots have different dimensions: expected ${r?.width}x${r?.height}, got ${a?.width}x${a?.height}`)}else{let e=t?l("red","✗"):"✗",r=0===o&&a>0?"<0.01":String(o),n=`${r}% pixels differ`;c.push(`${e} ${t?l("red",n):n}`)}if(s&&!r){let e=tr(s),r=t?l("dim","Diff image:"):"Diff image:",a=t?l("green",e):e;c.push(` ${r} ${a}`)}if(e.currentOverlayPath&&!r){let r=tr(e.currentOverlayPath),a=t?l("dim","Current overlay:"):"Current overlay:",n=t?l("green",r):r,o=ta(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:"";c.push(` ${a} ${n}${s}`)}if(!r&&!i){let e=t?l("red",String(a)):String(a);c.push(` ${e} different / ${n} total pixels`)}let u=r||i?[]: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=${tt(r.xRange)}px dy=${tt(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(te).join("; ")}`);let a=(e.nonTextDeltas??[]).filter(e=>"separator"===e.likelyKind).slice(0,2);return a.length>0&&t.push(`non-text boundaries: ${a.map(te).join("; ")}`),t.slice(0,6)}(e);if(u.length>0)for(let e of(c.push(` ${to("Hints:",t)}`),u))c.push(` - ${e}`);let p=Array.isArray(e.regions)?e.regions:[];if(!r&&!i&&p.length>0)for(let e of(c.push(` ${to("Changed regions:",t)}`),p.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 a=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);a&&c.push(` ${a}`);let n=e.currentOverlayMatches?.[0];if(n){let e=n.label?` "${n.label}"`:"";c.push(` overlaps @${n.ref}${e}, ${n.regionCoveragePercentage}% of region`)}}let d=e.ocr?.matches??[];if(!r&&!i&&d.length>0){let r=d.slice(0,8);for(let[a,n]of(c.push(` ${to(`OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${r.length}/${d.length}; px):`,t)}`),c.push(` ${to("item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint",t)}`),r.entries())){let e=n.delta;c.push(` ${a+1} | ${JSON.stringify(n.text)} | ${e9(e.x)},${e9(e.y)} | ${e9(e.width)},${e9(e.height)} | ${e7(n.baselineRect)} | ${e7(n.currentRect)} | ${n.confidence} | ${n.possibleTextMetricMismatch?"ocr-bbox-size-change":"-"}`)}}let m=e.nonTextDeltas??[];if(!r&&!i&&m.length>0){let e=m.slice(0,8);for(let r of(c.push(` ${to(`Non-text visual deltas (showing ${e.length}/${m.length}; px):`,t)}`),c.push(` ${to("item | region | slot | kind | bboxCurrent | nearestText",t)}`),e))c.push(` ${r.index} | ${r.regionIndex?`r${r.regionIndex}`:"-"} | ${r.slot} | ${r.likelyKind} | ${e7(r.rect)} | ${r.nearestText?JSON.stringify(r.nearestText):"-"}`)}return`${c.join("\n")}
46
- `})(p)),!0};function a8(e){return null===e?{}:{timeoutMs:e}}function a4(e){let{suite:t,json:r,verbose:a,reportJunit:n}=e;return(n&&function(e,t){let r=i.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="${a9(e.durationMs)}">`];for(let r of e.tests)t.push(...function(e){let t=ne(i.basename(e.file)),r=ne("."===i.dirname(e.file)?e.file:i.dirname(e.file)),a=ne(e.file),n=a9(e.durationMs),o=[` <testcase classname="${r}" name="${t}" file="${a}" time="${n}">`];"failed"===e.status?o.push(` <failure message="${ne(e.error.message)}">${ne(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&&o.push(` <skipped message="${ne(e.message)}" />`);let s=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 s&&o.push(` <system-out>${ne(s)}</system-out>`),o.push(" </testcase>"),o}(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 eg("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(n,t),r)?(e4({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let r=e.tests.filter(a7);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return a6(e);let t="passed"===e.status?a7(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",r="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",a=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${r}${a}
42
+ `;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 a of t){let t=Math.max(0,a-1),n=Math.min(e.length-1,a+1);for(let e=t;e<=n;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 i?l("green",e):e}if("removed"===e.kind){let e=t.startsWith(" ")?`-${t}`:`- ${t}`;return i?l("red",e):e}return i?l("dim",t):t}),p=d.length>0?`${d.join("\n")}
43
+ `:"";if(!i)return`${u}${p}${n} additions, ${o} removals, ${s} unchanged
44
+ `;let m=`${(t=String(n),l("green",t))} additions, ${l("red",String(o))} removals, ${l("dim",String(s))} unchanged`;return`${u}${p}${m}
45
+ `})(e)),!0}if("screenshot"!==e[0])return!1;let n=t.baseline;if(!n||"string"!=typeof n)throw new eg("INVALID_ARGS","diff screenshot requires --baseline <path>");let o=Y(n),s="string"==typeof t.out?Y(t.out):void 0,c=e[1];if(e.length>2)throw new eg("INVALID_ARGS","diff screenshot accepts at most one current screenshot path");let u=el({backend:(a=r,{platform:function(e){switch(e.platform){case"android":case"linux":case"macos":return e.platform;default:return"ios"}}(t),captureScreenshot:async(e,t,r)=>{let n=await a.capture.screenshot({path:t,session:e.session,overlayRefs:r?.overlayRefs,fullscreen:r?.fullscreen,surface:r?.surface});return{path:n.path,...n.overlayRefs?{overlayRefs:n.overlayRefs}:{}}}}),artifacts:function(e={}){let t=e.cwd??process.cwd(),r=e.tempDir??g.tmpdir(),a=e.rootDir?nn(e.rootDir,t):void 0;return{resolveInput:async e=>{if("uploadedArtifact"===e.kind)throw new eg("UNSUPPORTED_OPERATION","Uploaded artifact inputs require a custom artifact adapter");return{path:nn(e.path,t,a)}},reserveOutput:async(e,n)=>{let o,s=n.visibility??"client-visible",l=e?.kind==="path"?nn(e.path,t,a):i.join(o=await h.mkdtemp(i.join(r,`agent-device-${n.field}-`)),`${n.field}${n.ext}`);return await h.mkdir(i.dirname(l),{recursive:!0}),{path:l,visibility:s,...o?{cleanup:async()=>{await h.rm(o,{recursive:!0,force:!0})}}:{},publish:async()=>e?.kind==="downloadableArtifact"?{kind:"localPath",field:n.field,path:l,fileName:e.fileName??i.basename(e.clientPath??l)}:void 0}},createTempFile:async e=>{let t=await h.mkdtemp(i.join(r,`${e.prefix}-`));return{path:i.join(t,`file${e.ext}`),visibility:"internal",cleanup:async()=>{await h.rm(t,{recursive:!0,force:!0})}}}}}(),sessions:{get:e=>({name:e}),set:()=>{}},policy:j()}),d=await u.capture.diffScreenshot({session:t.session,baseline:{kind:"path",path:o},current:c?{kind:"path",path:Y(c)}:{kind:"live"},...s?{out:{kind:"path",path:s}}:{},threshold:function(e){if(null!=e&&""!==e)return Number(e)}(t.threshold),overlayRefs:t.overlayRefs,surface:t.surface});return aK(t,d,()=>(function(e){let t=tn(),r=!0===e.match,a=ta(e.differentPixels),n=ta(e.totalPixels),o=ta(e.mismatchPercentage),s=e.diffPath,i=e.dimensionMismatch,c=[];if(r){let e=t?l("green","✓"):"✓";c.push(`${e} Screenshots match.`)}else if(i){let e=t?l("red","✗"):"✗",r=i.expected,a=i.actual;c.push(`${e} Screenshots have different dimensions: expected ${r?.width}x${r?.height}, got ${a?.width}x${a?.height}`)}else{let e=t?l("red","✗"):"✗",r=0===o&&a>0?"<0.01":String(o),n=`${r}% pixels differ`;c.push(`${e} ${t?l("red",n):n}`)}if(s&&!r){let e=tr(s),r=t?l("dim","Diff image:"):"Diff image:",a=t?l("green",e):e;c.push(` ${r} ${a}`)}if(e.currentOverlayPath&&!r){let r=tr(e.currentOverlayPath),a=t?l("dim","Current overlay:"):"Current overlay:",n=t?l("green",r):r,o=ta(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:"";c.push(` ${a} ${n}${s}`)}if(!r&&!i){let e=t?l("red",String(a)):String(a);c.push(` ${e} different / ${n} total pixels`)}let u=r||i?[]: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=${tt(r.xRange)}px dy=${tt(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(te).join("; ")}`);let a=(e.nonTextDeltas??[]).filter(e=>"separator"===e.likelyKind).slice(0,2);return a.length>0&&t.push(`non-text boundaries: ${a.map(te).join("; ")}`),t.slice(0,6)}(e);if(u.length>0)for(let e of(c.push(` ${to("Hints:",t)}`),u))c.push(` - ${e}`);let d=Array.isArray(e.regions)?e.regions:[];if(!r&&!i&&d.length>0)for(let e of(c.push(` ${to("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 a=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);a&&c.push(` ${a}`);let n=e.currentOverlayMatches?.[0];if(n){let e=n.label?` "${n.label}"`:"";c.push(` overlaps @${n.ref}${e}, ${n.regionCoveragePercentage}% of region`)}}let p=e.ocr?.matches??[];if(!r&&!i&&p.length>0){let r=p.slice(0,8);for(let[a,n]of(c.push(` ${to(`OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${r.length}/${p.length}; px):`,t)}`),c.push(` ${to("item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint",t)}`),r.entries())){let e=n.delta;c.push(` ${a+1} | ${JSON.stringify(n.text)} | ${e9(e.x)},${e9(e.y)} | ${e9(e.width)},${e9(e.height)} | ${e7(n.baselineRect)} | ${e7(n.currentRect)} | ${n.confidence} | ${n.possibleTextMetricMismatch?"ocr-bbox-size-change":"-"}`)}}let m=e.nonTextDeltas??[];if(!r&&!i&&m.length>0){let e=m.slice(0,8);for(let r of(c.push(` ${to(`Non-text visual deltas (showing ${e.length}/${m.length}; px):`,t)}`),c.push(` ${to("item | region | slot | kind | bboxCurrent | nearestText",t)}`),e))c.push(` ${r.index} | ${r.regionIndex?`r${r.regionIndex}`:"-"} | ${r.slot} | ${r.likelyKind} | ${e7(r.rect)} | ${r.nearestText?JSON.stringify(r.nearestText):"-"}`)}return`${c.join("\n")}
46
+ `})(d)),!0};function ni(e){return null===e?{}:{timeoutMs:e}}function nl(e){let{suite:t,json:r,verbose:a,reportJunit:n}=e;return(n&&function(e,t){let r=i.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="${nd(e.durationMs)}">`];for(let r of e.tests)t.push(...function(e){let t=np(i.basename(e.file)),r=np("."===i.dirname(e.file)?e.file:i.dirname(e.file)),a=np(e.file),n=nd(e.durationMs),o=[` <testcase classname="${r}" name="${t}" file="${a}" time="${n}">`];"failed"===e.status?o.push(` <failure message="${np(e.error.message)}">${np(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&&o.push(` <skipped message="${np(e.message)}" />`);let s=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 s&&o.push(` <system-out>${np(s)}</system-out>`),o.push(" </testcase>"),o}(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 eg("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(n,t),r)?(e4({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let r=e.tests.filter(nu);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return nc(e);let t="passed"===e.status?nu(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",r="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",a=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${r}${a}
48
48
  `),"skipped"===e.status&&process.stdout.write(` ${e.message??"skipped"}
49
- `)}(t);else{for(let t of e.failures)a6(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)nc(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}
50
50
  `)}(e)}let a="number"==typeof e.durationMs?e.durationMs:void 0,n=r.length>0?`, ${r.length} flaky`:"";return process.stdout.write(`Test summary: ${e.passed} passed, ${e.failed} failed${n}${void 0!==a?` in ${a}ms`:""}
51
- `),function(e){return+(e.failed>0)}(e)}(t,{verbose:a})}function a6(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:a})}function nc(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}
52
52
  `),process.stdout.write(` ${e.error?.message??"Unknown test failure"}
53
53
  `),e.error?.hint&&process.stdout.write(` hint: ${e.error.hint}
54
54
  `),e.artifactsDir&&process.stdout.write(` artifacts: ${e.artifactsDir}
55
55
  `),e.error?.logPath&&process.stdout.write(` log: ${e.error.logPath}
56
56
  `),e.error?.diagnosticId&&process.stdout.write(` diagnostic: ${e.error.diagnosticId}
57
- `)}function a7(e){return"passed"===e.status&&e.attempts>1}function a9(e){return(Math.max(0,e)/1e3).toFixed(3)}function ne(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}let nt={[rL]:nr(rL,({client:e,flags:t})=>e.devices.boot({...ay(t),headless:t.headless})),[rH]:nr(rH,({client:e,positionals:t,flags:r})=>e.apps.push({...ay(r),app:ns(t[0],"push requires bundleOrPackage"),payload:ns(t[1],"push requires payloadOrJson")})),[rB]:nr(rB,({client:e,flags:t})=>e.observability.perf(ay(t))),[rP]:nr(rP,({client:e,positionals:t,flags:r})=>e.interactions.click({...nn(t),...na(r),...ay(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap,button:r.clickButton})),get:nr("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)),...na(r),...ay(r),format:function(e){if("text"===e||"attrs"===e)return e;throw new eg("INVALID_ARGS","get only supports text or attrs")}(t[0])})),[rK]:nr(rK,({client:e,positionals:t,flags:r})=>e.replay.run({...ay(r),path:ns(t[0],"replay requires path"),update:r.replayUpdate})),[r0]:nr(r0,({client:e,positionals:t,flags:r})=>(({json:r.json}).json||process.stderr.write("Running replay suite...\n"),e.replay.test({...ay(r),paths:t,update:r.replayUpdate,failFast:r.failFast,timeoutMs:r.timeoutMs,retries:r.retries,artifactsDir:r.artifactsDir,reportJunit:r.reportJunit}))),[rN]:nr(rN,({client:e,flags:t})=>e.batch.run({...ay(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out})),[rq]:nr(rq,({client:e,positionals:t,flags:r})=>e.interactions.press({...nn(t),...na(r),...ay(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap})),[rj]:nr(rj,({client:e,positionals:t,flags:r})=>e.interactions.longPress({...ay(r),x:Number(t[0]),y:Number(t[1]),durationMs:ni(t[2])})),[rQ]:nr(rQ,({client:e,positionals:t,flags:r})=>e.interactions.swipe({...ay(r),from:{x:Number(t[0]),y:Number(t[1])},to:{x:Number(t[2]),y:Number(t[3])},durationMs:ni(t[4]),count:r.count,pauseMs:r.pauseMs,pattern:r.pattern})),[rO]:nr(rO,({client:e,positionals:t,flags:r})=>e.interactions.focus({...ay(r),x:Number(t[0]),y:Number(t[1])})),[r3]:nr(r3,({client:e,positionals:t,flags:r})=>e.interactions.type({...ay(r),text:t.join(" "),delayMs:r.delayMs})),[rR]:nr(rR,({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=M(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),...na(r),...ay(r),delayMs:r.delayMs})),[rW]:nr(rW,({client:e,positionals:t,flags:r})=>e.interactions.scroll({...ay(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:ni(t[1]),pixels:r.pixels})),[rG]:nr(rG,({client:e,positionals:t,flags:r})=>e.interactions.pinch({...ay(r),scale:Number(t[0]),x:ni(t[1]),y:ni(t[2])})),[r2]:nr(r2,({client:e,positionals:t,flags:r})=>e.apps.triggerEvent({...ay(r),event:ns(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})),[rJ]:nr(rJ,({client:e,positionals:t,flags:r})=>e.recording.record({...ay(r),action:no(t[0],"record"),path:t[1],fps:r.fps,quality:function(e){if(void 0!==e){if([5,6,7,8,9,10].includes(e))return e;throw new eg("INVALID_ARGS",`Invalid quality: ${e}`)}}(r.quality),hideTouches:r.hideTouches})),[r1]:nr(r1,({client:e,positionals:t,flags:r})=>e.recording.trace({...ay(r),action:no(t[0],"trace"),path:t[1]})),[rF]:nr(rF,({client:e,positionals:t,flags:r})=>e.observability.logs({...ay(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})),[rV]:nr(rV,({client:e,positionals:t,flags:r})=>e.observability.network({...ay(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:ni(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])})),[rT]:nr(rT,({client:e,positionals:t,flags:r})=>{var a;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,a=r?e[1]:e[0],n=r?2:1,o=e[n];if(void 0===o)return{locator:t,query:ns(a,"find requires query")};if("get"===o){let r=e[n+1];if("text"===r)return{locator:t,query:ns(a,"find requires query"),action:"getText"};if("attrs"===r)return{locator:t,query:ns(a,"find requires query"),action:"getAttrs"};throw new eg("INVALID_ARGS","find get only supports text or attrs")}if("wait"===o)return{locator:t,query:ns(a,"find requires query"),action:"wait",timeoutMs:ni(e[n+1])};if("fill"===o||"type"===o)return{locator:t,query:ns(a,"find requires query"),action:o,value:e.slice(n+1).join(" ")};if("click"===o||"focus"===o||"exists"===o)return{locator:t,query:ns(a,"find requires query"),action:o};throw new eg("INVALID_ARGS",`Unsupported find action: ${o}`)}(t),...{depth:(a=r).snapshotDepth,raw:a.snapshotRaw},...ay(r),first:r.findFirst,last:r.findLast})}),is:nr("is",({client:e,positionals:t,flags:r})=>e.interactions.is({...function(e){let t=e[0],r=M(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),...na(r),...ay(r)})),[rY]:nr(rY,({client:e,positionals:t,flags:r})=>e.settings.update(function(e,t){let r=ay(t),a=e[0],n=e[1];if(("wifi"===a||"airplane"===a||"location"===a)&&("on"===n||"off"===n)||"appearance"===a&&("light"===n||"dark"===n||"toggle"===n)||("faceid"===a||"touchid"===a)&&("match"===n||"nonmatch"===n||"enroll"===n||"unenroll"===n)||"fingerprint"===a&&("match"===n||"nonmatch"===n))return{...r,setting:a,state:n};if("permission"===a&&("grant"===n||"deny"===n||"reset"===n))return{...r,setting:a,state:n,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 nr(e,t){return async({positionals:r,flags:a,client:n})=>{let o=await t({client:n,positionals:r,flags:a}),s=function(e,t,r,a){if(r.json)return e===r0?a4({suite:a,json:!0,reportJunit:r.reportJunit}):(e4({success:!0,data:a}),0);if(e===r0)return a4({suite:a,verbose:r.verbose,reportJunit:r.reportJunit});if(e===rN)return!function(e){let t="number"==typeof e.total?e.total:0,r="number"==typeof e.executed?e.executed:0,a="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let o of(process.stdout.write(`Batch completed: ${r}/${t} steps${void 0!==a?` in ${a}ms`:""}
57
+ `)}function nu(e){return"passed"===e.status&&e.attempts>1}function nd(e){return(Math.max(0,e)/1e3).toFixed(3)}function np(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}let nm={[rP]:nf(rP,({client:e,flags:t})=>e.devices.boot({...aH(t),headless:t.headless})),[rH]:nf(rH,({client:e,positionals:t,flags:r})=>e.apps.push({...aH(r),app:nw(t[0],"push requires bundleOrPackage"),payload:nw(t[1],"push requires payloadOrJson")})),[rV]:nf(rV,({client:e,flags:t})=>e.observability.perf(aH(t))),[rL]:nf(rL,({client:e,positionals:t,flags:r})=>e.interactions.click({...ng(t),...nh(r),...aH(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap,button:r.clickButton})),get:nf("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)),...nh(r),...aH(r),format:function(e){if("text"===e||"attrs"===e)return e;throw new eg("INVALID_ARGS","get only supports text or attrs")}(t[0])})),[rJ]:nf(rJ,({client:e,positionals:t,flags:r})=>e.replay.run({...aH(r),path:nw(t[0],"replay requires path"),update:r.replayUpdate})),[r0]:nf(r0,({client:e,positionals:t,flags:r})=>(({json:r.json}).json||process.stderr.write("Running replay suite...\n"),e.replay.test({...aH(r),paths:t,update:r.replayUpdate,failFast:r.failFast,timeoutMs:r.timeoutMs,retries:r.retries,artifactsDir:r.artifactsDir,reportJunit:r.reportJunit}))),[rN]:nf(rN,({client:e,flags:t})=>e.batch.run({...aH(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out})),[rq]:nf(rq,({client:e,positionals:t,flags:r})=>e.interactions.press({...ng(t),...nh(r),...aH(r),count:r.count,intervalMs:r.intervalMs,holdMs:r.holdMs,jitterPx:r.jitterPx,doubleTap:r.doubleTap})),[rj]:nf(rj,({client:e,positionals:t,flags:r})=>e.interactions.longPress({...aH(r),x:Number(t[0]),y:Number(t[1]),durationMs:nb(t[2])})),[rQ]:nf(rQ,({client:e,positionals:t,flags:r})=>e.interactions.swipe({...aH(r),from:{x:Number(t[0]),y:Number(t[1])},to:{x:Number(t[2]),y:Number(t[3])},durationMs:nb(t[4]),count:r.count,pauseMs:r.pauseMs,pattern:r.pattern})),[rC]:nf(rC,({client:e,positionals:t,flags:r})=>e.interactions.focus({...aH(r),x:Number(t[0]),y:Number(t[1])})),[r3]:nf(r3,({client:e,positionals:t,flags:r})=>e.interactions.type({...aH(r),text:t.join(" "),delayMs:r.delayMs})),[rR]:nf(rR,({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=M(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),...nh(r),...aH(r),delayMs:r.delayMs})),[rW]:nf(rW,({client:e,positionals:t,flags:r})=>e.interactions.scroll({...aH(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:nb(t[1]),pixels:r.pixels})),[rG]:nf(rG,({client:e,positionals:t,flags:r})=>e.interactions.pinch({...aH(r),scale:Number(t[0]),x:nb(t[1]),y:nb(t[2])})),[r2]:nf(r2,({client:e,positionals:t,flags:r})=>e.apps.triggerEvent({...aH(r),event:nw(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})),[rK]:nf(rK,({client:e,positionals:t,flags:r})=>e.recording.record({...aH(r),action:ny(t[0],"record"),path:t[1],fps:r.fps,quality:r.quality,hideTouches:r.hideTouches})),[r1]:nf(r1,({client:e,positionals:t,flags:r})=>e.recording.trace({...aH(r),action:ny(t[0],"trace"),path:t[1]})),[rF]:nf(rF,({client:e,positionals:t,flags:r})=>e.observability.logs({...aH(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})),[rB]:nf(rB,({client:e,positionals:t,flags:r})=>e.observability.network({...aH(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:nb(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])})),[rT]:nf(rT,({client:e,positionals:t,flags:r})=>{var a;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,a=r?e[1]:e[0],n=r?2:1,o=e[n];if(void 0===o)return{locator:t,query:nw(a,"find requires query")};if("get"===o){let r=e[n+1];if("text"===r)return{locator:t,query:nw(a,"find requires query"),action:"getText"};if("attrs"===r)return{locator:t,query:nw(a,"find requires query"),action:"getAttrs"};throw new eg("INVALID_ARGS","find get only supports text or attrs")}if("wait"===o)return{locator:t,query:nw(a,"find requires query"),action:"wait",timeoutMs:nb(e[n+1])};if("fill"===o||"type"===o)return{locator:t,query:nw(a,"find requires query"),action:o,value:e.slice(n+1).join(" ")};if("click"===o||"focus"===o||"exists"===o)return{locator:t,query:nw(a,"find requires query"),action:o};throw new eg("INVALID_ARGS",`Unsupported find action: ${o}`)}(t),...{depth:(a=r).snapshotDepth,raw:a.snapshotRaw},...aH(r),first:r.findFirst,last:r.findLast})}),is:nf("is",({client:e,positionals:t,flags:r})=>e.interactions.is({...function(e){let t=e[0],r=M(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),...nh(r),...aH(r)})),[rY]:nf(rY,({client:e,positionals:t,flags:r})=>e.settings.update(function(e,t){let r=aH(t),a=e[0],n=e[1];if(("wifi"===a||"airplane"===a||"location"===a)&&("on"===n||"off"===n)||"appearance"===a&&("light"===n||"dark"===n||"toggle"===n)||("faceid"===a||"touchid"===a)&&("match"===n||"nonmatch"===n||"enroll"===n||"unenroll"===n)||"fingerprint"===a&&("match"===n||"nonmatch"===n))return{...r,setting:a,state:n};if("permission"===a&&("grant"===n||"deny"===n||"reset"===n))return{...r,setting:a,state:n,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 nf(e,t){return async({positionals:r,flags:a,client:n})=>{let o=await t({client:n,positionals:r,flags:a}),s=function(e,t,r,a){if(r.json)return e===r0?nl({suite:a,json:!0,reportJunit:r.reportJunit}):(e4({success:!0,data:a}),0);if(e===r0)return nl({suite:a,verbose:r.verbose,reportJunit:r.reportJunit});if(e===rN)return!function(e){let t="number"==typeof e.total?e.total:0,r="number"==typeof e.executed?e.executed:0,a="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let o of(process.stdout.write(`Batch completed: ${r}/${t} steps${void 0!==a?` in ${a}ms`:""}
58
58
  `),Array.isArray(e.results)?e.results:[])){var n;if(!o||"object"!=typeof o)continue;let e="number"==typeof o.step?o.step:void 0,t="string"==typeof o.command?o.command:"step",r=!1!==o.ok,a="number"==typeof o.durationMs?o.durationMs:void 0,s=o.data&&"object"==typeof o.data?o.data:void 0,i=o.error&&"object"==typeof o.error?o.error:void 0,l=r?U(s)??t:(n=i,("string"==typeof n?.message&&n.message.length>0?n.message:null)??t),c=void 0!==e?`${e}. `:"- ",u=void 0!==a?` (${a}ms)`:"";process.stdout.write(`${c}${r?"OK":"FAILED"} ${l}${u}
59
59
  `)}}(a),0;if("get"===e){let e=t[0];if("text"===e)return process.stdout.write(`${"string"==typeof a.text?a.text:""}
60
60
  `),0;if("attrs"===e)return process.stdout.write(`${JSON.stringify(a.node??{},null,2)}
@@ -62,28 +62,28 @@ ${b}${v.join("\n")}${I}
62
62
  `),0;if("boolean"==typeof a.found)return process.stdout.write(`Found: ${a.found}
63
63
  `),0;if(a.node)return process.stdout.write(`${JSON.stringify(a.node,null,2)}
64
64
  `),0}if("is"===e)return process.stdout.write(`Passed: is ${a.predicate??"assertion"}
65
- `),0;if(e===rL){let e=a.platform??"unknown",t=a.device??a.id??"unknown";return process.stdout.write(`Boot ready: ${t} (${e})
66
- `),0}if(e===rJ){let e="string"==typeof a.outPath?a.outPath:"";return e&&process.stdout.write(`${e}
65
+ `),0;if(e===rP){let e=a.platform??"unknown",t=a.device??a.id??"unknown";return process.stdout.write(`Boot ready: ${t} (${e})
66
+ `),0}if(e===rK){let e="string"==typeof a.outPath?a.outPath:"";return e&&process.stdout.write(`${e}
67
67
  `),0}if(e===rF)return function(e,t){let r="string"==typeof e.path?e.path:"";if(!r)return;process.stdout.write(`${r}
68
68
  `);let a=["active","state","backend","sizeBytes"].map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ");a&&!t.json&&process.stderr.write(`${a}
69
69
  `);let n=["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(n&&!t.json&&process.stderr.write(`${n}
70
70
  `),e.hint&&!t.json&&process.stderr.write(`${e.hint}
71
71
  `),Array.isArray(e.notes)&&!t.json)for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
72
- `)}(a,r),0;if(e===rV)return function(e){let t="string"==typeof e.path?e.path:"";t&&process.stdout.write(`${t}
72
+ `)}(a,r),0;if(e===rB)return function(e){let t="string"==typeof e.path?e.path:"";t&&process.stdout.write(`${t}
73
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>",a="number"==typeof e.status?` status=${e.status}`:"",n="string"==typeof e.timestamp?`${e.timestamp} `:"",o="number"==typeof e.durationMs?` durationMs=${e.durationMs}`:"";process.stdout.write(`${n}${t} ${r}${a}${o}
74
74
  `),"string"==typeof e.headers&&process.stdout.write(` headers: ${e.headers}
75
75
  `),"string"==typeof e.requestBody&&process.stdout.write(` request: ${e.requestBody}
76
76
  `),"string"==typeof e.responseBody&&process.stdout.write(` response: ${e.responseBody}
77
77
  `)}let a=["active","state","backend","include","scannedLines","matchedLines"].map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ");if(a&&process.stderr.write(`${a}
78
78
  `),Array.isArray(e.notes))for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
79
- `)}(a),0;if(e===rP||e===rq){let e=a.ref??"",t=a.x,r=a.y;if(e&&"number"==typeof t&&"number"==typeof r)return process.stdout.write(`Tapped @${e} (${t}, ${r})
80
- `),0}if(e===rB)return process.stdout.write(`${JSON.stringify(a,null,2)}
79
+ `)}(a),0;if(e===rL||e===rq){let e=a.ref??"",t=a.x,r=a.y;if(e&&"number"==typeof t&&"number"==typeof r)return process.stdout.write(`Tapped @${e} (${t}, ${r})
80
+ `),0}if(e===rV)return process.stdout.write(`${JSON.stringify(a,null,2)}
81
81
  `),0;let n=U(a);return n&&process.stdout.write(`${n}
82
- `),0}(e,r,a,o);return 0!==s&&process.exit(s),!0}}function na(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function nn(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=M(e);return t?{selector:t.selectorExpression}:{x:Number(e[0]),y:Number(e[1])}}function no(e,t){if("start"===e||"stop"===e)return e;throw new eg("INVALID_ARGS",`${t} requires start|stop`)}function ns(e,t){if(void 0===e||""===e)throw new eg("INVALID_ARGS",t);return e}function ni(e){return void 0===e?void 0:Number(e)}let nl={...{session:av,[rE]:aI,[r$]:aS,"ensure-simulator":aA,metro:aD,install:a$,reinstall:ax,"install-from-source":aN,connect:aJ,disconnect:aK,connection:az,open:a_,close:aE,[rZ]:a1,[rX]:a3,[rM]:a5},...{[r5]:async({positionals:e,flags:t,client:r})=>(ab(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 a={...ay(t),depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw};if("sleep"===r.kind)return{...a,durationMs:r.durationMs};if("text"===r.kind){if(!r.text)throw new eg("INVALID_ARGS","wait requires text.");return{...a,text:r.text,...a8(r.timeoutMs)}}return"ref"===r.kind?{...a,ref:r.rawRef,...a8(r.timeoutMs)}:{...a,selector:r.selectorExpression,...a8(r.timeoutMs)}}(e,t))),!0),[rA]:async({positionals:e,flags:t,client:r})=>(ab(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]),a=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{...ay(t),...r?{action:r}:{},...void 0!==a?{timeoutMs:a}:{}}}(e,t))),!0),[rD]:async({flags:e,client:t})=>{let r=await t.command.appState(ay(e));return aw(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},[rx]:async({flags:e,client:t})=>(ab(e,await t.command.back({...ay(e),mode:e.backMode})),!0),[rC]:async({flags:e,client:t})=>(ab(e,await t.command.home(ay(e))),!0),[rz]:async({positionals:e,flags:t,client:r})=>(ab(t,await r.command.rotate(function(e,t){if(e.length>1)throw new eg("INVALID_ARGS","rotate accepts exactly one orientation argument.");return{...ay(t),orientation:v(e[0])}}(e,t))),!0),[rS]:async({flags:e,client:t})=>(ab(e,await t.command.appSwitcher(ay(e))),!0),[rU]:async({positionals:e,flags:t,client:r})=>(ab(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{...ay(t),...r?{action:r}:{}}}(e,t))),!0),[r_]:async({positionals:e,flags:t,client:r})=>{var a,n;return a=t,n=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 a=ay(t);if("read"===r){if(1!==e.length)throw new eg("INVALID_ARGS","clipboard read does not accept additional arguments.");return{...a,action:r}}if(e.length<2)throw new eg("INVALID_ARGS","clipboard write requires text.");return{...a,action:r,text:e.slice(1).join(" ")}}(e,t)),a.json?aw(a,n):"read"===n.action?process.stdout.write(`${n.text}
83
- `):ab(a,n),!0}},...nt};async function nc(e){let t=nl[e.command];return!!t&&await t(e)}function nu(e,t={}){let r=np(t),a={...e};return r.defaultPlatform&&void 0===a.platform&&(a.platform=r.defaultPlatform),a}function np(e){var t,r,a,n;let o,s=e.env??process.env,i=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.`)}}(s.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??s.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:i,lockPolicy:(r=e.policyOverrides,a=s,n=l,(o=r?.sessionLock??r?.sessionLockConflicts??nd(a.AGENT_DEVICE_SESSION_LOCK)??nd(a.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||L(a.AGENT_DEVICE_SESSION_LOCKED)||n?"reject":void 0))}}function nd(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 nm=aR.map(e=>e.key),nf={sendToDaemon:tD};async function nh(e,t=nf){let r=q(),a=J(),n=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),o=e.includes("--json"),s=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 ea({session:s,requestId:r,command:e[0],debug:n},async()=>{var s,l,c,u,p,d,m,h,g,y,w,b,v;let I,k,A,D,S,$,L;try{let t,r,a,n,o,b,v,k;s={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,a=[],n=[],o=!0;for(let s=0;s<e.length;s+=1){let i=e[s];if(o&&"--"===i){o=!1;continue}if(!o){r?a.push(i):r=e8(i);continue}let l=i.startsWith("--"),c=i.startsWith("-")&&i.length>1;if(!l&&!c){r?a.push(i):r=e8(i);continue}let[u,p]=l?e2(i):[i,void 0],d=eT.get(u);if(!d){if(function(e,t,r){var a;if(a=r,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let n=eC(e);return!n||!!n.allowsExtraPositionals||0!==n.positionalArgs.length&&(t.length<n.positionalArgs.length||n.positionalArgs.some(e=>e.includes("?")))}(r,a,i)){r?a.push(i):r=i;continue}throw new eg("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,r,a){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===a||e5(a)||!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("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let n=r??a;if(void 0===n||void 0===r&&e5(n))throw new eg("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:n,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(n))throw new eg("INVALID_ARGS",`Invalid ${e3(t)}: ${n}`);return{value:n,consumeNext:void 0===r}}let o=Number(n);if(!Number.isFinite(o)||"number"==typeof e.min&&o<e.min||"number"==typeof e.max&&o>e.max)throw new eg("INVALID_ARGS",`Invalid ${e3(t)}: ${n}`);return{value:Math.floor(o),consumeNext:void 0===r}}(d,u,p,e[s+1]);m.consumeNext&&(s+=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;n.push({key:d.key,token:u})}return{command:r,positionals:a,flags:t,warnings:[],providedFlags:n}}(e),r=s?.env??process.env,a=s?.cwd??process.cwd(),u=t.command,n=("connect"===u||"metro"===u)&&(l={remoteConfig:t.flags.remoteConfig,cwd:a,env:r}).remoteConfig?{...function(e){let t={};for(let r of nm){let a=e[r];void 0!==a&&(t[r]=a)}return t}(aO({configPath:l.remoteConfig,cwd:l.cwd,env:l.env}).profile),remoteConfig:l.remoteConfig}:{},v=eL((o=(c={command:t.command,cwd:a,cliFlags:t.flags,env:r}).env??process.env,b=eL({},function(e){let t={};for(let r of e)eL(t,function(e,t){let r,a;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{a=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(!a||"object"!=typeof a||Array.isArray(a))throw new eg("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[a,n]of Object.entries(e)){let e=eQ.get(a);if(!e)throw new eg("INVALID_ARGS",`Unknown config key "${a}" in ${t}.`);if(!e.config.enabled)throw new eg("INVALID_ARGS",`Unsupported config key "${a}" in ${t}.`);r[a]=ez(e1(e),n,t,a)}return r}(a,`config file ${e}`)}(r.path,r.required));return t}((p=c.cwd,d=c.cliFlags.config,m=o,(k=d??m.AGENT_DEVICE_CONFIG)?[{path:(h=k,g=p,y=m,Y(h,{cwd:g,env:y})),required:!0}]:[{path:(w=m,i.join(O("~",{env:w}),".agent-device","config.json")),required:!1},{path:i.resolve(p,"agent-device.json"),required:!1}]))),eL(b,function(e,t){var r,a,n;let o={};for(let s of eZ.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=s.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(o[s.key]=(r=t.value,a=`environment variable ${t.name}`,n=t.name,ez(e1(s),r,a,n)))}return o}(o,c.command))),n),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),a=[...e.warnings],n=eL({json:!1,help:!1,version:!1},t?.defaultFlags??{});eL(n,e.flags);let o=eC(e.command),s=e.providedFlags.filter(t=>!e0(t.key,e.command));if(s.length>0){var i,l;let t=s.map(e=>e.token),o=(i=e.command,l=t,i?1===l.length?`Flag ${l[0]} is not supported for command ${i}.`:`Flags ${l.join(", ")} are not supported for command ${i}.`: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",o);for(let e of(a.push(`${o} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),s))delete n[e.key]}for(let t of Object.keys(n))void 0!==n[t]&&(e0(t,e.command)||delete n[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),o?.defaults)for(let[e,t]of Object.entries(o.defaults))void 0===n[e]&&(n[e]=t);if("batch"===e.command&&1!=+!!n.steps+ +!!n.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:n,warnings:a})}(t,{strictFlags:s?.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=ef(t,{diagnosticId:W().diagnosticId,logPath:eo({force:!0})??void 0});o?e4({success:!1,error:e}):e6(e,{showDetails:n}),process.exit(1);return}for(let e of I.warnings)process.stderr.write(`Warning: ${e}
84
- `);I.flags.version&&(process.stdout.write(`${a}
85
- `),process.exit(0));let _="help"===I.command,E=I.flags.help;if(_||E){_&&I.positionals.length>1&&(e6(new eg("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=_?I.positionals[0]:I.command;e||(process.stdout.write(`${ej}
86
- `),process.exit(0));let t=function(e){var t,r;let a=eC(e);if(!a)return null;let n=(t=e,(r=a).usageOverride?r.usageOverride:[t,...r.positionalArgs.map(eF),...r.allowedFlags.flatMap(e=>(eO.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),o=eV(new Set(a.allowedFlags)),s=eV(eM),i=[];return o.length>0&&i.push(eB("Command flags:",o)),i.push(eB("Global flags:",s)),`agent-device ${n}
82
+ `),0}(e,r,a,o);return 0!==s&&process.exit(s),!0}}function nh(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function ng(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=M(e);return t?{selector:t.selectorExpression}:{x:Number(e[0]),y:Number(e[1])}}function ny(e,t){if("start"===e||"stop"===e)return e;throw new eg("INVALID_ARGS",`${t} requires start|stop`)}function nw(e,t){if(void 0===e||""===e)throw new eg("INVALID_ARGS",t);return e}function nb(e){return void 0===e?void 0:Number(e)}let nv={...{session:az,[rE]:aW,[r$]:aQ,"ensure-simulator":aY,metro:aZ,install:a0,reinstall:a1,"install-from-source":a2,connect:a6,disconnect:a7,connection:a9,open:a8,close:a4,[rZ]:na,[rX]:no,[rM]:ns},...{[r5]:async({positionals:e,flags:t,client:r})=>(aJ(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 a={...aH(t),depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw};if("sleep"===r.kind)return{...a,durationMs:r.durationMs};if("text"===r.kind){if(!r.text)throw new eg("INVALID_ARGS","wait requires text.");return{...a,text:r.text,...ni(r.timeoutMs)}}return"ref"===r.kind?{...a,ref:r.rawRef,...ni(r.timeoutMs)}:{...a,selector:r.selectorExpression,...ni(r.timeoutMs)}}(e,t))),!0),[rA]:async({positionals:e,flags:t,client:r})=>(aJ(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]),a=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{...aH(t),...r?{action:r}:{},...void 0!==a?{timeoutMs:a}:{}}}(e,t))),!0),[rS]:async({flags:e,client:t})=>{let r=await t.command.appState(aH(e));return aK(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},[rx]:async({flags:e,client:t})=>(aJ(e,await t.command.back({...aH(e),mode:e.backMode})),!0),[rO]:async({flags:e,client:t})=>(aJ(e,await t.command.home(aH(e))),!0),[rz]:async({positionals:e,flags:t,client:r})=>(aJ(t,await r.command.rotate(function(e,t){if(e.length>1)throw new eg("INVALID_ARGS","rotate accepts exactly one orientation argument.");return{...aH(t),orientation:v(e[0])}}(e,t))),!0),[rD]:async({flags:e,client:t})=>(aJ(e,await t.command.appSwitcher(aH(e))),!0),[rU]:async({positionals:e,flags:t,client:r})=>(aJ(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{...aH(t),...r?{action:r}:{}}}(e,t))),!0),[r_]:async({positionals:e,flags:t,client:r})=>{var a,n;return a=t,n=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 a=aH(t);if("read"===r){if(1!==e.length)throw new eg("INVALID_ARGS","clipboard read does not accept additional arguments.");return{...a,action:r}}if(e.length<2)throw new eg("INVALID_ARGS","clipboard write requires text.");return{...a,action:r,text:e.slice(1).join(" ")}}(e,t)),a.json?aK(a,n):"read"===n.action?process.stdout.write(`${n.text}
83
+ `):aJ(a,n),!0}},...nm};async function nI(e){let t=nv[e.command];return!!t&&await t(e)}function nk(e,t={}){let r=nA(t),a={...e};return r.defaultPlatform&&void 0===a.platform&&(a.platform=r.defaultPlatform),a}function nA(e){var t,r,a,n;let o,s=e.env??process.env,i=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.`)}}(s.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??s.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:i,lockPolicy:(r=e.policyOverrides,a=s,n=l,(o=r?.sessionLock??r?.sessionLockConflicts??nS(a.AGENT_DEVICE_SESSION_LOCK)??nS(a.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||P(a.AGENT_DEVICE_SESSION_LOCKED)||n?"reject":void 0))}}function nS(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 nD=ab.map(e=>e.key),n$={sendToDaemon:tS},nx=new Set(["launchUrl","metroBearerToken","metroKind","metroListenHost","metroNoInstallDeps","metroNoReuseExisting","metroPreparePort","metroProbeTimeoutMs","metroProjectRoot","metroProxyBaseUrl","metroPublicBaseUrl","metroRuntimeFile","metroStartupTimeoutMs","metroStatusHost"]),nN=new Set(["connect","connection","close","devices","disconnect","ensure-simulator","metro","session"]);async function nP(e,t=n$){let r=q(),a=K(),n=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),o=e.includes("--json"),s=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 ea({session:s,requestId:r,command:e[0],debug:n},async()=>{var s,l,c,u,d,p,m,h,g,y,w,b,v,I,k,A;let S,D,$,x,N,P,_;try{let t,r,a,n,o,b,v,I;s={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,a=[],n=[],o=!0;for(let s=0;s<e.length;s+=1){let i=e[s];if(o&&"--"===i){o=!1;continue}if(!o){r?a.push(i):r=e8(i);continue}let l=i.startsWith("--"),c=i.startsWith("-")&&i.length>1;if(!l&&!c){r?a.push(i):r=e8(i);continue}let[u,d]=l?e2(i):[i,void 0],p=eT.get(u);if(!p){if(function(e,t,r){var a;if(a=r,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let n=eO(e);return!n||!!n.allowsExtraPositionals||0!==n.positionalArgs.length&&(t.length<n.positionalArgs.length||n.positionalArgs.some(e=>e.includes("?")))}(r,a,i)){r?a.push(i):r=i;continue}throw new eg("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,r,a){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===a||e5(a)||!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("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let n=r??a;if(void 0===n||void 0===r&&e5(n))throw new eg("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:n,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(n))throw new eg("INVALID_ARGS",`Invalid ${e3(t)}: ${n}`);return{value:n,consumeNext:void 0===r}}let o=Number(n);if(!Number.isFinite(o)||"number"==typeof e.min&&o<e.min||"number"==typeof e.max&&o>e.max)throw new eg("INVALID_ARGS",`Invalid ${e3(t)}: ${n}`);return{value:Math.floor(o),consumeNext:void 0===r}}(p,u,d,e[s+1]);m.consumeNext&&(s+=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;n.push({key:p.key,token:u})}return{command:r,positionals:a,flags:t,warnings:[],providedFlags:n}}(e),r=s?.env??process.env,a=s?.cwd??process.cwd(),u=t.command,n=null!==u&&(l={remoteConfig:t.flags.remoteConfig,cwd:a,env:r}).remoteConfig?{...function(e){let t={};for(let r of nD){let a=e[r];void 0!==a&&(t[r]=a)}return t}(ak({configPath:l.remoteConfig,cwd:l.cwd,env:l.env}).profile),remoteConfig:l.remoteConfig}:{},v=eP((o=(c={command:t.command,cwd:a,cliFlags:t.flags,env:r}).env??process.env,b=eP({},function(e){let t={};for(let r of e)eP(t,function(e,t){let r,a;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{a=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(!a||"object"!=typeof a||Array.isArray(a))throw new eg("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[a,n]of Object.entries(e)){let e=eQ.get(a);if(!e)throw new eg("INVALID_ARGS",`Unknown config key "${a}" in ${t}.`);if(!e.config.enabled)throw new eg("INVALID_ARGS",`Unsupported config key "${a}" in ${t}.`);r[a]=ez(e1(e),n,t,a)}return r}(a,`config file ${e}`)}(r.path,r.required));return t}((d=c.cwd,p=c.cliFlags.config,m=o,(I=p??m.AGENT_DEVICE_CONFIG)?[{path:(h=I,g=d,y=m,Y(h,{cwd:g,env:y})),required:!0}]:[{path:(w=m,i.join(C("~",{env:w}),".agent-device","config.json")),required:!1},{path:i.resolve(d,"agent-device.json"),required:!1}]))),eP(b,function(e,t){var r,a,n;let o={};for(let s of eZ.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=s.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(o[s.key]=(r=t.value,a=`environment variable ${t.name}`,n=t.name,ez(e1(s),r,a,n)))}return o}(o,c.command))),n),S={...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),a=[...e.warnings],n=eP({json:!1,help:!1,version:!1},t?.defaultFlags??{});eP(n,e.flags);let o=eO(e.command),s=e.providedFlags.filter(t=>!e0(t.key,e.command));if(s.length>0){var i,l;let t=s.map(e=>e.token),o=(i=e.command,l=t,i?1===l.length?`Flag ${l[0]} is not supported for command ${i}.`:`Flags ${l.join(", ")} are not supported for command ${i}.`: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",o);for(let e of(a.push(`${o} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),s))delete n[e.key]}for(let t of Object.keys(n))void 0!==n[t]&&(e0(t,e.command)||delete n[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),o?.defaults)for(let[e,t]of Object.entries(o.defaults))void 0===n[e]&&(n[e]=t);if("batch"===e.command&&1!=+!!n.steps+ +!!n.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:n,warnings:a})}(t,{strictFlags:s?.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=ef(t,{diagnosticId:W().diagnosticId,logPath:eo({force:!0})??void 0});o?e4({success:!1,error:e}):e6(e,{showDetails:n}),process.exit(1);return}for(let e of S.warnings)process.stderr.write(`Warning: ${e}
84
+ `);S.flags.version&&(process.stdout.write(`${a}
85
+ `),process.exit(0));let E="help"===S.command,M=S.flags.help;if(E||M){E&&S.positionals.length>1&&(e6(new eg("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=E?S.positionals[0]:S.command;e||(process.stdout.write(`${ej}
86
+ `),process.exit(0));let t=function(e){var t,r;let a=eO(e);if(!a)return null;let n=(t=e,(r=a).usageOverride?r.usageOverride:[t,...r.positionalArgs.map(eF),...r.allowedFlags.flatMap(e=>(eC.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),o=eB(new Set(a.allowedFlags)),s=eB(eM),i=[];return o.length>0&&i.push(eV("Command flags:",o)),i.push(eV("Global flags:",s)),`agent-device ${n}
87
87
 
88
88
  ${a.helpDescription}
89
89
 
@@ -92,8 +92,8 @@ Usage:
92
92
 
93
93
  ${i.join("\n\n")}
94
94
  `}(e8(e));t&&(process.stdout.write(t),process.exit(0)),e6(new eg("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${ej}
95
- `),process.exit(1)}I.command||(process.stdout.write(`${ej}
96
- `),process.exit(1));let{command:M,positionals:R}=I,T=new Set(I.providedFlags.map(e=>e.key));try{if(I.flags.remoteConfig&&"connect"!==M&&"metro"!==M)throw new eg("INVALID_ARGS","--remote-config is only supported by connect and metro prepare. Run agent-device connect first, then use normal commands.");A=(k=np({policyOverrides:I.flags,configuredPlatform:I.flags.platform,configuredSession:I.flags.session})).lockPolicy?{...I.flags}:nu(I.flags,{policyOverrides:I.flags,configuredPlatform:I.flags.platform,configuredSession:I.flags.session}),D=en(A.stateDir),S=A.session??"default",b={command:M,explicitFlagKeys:T,stateDir:D.baseDir,session:S},L=($="connect"===b.command||"connection"===b.command||b.explicitFlagKeys.has("remoteConfig")?null:function(e){let t=e.validateRemoteConfigHash??!0,r=aC(e)??(e.allowActiveFallback?aB({stateDir:e.stateDir}):null);if(!r)return null;if(t&&aF(r.remoteConfigPath)!==r.remoteConfigHash)throw new eg("INVALID_ARGS","Active remote connection config changed. Run agent-device connect --force to refresh it.",{remoteConfig:r.remoteConfigPath});let a=function(e,t){try{return aO({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:{...a,remoteConfig:r.remoteConfigPath,daemonBaseUrl:r.daemon?.baseUrl??a.daemonBaseUrl,daemonTransport:r.daemon?.transport??a.daemonTransport,daemonServerMode:r.daemon?.serverMode??a.daemonServerMode,tenant:r.tenant,sessionIsolation:"tenant",runId:r.runId,leaseId:r.leaseId,leaseBackend:r.leaseBackend,session:r.session,platform:r.platform??a.platform,target:r.target??a.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 a={...e};for(let[e,n]of Object.entries(t))void 0!==n&&(r.has(e)||(a[e]=n));return a}(A,$.flags,T):A}catch(t){let e=ef(em(t),{diagnosticId:W().diagnosticId,logPath:eo({force:!0})??void 0});I.flags.json?e4({success:!1,error:e}):e6(e,{showDetails:I.flags.verbose}),process.exit(1);return}eN({command:M,currentVersion:a,stateDir:D.baseDir,flags:L});let C=L.daemonBaseUrl,U=!L.verbose||L.json||C?null:function(e){try{let t=0,r=!1,a=setInterval(()=>{if(!r&&f.existsSync(e))try{let r=f.statSync(e);if(r.size<t&&(t=0),r.size<=t)return;let a=f.openSync(e,"r");try{let e=Buffer.alloc(r.size-t);f.readSync(a,e,0,e.length,t),t=r.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{f.closeSync(a)}}catch{}},200);return()=>{r=!0,clearInterval(a)}}catch{return null}}(D.logPath),F=function(e={},t={}){var r;let a,n=t.transport??tD,o=async(t,r=[],a={})=>{var o,s;let i=(o=e,s=a,{...o,...s}),l=await n({session:ad(i.session),command:t,positionals:r,flags:al({stateDir:i.stateDir,daemonBaseUrl:i.daemonBaseUrl,daemonAuthToken:i.daemonAuthToken,daemonTransport:i.daemonTransport,daemonServerMode:i.daemonServerMode,tenant:i.tenant,sessionIsolation:i.sessionIsolation,runId:i.runId,leaseId:i.leaseId,leaseBackend:i.leaseBackend,platform:i.platform,target:i.target,device:i.device,udid:i.udid,serial:i.serial,iosSimulatorDeviceSet:i.iosSimulatorDeviceSet,androidDeviceAllowlist:i.androidDeviceAllowlist,runtime:i.simulatorRuntimeId,boot:i.boot,reuseExisting:i.reuseExisting,surface:i.surface,activity:i.activity,relaunch:i.relaunch,shutdown:i.shutdown,saveScript:i.saveScript,noRecord:i.noRecord,backMode:i.backMode,metroHost:i.metroHost,metroPort:i.metroPort,bundleUrl:i.bundleUrl,launchUrl:i.launchUrl,snapshotInteractiveOnly:i.interactiveOnly,snapshotCompact:i.compact,snapshotDepth:i.depth,snapshotScope:i.scope,snapshotRaw:i.raw,screenshotFullscreen:i.screenshotFullscreen,overlayRefs:i.overlayRefs,appsFilter:i.appsFilter,out:i.out,count:i.count,fps:i.fps,quality:i.quality,hideTouches:i.hideTouches,intervalMs:i.intervalMs,delayMs:i.delayMs,holdMs:i.holdMs,jitterPx:i.jitterPx,pixels:i.pixels,doubleTap:i.doubleTap,clickButton:i.clickButton,pauseMs:i.pauseMs,pattern:i.pattern,headless:i.headless,restart:i.restart,replayUpdate:i.replayUpdate,failFast:i.failFast,timeoutMs:i.timeoutMs,retries:i.retries,artifactsDir:i.artifactsDir,reportJunit:i.reportJunit,findFirst:i.findFirst,findLast:i.findLast,networkInclude:i.networkInclude,batchOnError:i.batchOnError,batchMaxSteps:i.batchMaxSteps,batchSteps:i.batchSteps,verbose:i.debug}),runtime:i.runtime,meta:al({requestId:i.requestId,cwd:i.cwd,debug:i.debug,lockPolicy:i.lockPolicy,lockPlatform:i.lockPlatform,tenantId:i.tenant,runId:i.runId,leaseId:i.leaseId,leaseBackend:i.leaseBackend,leaseTtlMs:i.leaseTtlMs,sessionIsolation:i.sessionIsolation,installSource:i.installSource,retainMaterializedPaths:i.retainMaterializedPaths,materializedPathRetentionMs:i.materializedPathRetentionMs,materializationId:i.materializationId})});return l.ok||function(e){throw new eg(e.code,e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(l.error),l.data??{}},s=async(e={})=>{let t=await o("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(ap)},i=async(e,t=[],r={})=>await o(e,t,r),l=(t={})=>{var r,a;return ad((r=e,a=t,{...r,...a}).session)};return{command:(r=async e=>await o(e.command,e.positionals,e.options),a=async e=>await r(e),{wait:async e=>await a(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:r5,positionals:[String(e.durationMs)],options:e};let t=void 0!==e.timeoutMs?[String(e.timeoutMs)]:[];if(void 0!==e.text)return{command:r5,positionals:["text",e.text,...t],options:e};if(void 0!==e.ref)return{command:r5,positionals:[e.ref,...t],options:e};let r=e.selector;return function(e){if(!H(e))throw new eg("INVALID_ARGS",`Invalid wait selector: ${e}`)}(r),{command:r5,positionals:[r,...t],options:e}}(e)),alert:async(e={})=>{var t;return await a({command:rA,positionals:[(t=e).action??"get",...void 0!==t.timeoutMs?[String(t.timeoutMs)]:[]],options:t})},appState:async(e={})=>await a({command:rD,positionals:[],options:e}),back:async(e={})=>await a({command:rx,positionals:[],options:{...e,backMode:e.mode}}),home:async(e={})=>await a({command:rC,positionals:[],options:e}),rotate:async e=>await a({command:rz,positionals:[e.orientation],options:e}),appSwitcher:async(e={})=>await a({command:rS,positionals:[],options:e}),keyboard:async(e={})=>await a({command:rU,positionals:e.action?[e.action]:[],options:e}),clipboard:async e=>{var t;return await a("read"===(t=e).action?{command:r_,positionals:["read"],options:t}:{command:r_,positionals:["write",t.text],options:t})}}),devices:{list:async(e={})=>{let t=await o(rE,[],e);return(Array.isArray(t.devices)?t.devices:[]).map(au)},boot:async(e={})=>await i(rL,[],e)},sessions:{list:async(e={})=>await s(e),close:async(e={})=>{let t=l(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,a=await o("ensure-simulator",[],{...r,simulatorRuntimeId:t}),n=r4(a,"udid"),s=r4(a,"device");return{udid:n,device:s,runtime:r4(a,"runtime"),created:!0===a.created,booted:!0===a.booted,iosSimulatorDeviceSet:r7(a,"ios_simulator_device_set"),identifiers:{deviceId:n,deviceName:s,udid:n}}}},apps:{install:async e=>ac(await o("install",[e.app,e.appPath],e),l(e)),reinstall:async e=>ac(await o("reinstall",[e.app,e.appPath],e),l(e)),installFromSource:async e=>(function(e,t){let r=r6(e,"bundleId"),a=r6(e,"packageName"),n=r??a??r6(e,"appId"),o=r6(e,"launchTarget")??a??r??n;if(!o)throw new eg("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:r6(e,"appName"),appId:n,bundleId:r,packageName:a,launchTarget:o,installablePath:r6(e,"installablePath"),archivePath:r6(e,"archivePath"),materializationId:r6(e,"materializationId"),materializationExpiresAt:r6(e,"materializationExpiresAt"),identifiers:N({session:t,bundleId:r,packageName:a,appId:n})}})(await o("install_source",[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),l(e)),list:async(e={})=>{let t=await o(r$,[],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]:[],a=await o("open",r,e),n=function(e){let t=e.platform,r=r6(e,"id"),a=r6(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!a)return;let n=ae(e,"target"),o=x(t,r,a);return{platform:t,target:n,id:r,name:a,identifiers:o,ios:"ios"===t?{udid:r6(e,"device_udid")??r,simulatorSetPath:r7(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:r6(e,"serial")??r}:void 0}}(a),s=r6(a,"appBundleId");return{session:t,appName:r6(a,"appName"),appBundleId:s,appId:s,startup:function(e){if(ai(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:r6(e,"appTarget"),appBundleId:r6(e,"appBundleId")}}(a.startup),runtime:function(e){if(!ai(e))return;let t=e.platform,r=r6(e,"metroHost"),a="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:a,bundleUrl:r6(e,"bundleUrl"),launchUrl:r6(e,"launchUrl")}}(a.runtime),device:n,identifiers:{session:t,deviceId:n?.id,deviceName:n?.name,udid:n?.ios?.udid,serial:n?.android?.serial,appId:s,appBundleId:s}}},close:async(e={})=>{let t=l(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 i(rH,[e.app,"string"==typeof(t=e.payload)?t:JSON.stringify(t)],e)},triggerEvent:async e=>{var t;return await i(r2,[(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:r4(t,"materializationId"),identifiers:{}}}},leases:{allocate:async e=>ag(await o("lease_allocate",[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>ag(await o("lease_heartbeat",[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await o("lease_release",[],e)).released})},metro:{prepare:async t=>await rk({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),a=await o(rZ,[],e),n=r6(a,"appBundleId"),s="object"==typeof a.visibility&&null!==a.visibility?a.visibility:void 0;return{nodes:Array.isArray(t=a.nodes)?t:[],truncated:!0===a.truncated,appName:r6(a,"appName"),appBundleId:n,...s?{visibility:s}:{},warnings:Array.isArray(a.warnings)?a.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:r,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=l(e),r=await o(rX,e.path?[e.path]:[],{...e,screenshotFullscreen:e.fullscreen});return{path:r4(r,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!ai(e))continue;let t=r6(e,"ref"),a=at(e,"rect"),n=at(e,"overlayRect"),o=function(e,t){let r=e[t];if(!ai(r))return;let a="number"==typeof r.x?r.x:void 0,n="number"==typeof r.y?r.y:void 0;if(void 0!==a&&void 0!==n)return{x:a,y:n}}(e,"center");t&&a&&n&&o&&r.push({ref:t,label:r6(e,"label"),rect:a,overlayRect:n,center:o})}return r}(r),identifiers:{session:t}}},diff:async e=>await i(rM,[e.kind],{...e,interactiveOnly:e.interactiveOnly,compact:e.compact,depth:e.depth,scope:e.scope,raw:e.raw})},interactions:{click:async e=>await i(rP,am(e),{...e,clickButton:e.button}),press:async e=>await i(rq,am(e),e),longPress:async e=>await i(rj,[String(e.x),String(e.y),...ah(e.durationMs)],e),swipe:async e=>await i(rQ,[String(e.from.x),String(e.from.y),String(e.to.x),String(e.to.y),...ah(e.durationMs)],e),focus:async e=>await i(rO,[String(e.x),String(e.y)],e),type:async e=>await i(r3,[e.text],e),fill:async e=>await i(rR,[...am(e),e.text],e),scroll:async e=>await i(rW,[e.direction,...ah(e.amount)],e),pinch:async e=>await i(rG,[String(e.scale),...ah(e.x),...ah(e.y)],e),get:async e=>{var t;return await i("get",[e.format,...void 0!==(t=e).ref?[t.ref,...af(t.label)]:[t.selector]],e)},is:async e=>await i("is",[e.predicate,e.selector,..."text"===e.predicate?[e.value]:[]],e),find:async e=>await i(rT,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",...ah(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 i(rK,[e.path],{...e,replayUpdate:e.update}),test:async e=>await i(r0,e.paths,{...e,replayUpdate:e.update})},batch:{run:async e=>await i(rN,[],{...e,batchSteps:e.steps,batchOnError:e.onError,batchMaxSteps:e.maxSteps})},observability:{perf:async(e={})=>await i(rB,[],e),logs:async(e={})=>{var t;return await i(rF,[(t=e).action??"path",...af(t.message)],e)},network:async(e={})=>{var t;return await i(rV,[...(t=e).action?[t.action]:[],...ah(t.limit)],{...e,networkInclude:e.include})}},recording:{record:async e=>await i(rJ,[e.action,...af(e.path)],e),trace:async e=>await i(r1,[e.action,...af(e.path)],e)},settings:{update:async e=>await i(rY,[e.setting,e.state,..."permission"in e?[e.permission]:[],..."mode"in e&&e.mode?[e.mode]:[]],e)}}}({session:L.session??S,requestId:r,stateDir:L.stateDir,daemonBaseUrl:L.daemonBaseUrl,daemonAuthToken:L.daemonAuthToken,daemonTransport:L.daemonTransport,daemonServerMode:L.daemonServerMode,tenant:L.tenant,sessionIsolation:L.sessionIsolation,runId:L.runId,leaseId:L.leaseId,leaseBackend:L.leaseBackend,runtime:$?.runtime,lockPolicy:k.lockPolicy,lockPlatform:k.defaultPlatform,cwd:process.cwd(),debug:!!L.verbose},{transport:t.sendToDaemon});try{if("batch"===M){if(R.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 P(t)})(A).map((e,t)=>({...e,flags:k.lockPolicy&&void 0===A.platform?{...e.flags??{}}:nu(e.flags??{},{policyOverrides:L,configuredPlatform:L.platform,configuredSession:L.session,inheritedPlatform:L.platform})}));if(await nc({command:M,positionals:R,flags:{...L,batchSteps:e},client:F}))return}else if("runtime"===M)throw new eg("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 nc({command:M,positionals:R,flags:L,client:F}))return;throw new eg("INVALID_ARGS",`Unknown command: ${M}`)}catch(r){let e=em(r),t=ef(e,{diagnosticId:W().diagnosticId,logPath:eo({force:!0})??void 0});if("close"===M&&"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))){L.json&&e4({success:!0,data:{closed:"session",source:"no-daemon"}});return}if(L.json)e4({success:!1,error:t});else if(e6(t,{showDetails:L.verbose}),L.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(`
95
+ `),process.exit(1)}S.command||(process.stdout.write(`${ej}
96
+ `),process.exit(1));let{command:R,positionals:T}=S,O=new Set(S.providedFlags.map(e=>e.key));try{$=(D=nA({policyOverrides:S.flags,configuredPlatform:S.flags.platform,configuredSession:S.flags.session})).lockPolicy?{...S.flags}:nk(S.flags,{policyOverrides:S.flags,configuredPlatform:S.flags.platform,configuredSession:S.flags.session}),x=en($.stateDir),N=$.session??"default",b={command:R,explicitFlagKeys:O,stateDir:x.baseDir,session:N,remoteConfig:$.remoteConfig},_=(P="connect"===b.command||"connection"===b.command?null:function(e){let t=e.validateRemoteConfigHash??!0,r=e.remoteConfig?aI({configPath:e.remoteConfig,cwd:e.cwd,env:e.env}):void 0,a=aA(e)??(e.allowActiveFallback?aL({stateDir:e.stateDir}):null);if(!a||r&&a.remoteConfigPath!==r)return null;if(t&&ax(a.remoteConfigPath)!==a.remoteConfigHash)throw new eg("INVALID_ARGS","Active remote connection config changed. Run agent-device connect --force to refresh it.",{remoteConfig:a.remoteConfigPath});let n=function(e,t){try{return ak({configPath:e.remoteConfigPath,cwd:t.cwd,env:t.env}).profile}catch(e){if(!1===t.validateRemoteConfigHash)return{};throw e}}(a,e);return{runtime:a.runtime,flags:{...n,remoteConfig:a.remoteConfigPath,daemonBaseUrl:a.daemon?.baseUrl??n.daemonBaseUrl,daemonTransport:a.daemon?.transport??n.daemonTransport,daemonServerMode:a.daemon?.serverMode??n.daemonServerMode,tenant:a.tenant,sessionIsolation:"tenant",runId:a.runId,leaseId:a.leaseId,leaseBackend:a.leaseBackend,session:a.session,platform:a.platform??n.platform,target:a.target??n.target}}}({stateDir:b.stateDir,session:b.session,remoteConfig:b.remoteConfig,cwd:process.cwd(),env:process.env,allowActiveFallback:!b.explicitFlagKeys.has("session")&&(!b.remoteConfig||"disconnect"===b.command),validateRemoteConfigHash:"disconnect"!==b.command}))?function(e,t,r){let a={...e};for(let[e,n]of Object.entries(t))void 0!==n&&(r.has(e)||(a[e]=n));return a}($,P.flags,O):$}catch(t){let e=ef(em(t),{diagnosticId:W().diagnosticId,logPath:eo({force:!0})??void 0});S.flags.json?e4({success:!1,error:e}):e6(e,{showDetails:S.flags.verbose}),process.exit(1);return}let U=null;try{let e;eN({command:R,currentVersion:a,stateDir:x.baseDir,flags:_});let n=P?.runtime,o=(e,t)=>({session:e.session??N,requestId:r,stateDir:e.stateDir,daemonBaseUrl:e.daemonBaseUrl,daemonAuthToken:e.daemonAuthToken,daemonTransport:e.daemonTransport,daemonServerMode:e.daemonServerMode,tenant:e.tenant,sessionIsolation:e.sessionIsolation,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,runtime:t,lockPolicy:D.lockPolicy,lockPlatform:D.defaultPlatform,cwd:process.cwd(),debug:!!e.verbose});if("batch"===R){if(T.length>0)throw new eg("INVALID_ARGS","batch does not accept positional arguments.");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 L(t)}($)}if(_.remoteConfig&&(v=R,!nN.has(v))){let r=am(o(_,n),{transport:t.sendToDaemon}),a=await aC({command:R,flags:_,client:r,runtime:n,batchSteps:e,forceRuntimePrepare:function(e){for(let t of nx)if(e.has(t))return!0;return!1}(O)});_=a.flags,n=a.runtime}I={command:R,flags:_,runtime:n,explicitFlagKeys:O,hadConnectionDefaults:!!P},!("open"===I.command&&!I.runtime&&!I.flags.bundleUrl&&!I.flags.metroHost&&!I.flags.metroPort&&!I.flags.remoteConfig&&!I.hadConnectionDefaults&&((k=I.explicitFlagKeys).has("daemonBaseUrl")||k.has("daemonTransport")||k.has("tenant")||k.has("sessionIsolation")||k.has("runId")||k.has("leaseId")||k.has("leaseBackend")))||process.stderr.write("Warning: open is using explicit remote daemon or tenant flags without saved Metro runtime hints. React Native apps may launch without bundle/runtime hints; prefer connect --remote-config <path> first or pass --remote-config <path> on this command.\n");let s=_.daemonBaseUrl;U=!_.verbose||_.json||s?null:function(e){try{let t=0,r=!1,a=setInterval(()=>{if(!r&&f.existsSync(e))try{let r=f.statSync(e);if(r.size<t&&(t=0),r.size<=t)return;let a=f.openSync(e,"r");try{let e=Buffer.alloc(r.size-t);f.readSync(a,e,0,e.length,t),t=r.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{f.closeSync(a)}}catch{}},200);return()=>{r=!0,clearInterval(a)}}catch{return null}}(x.logPath);let i=am(o(_,n),{transport:t.sendToDaemon});if("batch"===R){if(!e)throw new eg("INVALID_ARGS","batch requires --steps or --steps-file.");let t=e.map((e,t)=>({...e,flags:D.lockPolicy&&void 0===$.platform?{...e.flags??{}}:nk(e.flags??{},{policyOverrides:_,configuredPlatform:_.platform,configuredSession:_.session,inheritedPlatform:_.platform})}));if(await nI({command:R,positionals:T,flags:{..._,batchSteps:t},client:i}))return}else if("runtime"===R)throw new eg("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 nI({command:R,positionals:T,flags:_,client:i}))return;throw new eg("INVALID_ARGS",`Unknown command: ${R}`)}catch(r){let e=em(r),t=ef(e,{diagnosticId:W().diagnosticId,logPath:eo({force:!0})??void 0});if("close"===R&&"COMMAND_FAILED"===(A=e).code&&(A.details?.kind==="daemon_startup_failed"||A.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof A.details?.infoPath||"string"==typeof A.details?.lockPath))){_.json&&e4({success:!0,data:{closed:"session",source:"no-daemon"}});return}if(_.json)e4({success:!1,error:t});else if(e6(t,{showDetails:_.verbose}),_.verbose)try{let e=x.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(`
97
97
  [daemon log]
98
98
  ${r}
99
- `)}}catch{}U&&U(),process.exit(1)}finally{U&&U()}})}u(process.argv[1]??"").href===import.meta.url&&nh(process.argv.slice(2)).catch(e=>{e6(ef(em(e)),{showDetails:!0}),process.exit(1)}),nh(process.argv.slice(2));
99
+ `)}}catch{}U&&U(),process.exit(1)}finally{U&&U()}})}u(process.argv[1]??"").href===import.meta.url&&nP(process.argv.slice(2)).catch(e=>{e6(ef(em(e)),{showDetails:!0}),process.exit(1)}),nP(process.argv.slice(2));