agent-device 0.11.2 → 0.11.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -6
- package/dist/src/916.js +1 -1
- package/dist/src/bin.js +72 -68
- package/dist/src/daemon.js +38 -36
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +1 -1
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +4 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/Assets.xcassets/AppIcon.appiconset/Contents.json +14 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/Assets.xcassets/AppIcon.appiconset/logo-tinted.jpg +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/Assets.xcassets/Contents.json +6 -0
- package/package.json +1 -1
- package/skills/agent-device/SKILL.md +6 -0
- package/skills/agent-device/references/bootstrap-install.md +2 -0
- package/skills/agent-device/references/debugging.md +15 -0
- package/skills/agent-device/references/exploration.md +62 -0
package/dist/src/bin.js
CHANGED
|
@@ -1,103 +1,107 @@
|
|
|
1
|
-
let e,t,r,s,o,a,i;import n from"node:path";import{styleText as l}from"node:util";import{pathToFileURL as u}from"node:url";import p from"node:net";import d from"node:http";import c from"node:https";import m,{promises as f}from"node:fs";import{spawn as h}from"node:child_process";import g from"node:os";import{PNG as y}from"pngjs";import{SESSION_SURFACES as w,parseBatchStepsJson as b,serializeSessionListEntry as v,serializeSnapshotResult as D,isAgentDeviceDaemonProcess as I,runCmdDetached as k,buildDeviceIdentifiers as A,buildAppIdentifiers as S,resolveDaemonTransportPreference as $,serializeOpenResult as L,asAppError as E,expandUserHomePath as P,serializeDeployResult as x,AppError as N,readCommandMessage as _,serializeEnsureSimulatorResult as T,serializeDevice as M,buildSnapshotDisplayLines as R,createRequestId as O,normalizeError as F,readVersion as C,findProjectRoot as U,getDiagnosticsMeta as j,runCmdSync as V,withDiagnosticTimer as G,resolveUserPath as B,serializeCloseResult as q,emitDiagnostic as z,SETTINGS_USAGE_OVERRIDE as H,resolveDaemonPaths as J,withDiagnosticsScope as W,flushDiagnosticsToSessionFile as K,resolveDaemonServerMode as X,serializeInstallFromSourceResult as Y,decodePng as Z,stopProcessForTakeover as Q,formatSnapshotLine as ee}from"./916.js";function et(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&(e[r]=s);return e}let er=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],es=["snapshotDepth","snapshotScope","snapshotRaw"],eo=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","apple"],usageLabel:"--platform ios|macos|android|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:w,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"maxScrolls",names:["--max-scrolls"],type:"int",min:1,max:200,usageLabel:"--max-scrolls <n>",usageDescription:"scrollintoview: cap the number of scroll gestures before failing"},{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:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{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:"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"},{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)"}],ea=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),ei={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{helpDescription:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...er]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind"],allowedFlags:[...er,"baseline","threshold","out"]},"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 (startup timing)",summary:"Show startup 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:[]},"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:[...es]},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",...es]},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:[...es]},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",...es]},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:[...es,"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"]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",helpDescription:"Scroll until text appears or a snapshot ref is brought into view",summary:"Scroll until text or ref is visible",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["maxScrolls"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] | network log [limit] [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:[]},find:{usageOverride:"find <locator|text> <action> [value]",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"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...es]},settings:{usageOverride:H,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}},en=new Map,el=new Map;for(let e of eo){for(let t of e.names)en.set(t,e);let t=el.get(e.key);t?t.push(e):el.set(e.key,[e])}function eu(e){if(e)return ei[e]}function ep(){return Object.keys(ei)}function ed(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let ec=(e=`agent-device <command> [args] [--json]
|
|
1
|
+
let e,t,r,s,a,o,i,n;import l from"node:path";import{styleText as u}from"node:util";import{fileURLToPath as p,pathToFileURL as d}from"node:url";import c from"node:net";import m from"node:http";import f from"node:https";import h,{promises as g}from"node:fs";import{spawn as y}from"node:child_process";import w from"node:os";import{PNG as b}from"pngjs";import{SESSION_SURFACES as v,parseBatchStepsJson as D,serializeSessionListEntry as k,serializeSnapshotResult as I,isAgentDeviceDaemonProcess as A,runCmdDetached as S,buildDeviceIdentifiers as $,buildAppIdentifiers as L,resolveDaemonTransportPreference as E,serializeOpenResult as P,asAppError as N,expandUserHomePath as x,serializeDeployResult as _,AppError as T,readCommandMessage as M,serializeEnsureSimulatorResult as O,serializeDevice as R,buildSnapshotDisplayLines as F,createRequestId as C,normalizeError as U,readVersion as j,findProjectRoot as V,getDiagnosticsMeta as G,runCmdSync as B,withDiagnosticTimer as q,resolveUserPath as J,serializeCloseResult as z,emitDiagnostic as H,SETTINGS_USAGE_OVERRIDE as W,resolveDaemonPaths as K,withDiagnosticsScope as Y,flushDiagnosticsToSessionFile as X,resolveDaemonServerMode as Z,serializeInstallFromSourceResult as Q,decodePng as ee,stopProcessForTakeover as et,formatSnapshotLine as er}from"./916.js";function es(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&(e[r]=s);return e}let ea=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],eo=["snapshotDepth","snapshotScope","snapshotRaw"],ei=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","apple"],usageLabel:"--platform ios|macos|android|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:v,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"maxScrolls",names:["--max-scrolls"],type:"int",min:1,max:200,usageLabel:"--max-scrolls <n>",usageDescription:"scrollintoview: cap the number of scroll gestures before failing"},{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:"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"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],en=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),el={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{usageOverride:"snapshot [--diff] [-i] [-c] [-d <depth>] [-s <scope>] [--raw]",helpDescription:"Capture accessibility tree or diff against the previous session baseline",positionalArgs:[],allowedFlags:["snapshotDiff",...ea]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind"],allowedFlags:[...ea,"baseline","threshold","out"]},"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 (startup timing)",summary:"Show startup 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:[]},"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:[...eo]},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",...eo]},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:[...eo]},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",...eo]},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:[...eo,"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"]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",helpDescription:"Scroll until text appears or a snapshot ref is brought into view",summary:"Scroll until text or ref is visible",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["maxScrolls"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},find:{usageOverride:"find <locator|text> <action> [value]",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"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...eo]},settings:{usageOverride:W,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}},eu=new Map,ep=new Map;for(let e of ei){for(let t of e.names)eu.set(t,e);let t=ep.get(e.key);t?t.push(e):ep.set(e.key,[e])}function ed(e){if(e)return el[e]}function ec(){return Object.keys(el)}function em(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let ef=(e=`agent-device <command> [args] [--json]
|
|
2
2
|
|
|
3
3
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
-
`,t=
|
|
4
|
+
`,t=ey("Commands:",ec().map(e=>{let t=el[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let r=t.positionalArgs.map(r=>{var s,a,o;let i,n,l,u;return s=e,a=t,n=(i=(o=r).endsWith("?"))?o.slice(0,-1):o,u=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(n))||void 0!==a.usageOverride&&a.usageOverride.startsWith(`${s} ${n}`),i?l?`[${n}]`:u?n:`[${n}]`:u?n:`<${n}>`});return[e,...r].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),r=eg("Flags:",eh(en)),s=[ey("Agent Skills:",[{label:"agent-device",description:"Canonical mobile automation flows"},{label:"dogfood",description:"Exploratory QA and bug hunts"}]),"See `skills/<name>/SKILL.md` in the installed package."].join("\n\n"),a=ew("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=ey("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"}]),i=ew("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}
|
|
8
8
|
|
|
9
9
|
${s}
|
|
10
10
|
|
|
11
|
-
${o}
|
|
12
|
-
|
|
13
11
|
${a}
|
|
14
12
|
|
|
13
|
+
${o}
|
|
14
|
+
|
|
15
15
|
${i}
|
|
16
|
-
`);function
|
|
17
|
-
(none)`;let r=Math.max(...t.map(e=>e.label.length))+2,s=[e];for(let e of t)s.push(` ${e.label.padEnd(r)}${e.description}`);return s.join("\n")}function
|
|
18
|
-
(none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let
|
|
19
|
-
`)}function
|
|
16
|
+
`);function eh(e){return ei.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function eg(e,t){return ey(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function ey(e,t){if(0===t.length)return`${e}
|
|
17
|
+
(none)`;let r=Math.max(...t.map(e=>e.label.length))+2,s=[e];for(let e of t)s.push(` ${e.label.padEnd(r)}${e.description}`);return s.join("\n")}function ew(e,t){return 0===t.length?`${e}
|
|
18
|
+
(none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let eb=new Set(["config","remoteConfig","help","version","batchSteps"]),ev={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eD=new Set(["1","true","yes","on"]),ek=new Set(["0","false","no","off"]),eI=function(){let e=new Map;for(let t of ei){let r=e.get(t.key);r?r.push(t):e.set(t.key,[t])}let t=new Map;for(let e of en)t.set(e,new Set(["*"]));for(let e of ec()){let r=ed(e);if(r)for(let s of r.allowedFlags){let r=t.get(s);r&&r.has("*")||(r?r.add(e):t.set(s,new Set([e])))}}return[...e.entries()].map(([e,r])=>{var s;return{key:e,flagDefinitions:r,config:{enabled:!eb.has(e),key:e},env:{names:[(s=e,`AGENT_DEVICE_${s.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`),...ev[e]??[]]},supportsCommand(r){let s=t.get(e);return!!s&&(!!s.has("*")||!!r&&s.has(r))}}}).sort((e,t)=>e.key.localeCompare(t.key))}(),eA=new Map(eI.map(e=>[e.key,e]));function eS(e){return eA.get(e)}function e$(e,t){return eS(e)?.supportsCommand(t)??!1}function eL(e,t,r,s){let a=function(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}(e);if(a.multiple)return(Array.isArray(t)?t:[t]).map(t=>eL({...e,flagDefinitions:e.flagDefinitions.map(e=>({...e,multiple:!1}))},t,r,s));if("boolean"===a.type){var o=t,i=r,n=s;if("boolean"==typeof o)return o;if("string"==typeof o){let e=eE(o);if(void 0!==e)return e}throw new T("INVALID_ARGS",`Invalid value for "${n}" in ${i}. Expected boolean.`)}if("booleanOrString"===a.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==eE(t))return eE(t);if("string"==typeof t&&t.trim().length>0)return t;throw new T("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected boolean or non-empty string.`)}if("string"===a.type){if("string"==typeof t&&t.trim().length>0)return t;throw new T("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected non-empty string.`)}if("enum"===a.type){if(void 0!==a.setValue){var l=a,u=t,p=r,d=s;let e=l.setValue;if(u===e)return e;if("string"==typeof u){let t=u.trim();if(""===t||"true"===t||"1"===t)return e;if("false"===t||"0"===t)return}if(!0===u)return e;if(!1!==u)throw new T("INVALID_ARGS",`Invalid value for "${d}" in ${p}. Expected boolean or ${String(e)}.`);return}if("string"!=typeof t||!a.enumValues?.includes(t))throw new T("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected one of: ${a.enumValues?.join(", ")}.`);return t}let c="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(c)||!Number.isInteger(c))throw new T("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected integer.`);if("number"==typeof a.min&&c<a.min)throw new T("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Must be >= ${a.min}.`);if("number"==typeof a.max&&c>a.max)throw new T("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Must be <= ${a.max}.`);return c}function eE(e){let t=e.trim().toLowerCase();return!!eD.has(t)||!ek.has(t)&&void 0}function eP(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function eN(e){return e.replace(/^-+/,"")}function ex(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?eP(e):[e,void 0];return void 0!==eu.get(t)}function e_(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function eT(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
19
|
+
`)}function eM(e,t={}){let r=e instanceof T?U(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
|
|
25
|
-
`:"";if(0
|
|
26
|
-
|
|
27
|
-
${e.
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
`}function eM(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function eR(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}async function eO(e){let{localPath:t,baseUrl:r,token:s}=e,o=m.statSync(t).isDirectory(),a=n.basename(t),i=new URL("upload",r.endsWith("/")?r:`${r}/`),l="https:"===i.protocol?c:d,u={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":a,"transfer-encoding":"chunked"};return s&&(u.authorization=`Bearer ${s}`,u["x-agent-device-token"]=s),new Promise((e,r)=>{let s=l.request({protocol:i.protocol,host:i.hostname,port:i.port,method:"POST",path:i.pathname+i.search,headers:u},t=>{let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{clearTimeout(a);try{let t=JSON.parse(s);if(!t.ok||!t.uploadId)return void r(new N("COMMAND_FAILED",`Upload failed: ${s}`));e(t.uploadId)}catch{r(new N("COMMAND_FAILED",`Invalid upload response: ${s}`))}})}),a=setTimeout(()=>{s.destroy(),r(new N("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(s.on("error",e=>{clearTimeout(a),r(new N("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=h("tar",["cf","-","-C",n.dirname(t),n.basename(t)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(s),e.on("error",e=>{s.destroy(),r(new N("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(s.destroy(),r(new N("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=m.createReadStream(t);e.pipe(s),e.on("error",e=>{s.destroy(),r(new N("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let eF=ti(),eC=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}(),eU=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}(),ej=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function eV(e){let t=e.meta?.requestId??O(),r=!!(e.meta?.debug||e.flags?.verbose),s=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,r=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new N("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new N("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),s=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,o=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,a=$(o);if(r&&"socket"===a)throw new N("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:r});let i=X(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===o?"dual":void 0));return{paths:J(t),transportPreference:a,serverMode:i,remoteBaseUrl:r,remoteAuthToken:s}}(e),o=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return ti(t)}(e.command),a=await G("daemon_startup",async()=>await eH(s),{requestId:t,session:e.session}),i=await eG(e,a),n={...e,positionals:i.positionals,flags:i.flags,token:a.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,...i.uploadedArtifactId?{uploadedArtifactId:i.uploadedArtifactId}:{},...i.clientArtifactPaths?{clientArtifactPaths:i.clientArtifactPaths}:{},...i.installSource?{installSource:i.installSource}:{}}};return z({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await G("daemon_request",async()=>await e8(a,n,s.transportPreference,o),{requestId:t,command:e.command})}async function eG(e,t){let r,s=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,a=e.meta?.installSource,i={};if(tr(t)){let l=function(e,t){if("screenshot"===e.command){let r=eq(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:ez("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:ez("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=eq(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:ez("recording",n.extname(t)||".mp4")}}return null}(e,s);l&&(void 0!==l.positionalPath&&(s[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((o??={}).out=l.flagPath),i[l.field]=l.localPath);let u=await eB(e,t);u&&(a=u.installSource,r=u.uploadedArtifactId??r)}if(!tr(t)||"install"!==e.command&&"reinstall"!==e.command||s.length<2)return{positionals:s,flags:o,installSource:a,uploadedArtifactId:r,...Object.keys(i).length>0?{clientArtifactPaths:i}:{}};let l=s[1];if(l.startsWith("remote:"))return s[1]=l.slice(7),{positionals:s,flags:o,...Object.keys(i).length>0?{clientArtifactPaths:i}:{}};let u=n.isAbsolute(l)?l:n.resolve(e.meta?.cwd??process.cwd(),l);return m.existsSync(u)?{positionals:s,flags:o,installSource:a,uploadedArtifactId:r=await eO({localPath:u,baseUrl:t.baseUrl,token:t.token}),...Object.keys(i).length>0?{clientArtifactPaths:i}:{}}:{positionals:s,flags:o,...Object.keys(i).length>0?{clientArtifactPaths:i}:{}}}async function eB(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let s=r.path.trim();if(!s)return{installSource:r};if(s.startsWith("remote:"))return{installSource:{...r,path:s.slice(7)}};let o=n.isAbsolute(s)?s:n.resolve(e.meta?.cwd??process.cwd(),s);if(!m.existsSync(o))return{installSource:{...r,path:o}};let a=await eO({localPath:o,baseUrl:t.baseUrl,token:t.token});return{installSource:{...r,path:o},uploadedArtifactId:a}}function eq(e,t,r,s=0){let o=e.positionals?.[s]??e.flags?.out,a=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,i=o&&o.trim().length>0?o:a;return n.isAbsolute(i)?i:n.resolve(e.meta?.cwd??process.cwd(),i)}function ez(e,t){let r=t.startsWith(".")?t:`.${t}`;return n.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function eH(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await e2(t,"http"))return t;throw new N("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=eY(e.paths.infoPath),s=C(),o=function(e,t=U()){try{let r=m.statSync(e),s=n.relative(t,e)||e;return`${s}:${r.size}:${Math.trunc(r.mtimeMs)}`}catch{return"unknown"}}((t=e5()).useSrc?t.srcPath:t.distPath,t.root),a=!!r&&await e2(r,e.transportPreference);if(r&&r.version===s&&r.codeSignature===o&&a)return r;r&&(r.version!==s||r.codeSignature!==o||!a)&&(await eX(r),e1(e.paths.infoPath)),function(e){let t=eQ(e);if(!t.hasLock||t.hasInfo)return;let r=eZ(e.lockPath);if(!r)return e1(e.lockPath);I(r.pid,r.processStartTime)||e1(e.lockPath)}(e.paths);let i=0;for(let t=1;t<=eU;t+=1){await e3(e);let r=await eJ(eC,e);if(r)return r;if(await eK(e.paths)){i+=1;continue}let s=eQ(e.paths);if(!(t<eU))break;if(!s.hasInfo&&!s.hasLock){await eW(150);continue}}let l=eQ(e.paths);throw new N("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:eC,startupAttempts:eU,lockRecoveryCount:i,metadataState:l,hint:function(e,t=J(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.`}(l,e.paths)})}async function eJ(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=eY(t.paths.infoPath);if(e&&await e2(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function eW(e){await new Promise(t=>setTimeout(t,e))}async function eK(e){let t=eQ(e);if(!t.hasLock||t.hasInfo)return!1;let r=eZ(e.lockPath);return r&&I(r.pid,r.processStartTime)&&await Q(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),e1(e.lockPath),!0}async function eX(e){await Q(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eY(e){let t=e0(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 s=Number.isInteger(t.port)&&Number(t.port)>0,o=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!s&&!o)return null;let a=t.transport,i="string"==typeof t.version?t.version:void 0,n="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,u=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:s?Number(t.port):void 0,httpPort:o?Number(t.httpPort):void 0,transport:"socket"===a||"http"===a||"dual"===a?a:void 0,pid:u?Number(t.pid):0,version:i,codeSignature:n,processStartTime:l}}function eZ(e){let t=e0(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}function eQ(e){return{hasInfo:m.existsSync(e.infoPath),hasLock:m.existsSync(e.lockPath)}}function e0(e){if(!m.existsSync(e))return null;try{return JSON.parse(m.readFileSync(e,"utf8"))}catch{return null}}function e1(e){try{m.existsSync(e)&&m.unlinkSync(e)}catch{}}async function e2(e,t){var r;return"http"===e4(e,t)?await function(e){let t=e.baseUrl?ts(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),s="https:"===r.protocol?c:d,o=e.baseUrl?3e3:500;return new Promise(e=>{let t=s.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:o},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 e3(e){let t=e5(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],s={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};k(process.execPath,r,{env:s})}function e5(){let e=U(),t=n.join(e,"dist","src","daemon.js"),r=n.join(e,"src","daemon.ts"),s=m.existsSync(t),o=m.existsSync(r);if(!s&&!o)throw new N("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!s&&o}}async function e8(e,t,r,s){return"http"===e4(e,r)?await tt(e,t,s):await te(e,t,s)}function e4(e,t){if(e.baseUrl){if("socket"===t)throw new N("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,s=t;if(e7(r,s))return s;throw new N("COMMAND_FAILED","http"===s?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let o=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>e7(e,t));if(o)return o;throw new N("COMMAND_FAILED","Daemon metadata has no reachable transport")}function e7(e,t){return"http"===t?!!e.httpPort:!!e.port}function e6(e,t,r,s,o,a){let i=o?{terminated:0}:function(){let e=0;try{for(let t of ej){let r=V("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)}}}(),n=o?{forcedKill:!1}:function(e,t){let r=!1;try{I(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{Q(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{e1(t.infoPath),e1(t.lockPath)}return{forcedKill:r}}(e,t);return z({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:a,requestId:r,command:s,timedOutRunnerPidsTerminated:i.terminated,timedOutRunnerCleanupError:i.error,daemonPidReset:o?void 0:e.pid,daemonPidForceKilled:o?void 0:n.forcedKill,daemonBaseUrl:e.baseUrl}}),new N("COMMAND_FAILED","Daemon request timed out",{timeoutMs:a,requestId:r,hint:o?"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 e9(e,t,r){return z({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new N("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 te(e,t,r){let s=e.port;if(!s)throw new N("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((o,a)=>{let i=p.createConnection({host:"127.0.0.1",port:s},()=>{i.write(`${JSON.stringify(t)}
|
|
33
|
-
`)}),n=J(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{i.destroy(),a(e6(e,n,t.meta?.requestId,t.command,!1,r))},r):void 0,u="";i.setEncoding("utf8"),i.on("data",e=>{let r=(u+=e).indexOf("\n");if(-1===r)return;let s=u.slice(0,r).trim();if(s)try{let e=JSON.parse(s);i.end(),l&&clearTimeout(l),o(e)}catch(e){l&&clearTimeout(l),a(new N("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}}),i.on("error",e=>{l&&clearTimeout(l),a(e9(e,t.meta?.requestId,!1))})})}async function tt(e,t,r){let s=e.baseUrl?new URL(ts(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!s)throw new N("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let o=JSON.stringify({jsonrpc:"2.0",id:t.meta?.requestId??O(),method:"agent_device.command",params:t}),a={"content-type":"application/json","content-length":Buffer.byteLength(o)};return e.baseUrl&&e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token),await new Promise((i,n)=>{let l=J(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),u=("https:"===s.protocol?c:d).request({protocol:s.protocol,host:s.hostname,port:s.port,method:"POST",path:s.pathname+s.search,headers:a},r=>{let s="";r.setEncoding("utf8"),r.on("data",e=>{s+=e}),r.on("end",()=>{m&&clearTimeout(m);try{let r=JSON.parse(s);if(r.error){let e=r.error.data??{};n(new N(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 N("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void to(e,t,r.result).then(i).catch(n);i(r.result)}catch(e){m&&clearTimeout(m),n(new N("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}})}),p=tr(e),m="number"==typeof r?setTimeout(()=>{u.destroy(),n(e6(e,l,t.meta?.requestId,t.command,p,r))},r):void 0;u.on("error",e=>{m&&clearTimeout(m),n(e9(e,t.meta?.requestId,p))}),u.write(o),u.end()})}function tr(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function ts(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function to(e,t,r){let s=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===s.length||!e.baseUrl)return r;let o=r.data?{...r.data}:{},a=[];for(let r of s){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){a.push(r);continue}let s=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return n.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await ta({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:s,requestId:t.meta?.requestId}),o[r.field]=s,a.push({...r,localPath:s})}return o.artifacts=a,{ok:!0,data:o}}async function ta(e){var t,r;let s,o=new URL((t=e.baseUrl,r=e.artifactId,s=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,s).toString())),a="https:"===o.protocol?c:d;await m.promises.mkdir(n.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let s=!1,i=e.timeoutMs??eF,n=o=>{if(!s){if(s=!0,clearTimeout(u),o)return void m.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(o));t()}},l=a.request({protocol:o.protocol,host:o.hostname,port:o.port,method:"GET",path:o.pathname+o.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",()=>{n(new N("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=m.createWriteStream(e.destinationPath);r.on("error",e=>{n(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{n(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{n(new N("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>n())}),t.pipe(r)}),u=setTimeout(()=>{l.destroy(new N("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:i}))},i);l.on("error",t=>{t instanceof N?n(t):n(new N("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:i},t instanceof Error?t:void 0))}),l.end()})}function ti(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}function tn(e){return e.replace(/\/+$/,"")}function tl(e){return"string"==typeof e&&e.trim()?tn(e.trim()):""}function tu(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function tp(e,t,r){return B(e,{env:t,cwd:r})}function td(e){try{return m.accessSync(e,m.constants.F_OK),!0}catch{return!1}}function tc(e,t,r){if(null==e||""===e)return t;let s=Number.parseInt(String(e),10);return Number.isInteger(s)?Math.max(s,r):t}function tm(e,t){let r;return{platform:t,bundleUrl:((r=new URL(`${tn(e)}/index.bundle`)).searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString())}}function tf(e,t){return{platform:t,metroHost:tu(e?.metro_host),metroPort:e?.metro_port,bundleUrl:tu(e?.metro_bundle_url),launchUrl:tu(e?.launch_url)}}async function th(e){await new Promise(t=>setTimeout(t,e))}async function tg(e,t,r={}){try{let s=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:s.ok,status:s.status,body:await s.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function ty(e,t){try{let r=await tg(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function tw(e){var t,r,s;let o;try{o=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Error(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`);throw t}let a=await o.text(),i=a?JSON.parse(a):{};if(!o.ok)throw Error(`/api/metro/bridge failed (${o.status}): ${JSON.stringify(i)}`);return{enabled:(s=i.data??i).enabled,baseUrl:s.base_url,statusUrl:s.status_url,bundleUrl:s.bundle_url,iosRuntime:tf(s.ios_runtime,"ios"),androidRuntime:tf(s.android_runtime,"android"),upstream:{bundleUrl:s.upstream.bundle_url,host:s.upstream.host,port:s.upstream.port,statusUrl:s.upstream.status_url},probe:{reachable:s.probe.reachable,statusCode:s.probe.status_code,latencyMs:s.probe.latency_ms,detail:s.probe.detail}}}async function tb(e,t,r){let s=Date.now()+t;for(;Date.now()<s;){let t=Math.min(r,Math.max(s-Date.now(),1));if(await ty(e,t))return!0;let o=Math.min(500,Math.max(s-Date.now(),0));o>0&&await th(o)}return!1}async function tv(e={}){let t=e.env??process.env,r=process.cwd(),s=tp(e.projectRoot??r,t,r),o=function(e,t){if("auto"!==t)return t;let r=function(e){let t=n.join(e,"package.json");if(!td(t))throw new N("INVALID_ARGS",`package.json not found at ${t}`);return JSON.parse(m.readFileSync(t,"utf8"))}(e);return"string"==typeof({...r.dependencies??{},...r.devDependencies??{}}).expo?"expo":"react-native"}(s,e.kind??"auto"),a=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 N("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(e.metroPort??8081),i=tu(e.listenHost)??"0.0.0.0",l=tu(e.statusHost)??"127.0.0.1",u=tl(e.publicBaseUrl),p=tc(e.startupTimeoutMs,18e4,3e4),d=tc(e.probeTimeoutMs,1e4,1e3),c=e.reuseExisting??!0,f=e.installDependenciesIfNeeded??!0,h=e.runtimeFilePath?tp(e.runtimeFilePath,t,r):null,g=tp(e.logPath??n.join(s,".agent-device","metro.log"),t,r);if(!u)throw new N("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:y,proxyBaseUrl:w,proxyBearerToken:b}=function(e,t){if(e&&!t)throw new N("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 N("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(tl(e.proxyBaseUrl),tu(e.proxyBearerToken)??""),v=f?function(e,t){if(function(e){try{return m.statSync(e).isDirectory()}catch{return!1}}(n.join(e,"node_modules")))return{installed:!1};let r=td(n.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:td(n.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return V(r.command,r.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:r.command}}(s,t):{installed:!1},D=`http://${l}:${a}/status`,I=!1,A=!1,S=0;if(c&&await ty(D,d))A=!0;else if(I=!0,S=function(e,t,r,s,o,a){let i="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",s,"--port",String(r)]};m.mkdirSync(n.dirname(o),{recursive:!0});let l=m.openSync(o,"a"),u=0;try{u=k(i.command,i.installArgs,{cwd:e,env:a,stdio:["ignore",l,l]})}finally{m.closeSync(l)}if(!Number.isInteger(u)||u<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:u}}(s,o,a,i,g,t).pid,!await tb(D,p,d))throw Error(`Metro did not become ready at ${D} within ${p}ms. Check ${g}.`);let $=tm(u,"ios"),L=tm(u,"android"),E=null,P=null;if(y)try{E=await tw({baseUrl:w,bearerToken:b,runtime:{metro_bundle_url:$.bundleUrl},timeoutMs:d})}catch(e){P=e instanceof Error?e.message:String(e)}if(y&&(!E||!1===E.probe.reachable)){var x,_;let e;throw Error((x=P,_=E,e=[`Metro bridge is required for this run but could not be configured via ${w}/api/metro/bridge.`],x&&e.push(`bridgeError=${x}`),_?.probe.reachable===!1&&e.push(`bridgeProbe=${_.probe.detail||`unreachable (status ${_.probe.statusCode||0})`}`),e.join(" ")))}let T=E?.iosRuntime??$,M=E?.androidRuntime??L,R={projectRoot:s,kind:o,dependenciesInstalled:v.installed,packageManager:v.packageManager??null,started:I,reused:A,pid:S,logPath:g,statusUrl:D,runtimeFilePath:h,iosRuntime:T,androidRuntime:M,bridge:E};return h&&(m.mkdirSync(n.dirname(h),{recursive:!0}),m.writeFileSync(h,JSON.stringify(R,null,2))),R}function tD(e,t,r,s){let o=r(e[t]);if(void 0===o)throw new N("COMMAND_FAILED",s,{response:e});return o}function tI(e,t){return tD(e,t,tE,`Daemon response is missing "${t}".`)}function tk(e,t){return tE(e[t])}function tA(e,t){var r;let s;return r=tE,null===(s=e[t])?null:r(s)}function tS(e,t){return tD(e,t,tx,`Daemon response has invalid "${t}".`)}function t$(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function tL(e,t){let r=e[t];if(!tT(r))return;let s="number"==typeof r.x?r.x:void 0,o="number"==typeof r.y?r.y:void 0,a="number"==typeof r.width?r.width:void 0,i="number"==typeof r.height?r.height:void 0;if(void 0!==s&&void 0!==o&&void 0!==a&&void 0!==i)return{x:s,y:o,width:a,height:i}}function tE(e){return"string"==typeof e&&e.length>0?e:void 0}function tP(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function tx(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function tN(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function t_(e){if(!tT(e))throw new N("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function tT(e){return"object"==typeof e&&null!==e}function tM(e){let t={};for(let[r,s]of Object.entries(e))void 0!==s&&(t[r]=s);return t}function tR(e,t){let r=tk(e,"bundleId"),s=tk(e,"package");return{app:tI(e,"app"),appPath:tI(e,"appPath"),platform:tS(e,"platform"),appId:r??s,bundleId:r,package:s,identifiers:S({session:t,bundleId:r,packageName:s})}}function tO(e){let t=t_(e),r=tS(t,"platform"),s=tI(t,"id"),o=tI(t,"name");return{platform:r,target:t$(t,"target"),kind:tD(t,"kind",tN,'Daemon response has invalid "kind".'),id:s,name:o,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:A(r,s,o),ios:"ios"===r?{udid:s}:void 0,android:"android"===r?{serial:s}:void 0}}function tF(e){let t=t_(e),r=tS(t,"platform"),s=tI(t,"id"),o=tI(t,"name"),a=t$(t,"target"),i=tI(t,"device"),n={session:o,...A(r,s,i)};return{name:o,createdAt:tD(t,"createdAt",tP,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:a,id:s,name:i,identifiers:n,ios:"ios"===r?{udid:s,simulatorSetPath:tA(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:s}:void 0},identifiers:n}}function tC(e,t){return t??e??"default"}function tU(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function tj(e,t,r){var s;if(e.json)return void eN({success:!0,data:t});let o=r?.();o&&(s=o,process.stdout.write(s.endsWith("\n")?s:`${s}
|
|
34
|
-
`))}function tV(e,t){tj(e,t,()=>_(t))}function tG(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",s="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${s}`}async function tB(e,t,r,s){let o=t[0],a=t[1];if(!o||!a)throw new N("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let i={app:o,appPath:a,...tU(r)};return"install"===e?await s.apps.install(i):await s.apps.reinstall(i)}async function tq(e,t,r){let s=e[0]?.trim();if(!s)throw new N("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new N("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await r.apps.installFromSource({...tU(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:s,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 N("INVALID_ARGS",`Invalid --header value "${r}". Expected "name:value".`);let s=r.slice(0,e).trim(),o=r.slice(e+1).trim();if(!s)throw new N("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[s]=o}return t}(t.header)}})}async function tz(e,t){if(!e.remoteConfig)return;let r=e.platform;if("ios"!==r&&"android"!==r)throw new N("INVALID_ARGS",'open --remote-config requires platform "ios" or "android" in the remote config file or CLI flags.');if(!e.metroPublicBaseUrl)throw new N("INVALID_ARGS",'open --remote-config requires "metroPublicBaseUrl" in the remote config file.');let s=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return"ios"===r?s.iosRuntime:s.androidRuntime}let tH=255*Math.sqrt(3);async function tJ(e,t,r={}){await tW(e,"Baseline image not found"),await tW(t,"Current screenshot not found");let s=r.outputPath,[o,a]=await Promise.all([f.readFile(e),f.readFile(t)]),i=Z(o,"baseline screenshot"),l=Z(a,"current screenshot"),u=r.threshold??.1;if(i.width!==l.width||i.height!==l.height){let e=i.width*i.height;return await tK(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:i.width,height:i.height},actual:{width:l.width,height:l.height}}}}let p=i.width*i.height,d=u*tH,c=new y({width:i.width,height:i.height}),m=0;for(let e=0;e<i.data.length;e+=4){if(Math.sqrt((i.data[e]-l.data[e])**2+(i.data[e+1]-l.data[e+1])**2+(i.data[e+2]-l.data[e+2])**2)>d){m+=1,c.data[e]=255,c.data[e+1]=0,c.data[e+2]=0,c.data[e+3]=255;continue}let t=Math.round(.3*Math.round((i.data[e]+i.data[e+1]+i.data[e+2])/3));c.data[e]=t,c.data[e+1]=t,c.data[e+2]=t,c.data[e+3]=255}m>0&&s?(await f.mkdir(n.dirname(s),{recursive:!0}),await f.writeFile(s,y.sync.write(c))):await tK(r.outputPath);let h=p>0?Math.round(m/p*1e4)/100:0;return{...m>0&&s?{diffPath:s}:{},totalPixels:p,differentPixels:m,mismatchPercentage:h,match:0===m}}async function tW(e,t){try{await f.access(e)}catch{throw new N("INVALID_ARGS",`${t}: ${e}`)}}async function tK(e){if(e)try{await f.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}let tX={session:async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new N("INVALID_ARGS","session only supports list");let s={sessions:(await r.sessions.list()).map(v)};return tj(t,s,()=>JSON.stringify(s,null,2)),!0},devices:async({flags:e,client:t})=>{let r=await t.devices.list(tU(e));return tj(e,{devices:r.map(M)},()=>r.map(tG).join("\n")),!0},"ensure-simulator":async({flags:e,client:t})=>{if(!e.device)throw new N("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 tj(e,T(r),()=>{let e=r.created?"Created":"Reused",t=r.booted?" (booted)":"";return r.runtime?`${e}: ${r.device} ${r.udid}${t}
|
|
35
|
-
|
|
36
|
-
`})
|
|
37
|
-
`}(
|
|
24
|
+
`)}function eO(e,t={}){var r,s,a;let o,i=e.nodes,n=Array.isArray(i)?i:[],l=!!e.truncated,u="string"==typeof e.appName?e.appName:void 0,p="string"==typeof e.appBundleId?e.appBundleId:void 0,d=[];u&&d.push(`Page: ${u}`),p&&d.push(`App: ${p}`);let c=`Snapshot: ${n.length} nodes${l?" (truncated)":""}`,m=d.length>0?`${d.join("\n")}
|
|
25
|
+
`:"",f=(r=e,s=n,a=t,o=eC(r),!a.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let s of e){var r;let e=(s.type??"").toLowerCase(),a=(r=s,r.label?.trim()||r.value?.trim()||r.identifier?.trim()||"").trim().toLowerCase();if(!a)continue;let o=`${e}|${a}`;t.set(o,(t.get(o)??0)+1)}let s=0;for(let e of t.values())e>1&&(s+=e);return s>=8}(s)&&o.push("Warning: possible repeated nav subtree detected."),o),h=f.length>0?`${f.join("\n")}
|
|
26
|
+
`:"";if(0===n.length)return`${m}${c}
|
|
27
|
+
${h}`;if(t.raw){let e=n.map(e=>JSON.stringify(e));return`${m}${c}
|
|
28
|
+
${h}${e.join("\n")}
|
|
29
|
+
`}if(t.flatten){let e=n.map(e=>er(e,0,!1,void 0,{summarizeTextSurfaces:!0}));return`${m}${c}
|
|
30
|
+
${h}${e.join("\n")}
|
|
31
|
+
`}let g=F(n,{summarizeTextSurfaces:!0}).map(e=>e.text);return`${m}${c}
|
|
32
|
+
${h}${g.join("\n")}
|
|
33
|
+
`}function eR(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function eF(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function eC(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}async function eU(e){let{localPath:t,baseUrl:r,token:s}=e,a=h.statSync(t).isDirectory(),o=l.basename(t),i=new URL("upload",r.endsWith("/")?r:`${r}/`),n="https:"===i.protocol?f:m,u={"x-artifact-type":a?"app-bundle":"file","x-artifact-filename":o,"transfer-encoding":"chunked"};return s&&(u.authorization=`Bearer ${s}`,u["x-agent-device-token"]=s),new Promise((e,r)=>{let s=n.request({protocol:i.protocol,host:i.hostname,port:i.port,method:"POST",path:i.pathname+i.search,headers:u},t=>{let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{clearTimeout(o);try{let t=JSON.parse(s);if(!t.ok||!t.uploadId)return void r(new T("COMMAND_FAILED",`Upload failed: ${s}`));e(t.uploadId)}catch{r(new T("COMMAND_FAILED",`Invalid upload response: ${s}`))}})}),o=setTimeout(()=>{s.destroy(),r(new T("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(s.on("error",e=>{clearTimeout(o),r(new T("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),a){let e=y("tar",["cf","-","-C",l.dirname(t),l.basename(t)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(s),e.on("error",e=>{s.destroy(),r(new T("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(s.destroy(),r(new T("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=h.createReadStream(t);e.pipe(s),e.on("error",e=>{s.destroy(),r(new T("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let ej=tu(),eV=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}(),eG=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}(),eB=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function eq(e){let t=e.meta?.requestId??C(),r=!!(e.meta?.debug||e.flags?.verbose),s=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,r=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new T("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new T("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),s=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,a=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=E(a);if(r&&"socket"===o)throw new T("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:r});let i=Z(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0));return{paths:K(t),transportPreference:o,serverMode:i,remoteBaseUrl:r,remoteAuthToken:s}}(e),a=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return tu(t)}(e.command),o=await q("daemon_startup",async()=>await eK(s),{requestId:t,session:e.session}),i=await eJ(e,o),n={...e,positionals:i.positionals,flags:i.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,...i.uploadedArtifactId?{uploadedArtifactId:i.uploadedArtifactId}:{},...i.clientArtifactPaths?{clientArtifactPaths:i.clientArtifactPaths}:{},...i.installSource?{installSource:i.installSource}:{}}};return H({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await q("daemon_request",async()=>await e6(o,n,s.transportPreference,a),{requestId:t,command:e.command})}async function eJ(e,t){let r,s=[...e.positionals??[]],a=e.flags?{...e.flags}:void 0,o=e.meta?.installSource,i={};if(to(t)){let n=function(e,t){if("screenshot"===e.command){let r=eH(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:eW("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:eW("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=eH(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eW("recording",l.extname(t)||".mp4")}}return null}(e,s);n&&(void 0!==n.positionalPath&&(s[n.positionalIndex]=n.positionalPath),void 0!==n.flagPath&&((a??={}).out=n.flagPath),i[n.field]=n.localPath);let u=await ez(e,t);u&&(o=u.installSource,r=u.uploadedArtifactId??r)}if(!to(t)||"install"!==e.command&&"reinstall"!==e.command||s.length<2)return{positionals:s,flags:a,installSource:o,uploadedArtifactId:r,...Object.keys(i).length>0?{clientArtifactPaths:i}:{}};let n=s[1];if(n.startsWith("remote:"))return s[1]=n.slice(7),{positionals:s,flags:a,...Object.keys(i).length>0?{clientArtifactPaths:i}:{}};let u=l.isAbsolute(n)?n:l.resolve(e.meta?.cwd??process.cwd(),n);return h.existsSync(u)?{positionals:s,flags:a,installSource:o,uploadedArtifactId:r=await eU({localPath:u,baseUrl:t.baseUrl,token:t.token}),...Object.keys(i).length>0?{clientArtifactPaths:i}:{}}:{positionals:s,flags:a,...Object.keys(i).length>0?{clientArtifactPaths:i}:{}}}async function ez(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let s=r.path.trim();if(!s)return{installSource:r};if(s.startsWith("remote:"))return{installSource:{...r,path:s.slice(7)}};let a=l.isAbsolute(s)?s:l.resolve(e.meta?.cwd??process.cwd(),s);if(!h.existsSync(a))return{installSource:{...r,path:a}};let o=await eU({localPath:a,baseUrl:t.baseUrl,token:t.token});return{installSource:{...r,path:a},uploadedArtifactId:o}}function eH(e,t,r,s=0){let a=e.positionals?.[s]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,i=a&&a.trim().length>0?a:o;return l.isAbsolute(i)?i:l.resolve(e.meta?.cwd??process.cwd(),i)}function eW(e,t){let r=t.startsWith(".")?t:`.${t}`;return l.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function eK(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await e8(t,"http"))return t;throw new T("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=e0(e.paths.infoPath),s=j(),a=function(e,t=V()){try{let r=h.statSync(e),s=l.relative(t,e)||e;return`${s}:${r.size}:${Math.trunc(r.mtimeMs)}`}catch{return"unknown"}}((t=e7()).useSrc?t.srcPath:t.distPath,t.root),o=!!r&&await e8(r,e.transportPreference);if(r&&r.version===s&&r.codeSignature===a&&o)return r;r&&(r.version!==s||r.codeSignature!==a||!o)&&(await eQ(r),e5(e.paths.infoPath)),function(e){let t=e2(e);if(!t.hasLock||t.hasInfo)return;let r=e1(e.lockPath);if(!r)return e5(e.lockPath);A(r.pid,r.processStartTime)||e5(e.lockPath)}(e.paths);let i=0;for(let t=1;t<=eG;t+=1){await e4(e);let r=await eY(eV,e);if(r)return r;if(await eZ(e.paths)){i+=1;continue}let s=e2(e.paths);if(!(t<eG))break;if(!s.hasInfo&&!s.hasLock){await eX(150);continue}}let n=e2(e.paths);throw new T("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:eV,startupAttempts:eG,lockRecoveryCount:i,metadataState:n,hint:function(e,t=K(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.`}(n,e.paths)})}async function eY(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=e0(t.paths.infoPath);if(e&&await e8(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function eX(e){await new Promise(t=>setTimeout(t,e))}async function eZ(e){let t=e2(e);if(!t.hasLock||t.hasInfo)return!1;let r=e1(e.lockPath);return r&&A(r.pid,r.processStartTime)&&await et(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),e5(e.lockPath),!0}async function eQ(e){await et(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function e0(e){let t=e3(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 s=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!s&&!a)return null;let o=t.transport,i="string"==typeof t.version?t.version:void 0,n="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,u=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:s?Number(t.port):void 0,httpPort:a?Number(t.httpPort):void 0,transport:"socket"===o||"http"===o||"dual"===o?o:void 0,pid:u?Number(t.pid):0,version:i,codeSignature:n,processStartTime:l}}function e1(e){let t=e3(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}function e2(e){return{hasInfo:h.existsSync(e.infoPath),hasLock:h.existsSync(e.lockPath)}}function e3(e){if(!h.existsSync(e))return null;try{return JSON.parse(h.readFileSync(e,"utf8"))}catch{return null}}function e5(e){try{h.existsSync(e)&&h.unlinkSync(e)}catch{}}async function e8(e,t){var r;return"http"===e9(e,t)?await function(e){let t=e.baseUrl?ti(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),s="https:"===r.protocol?f:m,a=e.baseUrl?3e3:500;return new Promise(e=>{let t=s.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:a},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=c.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function e4(e){let t=e7(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],s={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};S(process.execPath,r,{env:s})}function e7(){let e=V(),t=l.join(e,"dist","src","daemon.js"),r=l.join(e,"src","daemon.ts"),s=h.existsSync(t),a=h.existsSync(r);if(!s&&!a)throw new T("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?a:!s&&a}}async function e6(e,t,r,s){return"http"===e9(e,r)?await ta(e,t,s):await ts(e,t,s)}function e9(e,t){if(e.baseUrl){if("socket"===t)throw new T("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,s=t;if(te(r,s))return s;throw new T("COMMAND_FAILED","http"===s?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let a=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>te(e,t));if(a)return a;throw new T("COMMAND_FAILED","Daemon metadata has no reachable transport")}function te(e,t){return"http"===t?!!e.httpPort:!!e.port}function tt(e,t,r,s,a,o){let i=a?{terminated:0}:function(){let e=0;try{for(let t of eB){let r=B("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)}}}(),n=a?{forcedKill:!1}:function(e,t){let r=!1;try{A(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{et(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{e5(t.infoPath),e5(t.lockPath)}return{forcedKill:r}}(e,t);return H({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:o,requestId:r,command:s,timedOutRunnerPidsTerminated:i.terminated,timedOutRunnerCleanupError:i.error,daemonPidReset:a?void 0:e.pid,daemonPidForceKilled:a?void 0:n.forcedKill,daemonBaseUrl:e.baseUrl}}),new T("COMMAND_FAILED","Daemon request timed out",{timeoutMs:o,requestId:r,hint:a?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."})}function tr(e,t,r){return H({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new T("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 ts(e,t,r){let s=e.port;if(!s)throw new T("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,o)=>{let i=c.createConnection({host:"127.0.0.1",port:s},()=>{i.write(`${JSON.stringify(t)}
|
|
34
|
+
`)}),n=K(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{i.destroy(),o(tt(e,n,t.meta?.requestId,t.command,!1,r))},r):void 0,u="";i.setEncoding("utf8"),i.on("data",e=>{let r=(u+=e).indexOf("\n");if(-1===r)return;let s=u.slice(0,r).trim();if(s)try{let e=JSON.parse(s);i.end(),l&&clearTimeout(l),a(e)}catch(e){l&&clearTimeout(l),o(new T("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}}),i.on("error",e=>{l&&clearTimeout(l),o(tr(e,t.meta?.requestId,!1))})})}async function ta(e,t,r){let s=e.baseUrl?new URL(ti(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!s)throw new T("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let a=JSON.stringify({jsonrpc:"2.0",id:t.meta?.requestId??C(),method:"agent_device.command",params:t}),o={"content-type":"application/json","content-length":Buffer.byteLength(a)};return e.baseUrl&&e.token&&(o.authorization=`Bearer ${e.token}`,o["x-agent-device-token"]=e.token),await new Promise((i,n)=>{let l=K(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),u=("https:"===s.protocol?f:m).request({protocol:s.protocol,host:s.hostname,port:s.port,method:"POST",path:s.pathname+s.search,headers:o},r=>{let s="";r.setEncoding("utf8"),r.on("data",e=>{s+=e}),r.on("end",()=>{d&&clearTimeout(d);try{let r=JSON.parse(s);if(r.error){let e=r.error.data??{};n(new T(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 T("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void tn(e,t,r.result).then(i).catch(n);i(r.result)}catch(e){d&&clearTimeout(d),n(new T("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}})}),p=to(e),d="number"==typeof r?setTimeout(()=>{u.destroy(),n(tt(e,l,t.meta?.requestId,t.command,p,r))},r):void 0;u.on("error",e=>{d&&clearTimeout(d),n(tr(e,t.meta?.requestId,p))}),u.write(a),u.end()})}function to(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function ti(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function tn(e,t,r){let s=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===s.length||!e.baseUrl)return r;let a=r.data?{...r.data}:{},o=[];for(let r of s){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){o.push(r);continue}let s=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return l.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await tl({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:s,requestId:t.meta?.requestId}),a[r.field]=s,o.push({...r,localPath:s})}return a.artifacts=o,{ok:!0,data:a}}async function tl(e){var t,r;let s,a=new URL((t=e.baseUrl,r=e.artifactId,s=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,s).toString())),o="https:"===a.protocol?f:m;await h.promises.mkdir(l.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let s=!1,i=e.timeoutMs??ej,n=a=>{if(!s){if(s=!0,clearTimeout(u),a)return void h.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(a));t()}},l=o.request({protocol:a.protocol,host:a.hostname,port:a.port,method:"GET",path:a.pathname+a.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{n(new T("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=h.createWriteStream(e.destinationPath);r.on("error",e=>{n(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{n(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{n(new T("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>n())}),t.pipe(r)}),u=setTimeout(()=>{l.destroy(new T("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:i}))},i);l.on("error",t=>{t instanceof T?n(t):n(new T("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:i},t instanceof Error?t:void 0))}),l.end()})}function tu(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}function tp(e){return e.replace(/\/+$/,"")}function td(e){return"string"==typeof e&&e.trim()?tp(e.trim()):""}function tc(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function tm(e,t,r){return J(e,{env:t,cwd:r})}function tf(e){try{return h.accessSync(e,h.constants.F_OK),!0}catch{return!1}}function th(e,t,r){if(null==e||""===e)return t;let s=Number.parseInt(String(e),10);return Number.isInteger(s)?Math.max(s,r):t}function tg(e,t){let r;return{platform:t,bundleUrl:((r=new URL(`${tp(e)}/index.bundle`)).searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString())}}function ty(e,t){return{platform:t,metroHost:tc(e?.metro_host),metroPort:e?.metro_port,bundleUrl:tc(e?.metro_bundle_url),launchUrl:tc(e?.launch_url)}}async function tw(e){await new Promise(t=>setTimeout(t,e))}async function tb(e,t,r={}){try{let s=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:s.ok,status:s.status,body:await s.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function tv(e,t){try{let r=await tb(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function tD(e){var t,r,s;let a;try{a=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Error(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`);throw t}let o=await a.text(),i=o?JSON.parse(o):{};if(!a.ok)throw Error(`/api/metro/bridge failed (${a.status}): ${JSON.stringify(i)}`);return{enabled:(s=i.data??i).enabled,baseUrl:s.base_url,statusUrl:s.status_url,bundleUrl:s.bundle_url,iosRuntime:ty(s.ios_runtime,"ios"),androidRuntime:ty(s.android_runtime,"android"),upstream:{bundleUrl:s.upstream.bundle_url,host:s.upstream.host,port:s.upstream.port,statusUrl:s.upstream.status_url},probe:{reachable:s.probe.reachable,statusCode:s.probe.status_code,latencyMs:s.probe.latency_ms,detail:s.probe.detail}}}async function tk(e,t,r){let s=Date.now()+t;for(;Date.now()<s;){let t=Math.min(r,Math.max(s-Date.now(),1));if(await tv(e,t))return!0;let a=Math.min(500,Math.max(s-Date.now(),0));a>0&&await tw(a)}return!1}async function tI(e={}){let t=e.env??process.env,r=process.cwd(),s=tm(e.projectRoot??r,t,r),a=function(e,t){if("auto"!==t)return t;let r=function(e){let t=l.join(e,"package.json");if(!tf(t))throw new T("INVALID_ARGS",`package.json not found at ${t}`);return JSON.parse(h.readFileSync(t,"utf8"))}(e);return"string"==typeof({...r.dependencies??{},...r.devDependencies??{}}).expo?"expo":"react-native"}(s,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 T("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(e.metroPort??8081),i=tc(e.listenHost)??"0.0.0.0",n=tc(e.statusHost)??"127.0.0.1",u=td(e.publicBaseUrl),p=th(e.startupTimeoutMs,18e4,3e4),d=th(e.probeTimeoutMs,1e4,1e3),c=e.reuseExisting??!0,m=e.installDependenciesIfNeeded??!0,f=e.runtimeFilePath?tm(e.runtimeFilePath,t,r):null,g=tm(e.logPath??l.join(s,".agent-device","metro.log"),t,r);if(!u)throw new T("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:y,proxyBaseUrl:w,proxyBearerToken:b}=function(e,t){if(e&&!t)throw new T("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 T("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(td(e.proxyBaseUrl),tc(e.proxyBearerToken)??""),v=m?function(e,t){if(function(e){try{return h.statSync(e).isDirectory()}catch{return!1}}(l.join(e,"node_modules")))return{installed:!1};let r=tf(l.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:tf(l.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return B(r.command,r.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:r.command}}(s,t):{installed:!1},D=`http://${n}:${o}/status`,k=!1,I=!1,A=0;if(c&&await tv(D,d))I=!0;else if(k=!0,A=function(e,t,r,s,a,o){let i="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",s,"--port",String(r)]};h.mkdirSync(l.dirname(a),{recursive:!0});let n=h.openSync(a,"a"),u=0;try{u=S(i.command,i.installArgs,{cwd:e,env:o,stdio:["ignore",n,n]})}finally{h.closeSync(n)}if(!Number.isInteger(u)||u<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:u}}(s,a,o,i,g,t).pid,!await tk(D,p,d))throw Error(`Metro did not become ready at ${D} within ${p}ms. Check ${g}.`);let $=tg(u,"ios"),L=tg(u,"android"),E=null,P=null;if(y)try{E=await tD({baseUrl:w,bearerToken:b,runtime:{metro_bundle_url:$.bundleUrl},timeoutMs:d})}catch(e){P=e instanceof Error?e.message:String(e)}if(y&&(!E||!1===E.probe.reachable)){var N,x;let e;throw Error((N=P,x=E,e=[`Metro bridge is required for this run but could not be configured via ${w}/api/metro/bridge.`],N&&e.push(`bridgeError=${N}`),x?.probe.reachable===!1&&e.push(`bridgeProbe=${x.probe.detail||`unreachable (status ${x.probe.statusCode||0})`}`),e.join(" ")))}let _=E?.iosRuntime??$,M=E?.androidRuntime??L,O={projectRoot:s,kind:a,dependenciesInstalled:v.installed,packageManager:v.packageManager??null,started:k,reused:I,pid:A,logPath:g,statusUrl:D,runtimeFilePath:f,iosRuntime:_,androidRuntime:M,bridge:E};return f&&(h.mkdirSync(l.dirname(f),{recursive:!0}),h.writeFileSync(f,JSON.stringify(O,null,2))),O}function tA(e,t,r,s){let a=r(e[t]);if(void 0===a)throw new T("COMMAND_FAILED",s,{response:e});return a}function tS(e,t){return tA(e,t,tx,`Daemon response is missing "${t}".`)}function t$(e,t){return tx(e[t])}function tL(e,t){var r;let s;return r=tx,null===(s=e[t])?null:r(s)}function tE(e,t){return tA(e,t,tT,`Daemon response has invalid "${t}".`)}function tP(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function tN(e,t){let r=e[t];if(!tR(r))return;let s="number"==typeof r.x?r.x:void 0,a="number"==typeof r.y?r.y:void 0,o="number"==typeof r.width?r.width:void 0,i="number"==typeof r.height?r.height:void 0;if(void 0!==s&&void 0!==a&&void 0!==o&&void 0!==i)return{x:s,y:a,width:o,height:i}}function tx(e){return"string"==typeof e&&e.length>0?e:void 0}function t_(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function tT(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function tM(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function tO(e){if(!tR(e))throw new T("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function tR(e){return"object"==typeof e&&null!==e}function tF(e){let t={};for(let[r,s]of Object.entries(e))void 0!==s&&(t[r]=s);return t}function tC(e,t){let r=t$(e,"bundleId"),s=t$(e,"package");return{app:tS(e,"app"),appPath:tS(e,"appPath"),platform:tE(e,"platform"),appId:r??s,bundleId:r,package:s,identifiers:L({session:t,bundleId:r,packageName:s})}}function tU(e){let t=tO(e),r=tE(t,"platform"),s=tS(t,"id"),a=tS(t,"name");return{platform:r,target:tP(t,"target"),kind:tA(t,"kind",tM,'Daemon response has invalid "kind".'),id:s,name:a,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:$(r,s,a),ios:"ios"===r?{udid:s}:void 0,android:"android"===r?{serial:s}:void 0}}function tj(e){let t=tO(e),r=tE(t,"platform"),s=tS(t,"id"),a=tS(t,"name"),o=tP(t,"target"),i=tS(t,"device"),n={session:a,...$(r,s,i)};return{name:a,createdAt:tA(t,"createdAt",t_,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:o,id:s,name:i,identifiers:n,ios:"ios"===r?{udid:s,simulatorSetPath:tL(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:s}:void 0},identifiers:n}}function tV(e,t){return t??e??"default"}function tG(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function tB(e,t,r){var s;if(e.json)return void eT({success:!0,data:t});let a=r?.();a&&(s=a,process.stdout.write(s.endsWith("\n")?s:`${s}
|
|
35
|
+
`))}function tq(e,t){tB(e,t,()=>M(t))}function tJ(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",s="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${s}`}async function tz(e,t,r,s){let a=t[0],o=t[1];if(!a||!o)throw new T("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let i={app:a,appPath:o,...tG(r)};return"install"===e?await s.apps.install(i):await s.apps.reinstall(i)}async function tH(e,t,r){let s=e[0]?.trim();if(!s)throw new T("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new T("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await r.apps.installFromSource({...tG(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:s,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 T("INVALID_ARGS",`Invalid --header value "${r}". Expected "name:value".`);let s=r.slice(0,e).trim(),a=r.slice(e+1).trim();if(!s)throw new T("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[s]=a}return t}(t.header)}})}async function tW(e,t){if(!e.remoteConfig)return;let r=e.platform;if("ios"!==r&&"android"!==r)throw new T("INVALID_ARGS",'open --remote-config requires platform "ios" or "android" in the remote config file or CLI flags.');if(!e.metroPublicBaseUrl)throw new T("INVALID_ARGS",'open --remote-config requires "metroPublicBaseUrl" in the remote config file.');let s=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return"ios"===r?s.iosRuntime:s.androidRuntime}let tK=255*Math.sqrt(3);async function tY(e,t,r={}){await tX(e,"Baseline image not found"),await tX(t,"Current screenshot not found");let s=r.outputPath,[a,o]=await Promise.all([g.readFile(e),g.readFile(t)]),i=ee(a,"baseline screenshot"),n=ee(o,"current screenshot"),u=r.threshold??.1;if(i.width!==n.width||i.height!==n.height){let e=i.width*i.height;return await tZ(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:i.width,height:i.height},actual:{width:n.width,height:n.height}}}}let p=i.width*i.height,d=u*tK,c=new b({width:i.width,height:i.height}),m=0;for(let e=0;e<i.data.length;e+=4){if(Math.sqrt((i.data[e]-n.data[e])**2+(i.data[e+1]-n.data[e+1])**2+(i.data[e+2]-n.data[e+2])**2)>d){m+=1,c.data[e]=255,c.data[e+1]=0,c.data[e+2]=0,c.data[e+3]=255;continue}let t=Math.round(.3*Math.round((i.data[e]+i.data[e+1]+i.data[e+2])/3));c.data[e]=t,c.data[e+1]=t,c.data[e+2]=t,c.data[e+3]=255}m>0&&s?(await g.mkdir(l.dirname(s),{recursive:!0}),await g.writeFile(s,b.sync.write(c))):await tZ(r.outputPath);let f=p>0?Math.round(m/p*1e4)/100:0;return{...m>0&&s?{diffPath:s}:{},totalPixels:p,differentPixels:m,mismatchPercentage:f,match:0===m}}async function tX(e,t){try{await g.access(e)}catch{throw new T("INVALID_ARGS",`${t}: ${e}`)}}async function tZ(e){if(e)try{await g.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}let tQ={session:async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new T("INVALID_ARGS","session only supports list");let s={sessions:(await r.sessions.list()).map(k)};return tB(t,s,()=>JSON.stringify(s,null,2)),!0},devices:async({flags:e,client:t})=>{let r=await t.devices.list(tG(e));return tB(e,{devices:r.map(R)},()=>r.map(tJ).join("\n")),!0},"ensure-simulator":async({flags:e,client:t})=>{if(!e.device)throw new T("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 tB(e,O(r),()=>{let e=r.created?"Created":"Reused",t=r.booted?" (booted)":"";return r.runtime?`${e}: ${r.device} ${r.udid}${t}
|
|
36
|
+
Runtime: ${r.runtime}`:`${e}: ${r.device} ${r.udid}${t}`}),!0},metro:async({positionals:e,flags:t,client:r})=>{if("prepare"!==(e[0]??"").toLowerCase())throw new T("INVALID_ARGS","metro only supports prepare");if(!t.metroPublicBaseUrl)throw new T("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let s=await r.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile});return tB(t,s,()=>JSON.stringify(s,null,2)),!0},install:async({positionals:e,flags:t,client:r})=>{let s=_(await tz("install",e,t,r));return tq(t,s),!0},reinstall:async({positionals:e,flags:t,client:r})=>{let s=_(await tz("reinstall",e,t,r));return tq(t,s),!0},"install-from-source":async({positionals:e,flags:t,client:r})=>{let s=Q(await tH(e,t,r));return tq(t,s),!0},open:async({positionals:e,flags:t,client:r})=>{if(!e[0])return!1;let s=await tW(t,r),a=P(await r.apps.open({app:e[0],url:e[1],surface:t.surface,activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,runtime:s,...tG(t)}));return tq(t,a),!0},close:async({positionals:e,flags:t,client:r})=>{let s=z(e[0]?await r.apps.close({app:e[0],shutdown:t.shutdown}):await r.sessions.close({shutdown:t.shutdown}));return tq(t,s),!0},snapshot:async({flags:e,client:t})=>{let r=I(await t.capture.snapshot({...tG(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return tB(e,r,()=>eO(r,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},screenshot:async({positionals:e,flags:t,client:r})=>{let s=await r.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs});return tB(t,{path:s.path,...s.overlayRefs?{overlayRefs:s.overlayRefs}:{}},()=>s.overlayRefs?`Annotated ${s.overlayRefs.length} refs onto ${s.path}`:s.path),!0},diff:async({positionals:e,flags:t,client:r})=>{let s;if("screenshot"!==e[0])return!1;let a=t.baseline;if(!a||"string"!=typeof a)throw new T("INVALID_ARGS","diff screenshot requires --baseline <path>");let o=J(a),i="string"==typeof t.out?J(t.out):void 0,n=.1;if(null!=t.threshold&&""!==t.threshold&&(Number.isNaN(n=Number(t.threshold))||n<0||n>1))throw new T("INVALID_ARGS","--threshold must be a number between 0 and 1");let p=h.mkdtempSync(l.join(w.tmpdir(),"agent-device-diff-current-")),d=l.join(p,`current-${Date.now()}.png`),c=(await r.capture.screenshot({path:d})).path;try{s=await tY(o,c,{threshold:n,outputPath:i})}finally{try{h.unlinkSync(c)}catch{}try{h.rmSync(p,{recursive:!0,force:!0})}catch{}}return tB(t,s,()=>(function(e){let t=eF(),r=!0===e.match,s=eR(e.differentPixels),a=eR(e.totalPixels),o=eR(e.mismatchPercentage),i=e.diffPath,n=e.dimensionMismatch,p=[];if(r){let e=t?u("green","✓"):"✓";p.push(`${e} Screenshots match.`)}else if(n){let e=t?u("red","✗"):"✗",r=n.expected,s=n.actual;p.push(`${e} Screenshots have different dimensions: expected ${r?.width}x${r?.height}, got ${s?.width}x${s?.height}`)}else{let e=t?u("red","✗"):"✗",r=0===o&&s>0?"<0.01":String(o);p.push(`${e} ${r}% pixels differ`)}if(i&&!r){var d;let e,r,s=(d=i,e=process.cwd(),""!==(r=l.relative(e,d))&&(r.startsWith("..")||l.isAbsolute(r))?d:""===r?".":`.${l.sep}${r}`),a=t?u("dim","Diff image:"):"Diff image:",o=t?u("green",s):s;p.push(` ${a} ${o}`)}if(!r&&!n){let e=t?u("red",String(s)):String(s);p.push(` ${e} different / ${a} total pixels`)}return`${p.join("\n")}
|
|
37
|
+
`})(s)),!0}};async function t0(e){let t=tQ[e.command];return!!t&&await t(e)}function t1(e){let{suite:t,json:r,verbose:s,reportJunit:a}=e;return(a&&function(e,t){let r=l.dirname(e);try{h.mkdirSync(r,{recursive:!0}),h.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="${t5(e.durationMs)}">`];for(let r of e.tests)t.push(...function(e){let t=t8(l.basename(e.file)),r=t8("."===l.dirname(e.file)?e.file:l.dirname(e.file)),s=t8(e.file),a=t5(e.durationMs),o=[` <testcase classname="${r}" name="${t}" file="${s}" time="${a}">`];"failed"===e.status?o.push(` <failure message="${t8(e.error.message)}">${t8(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="${t8(e.message)}" />`);let i=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 i&&o.push(` <system-out>${t8(i)}</system-out>`),o.push(" </testcase>"),o}(r));return t.push(" </testsuite>"),t.push("</testsuites>"),`${t.join("\n")}
|
|
38
|
+
`}(t),"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new T("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(a,t),r)?(eT({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let r=e.tests.filter(t3);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return t2(e);let t="passed"===e.status?t3(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",r="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",s=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${r}${s}
|
|
38
39
|
`),"skipped"===e.status&&process.stdout.write(` ${e.message??"skipped"}
|
|
39
|
-
`)}(t);else{for(let t of e.failures)
|
|
40
|
-
`)}(e)}let s="number"==typeof e.durationMs?e.durationMs:void 0,
|
|
41
|
-
`),function(e){return+(e.failed>0)}(e)}(t,{verbose:s})}function
|
|
40
|
+
`)}(t);else{for(let t of e.failures)t2(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}
|
|
41
|
+
`)}(e)}let s="number"==typeof e.durationMs?e.durationMs:void 0,a=r.length>0?`, ${r.length} flaky`:"";return process.stdout.write(`Test summary: ${e.passed} passed, ${e.failed} failed${a}${void 0!==s?` in ${s}ms`:""}
|
|
42
|
+
`),function(e){return+(e.failed>0)}(e)}(t,{verbose:s})}function t2(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}
|
|
42
43
|
`),process.stdout.write(` ${e.error?.message??"Unknown test failure"}
|
|
43
44
|
`),e.error?.hint&&process.stdout.write(` hint: ${e.error.hint}
|
|
44
45
|
`),e.artifactsDir&&process.stdout.write(` artifacts: ${e.artifactsDir}
|
|
45
46
|
`),e.error?.logPath&&process.stdout.write(` log: ${e.error.logPath}
|
|
46
47
|
`),e.error?.diagnosticId&&process.stdout.write(` diagnostic: ${e.error.diagnosticId}
|
|
47
|
-
`)}function t0(e){return"passed"===e.status&&e.attempts>1}function t1(e){return(Math.max(0,e)/1e3).toFixed(3)}function t2(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function t3(e,t={}){let r=t5(t),s={...e};return r.defaultPlatform&&void 0===s.platform&&(s.platform=r.defaultPlatform),s}function t5(e){var t,r,s,o;let a,i=e.env??process.env,n=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 N("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(i.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??i.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:n,lockPolicy:(r=e.policyOverrides,s=i,o=l,(a=r?.sessionLock??r?.sessionLockConflicts??t8(s.AGENT_DEVICE_SESSION_LOCK)??t8(s.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||function(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;default:return!1}}(s.AGENT_DEVICE_SESSION_LOCKED)||o?"reject":void 0))}}function t8(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new N("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let t4=["stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],t7=new Set(["stateDir","iosSimulatorDeviceSet","metroProjectRoot","metroRuntimeFile"]),t6=["remoteConfig","session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],t9={sendToDaemon:eV};async function re(e,t=t9){let r=O(),s=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),o=e.includes("--json"),a=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 W({session:a,requestId:r,command:e[0],debug:s},async()=>{var a,i,u,p,d,c,f,h,g,y;let w;try{let t,r,s,o,l,y,b,v,D;a={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,s=[],o=[],a=!0;for(let i=0;i<e.length;i+=1){let n=e[i];if(a&&"--"===n){a=!1;continue}if(!a){r?s.push(n):r=ex(n);continue}let l=n.startsWith("--"),u=n.startsWith("-")&&n.length>1;if(!l&&!u){r?s.push(n):r=ex(n);continue}let[p,d]=l?eL(n):[n,void 0],c=en.get(p);if(!c){if(function(e,t,r){var s;if(s=r,!/^-\d+(\.\d+)?$/.test(s)||!e)return!1;let o=eu(e);return!o||!!o.allowsExtraPositionals||0!==o.positionalArgs.length&&(t.length<o.positionalArgs.length||o.positionalArgs.some(e=>e.includes("?")))}(r,s,n)){r?s.push(n):r=n;continue}throw new N("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,r,s){if(void 0!==e.setValue){if(void 0!==r)throw new N("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 N("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 N("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:r,consumeNext:!1}}return void 0===s||eP(s)||!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("\\"))}(s)?{value:!0,consumeNext:!1}:{value:s,consumeNext:!0}}let o=r??s;if(void 0===o||void 0===r&&eP(o))throw new N("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:o,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(o))throw new N("INVALID_ARGS",`Invalid ${eE(t)}: ${o}`);return{value:o,consumeNext:void 0===r}}let a=Number(o);if(!Number.isFinite(a)||"number"==typeof e.min&&a<e.min||"number"==typeof e.max&&a>e.max)throw new N("INVALID_ARGS",`Invalid ${eE(t)}: ${o}`);return{value:Math.floor(a),consumeNext:void 0===r}}(c,p,d,e[i+1]);m.consumeNext&&(i+=1);let f=t[c.key];if(c.multiple){let e=Array.isArray(f)?[...f,m.value]:void 0===f?[m.value]:[f,m.value];t[c.key]=e}else t[c.key]=m.value;o.push({key:c.key,token:p})}return{command:r,positionals:s,flags:t,warnings:[],providedFlags:o}}(e),r=a?.env??process.env,s=a?.cwd??process.cwd(),o=function(e){if(!e.cliFlags.remoteConfig)return{};let t=function(e,t){let r={};for(let s of t){let t=ek(s);if(!t)continue;let o=t.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);o&&(r[s]=eS(t,o.value,`environment variable ${o.name}`,o.name))}return r}(e.env,t6);return et(t,function(e){let t,r,s=e.env??process.env,o=B(e.configPath,{cwd:e.cwd,env:s});if(!m.existsSync(o))throw new N("INVALID_ARGS",`Remote config file not found: ${o}`);try{t=m.readFileSync(o,"utf8")}catch(e){throw new N("INVALID_ARGS",`Failed to read remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}try{r=JSON.parse(t)}catch(e){throw new N("INVALID_ARGS",`Invalid JSON in remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new N("INVALID_ARGS",`Remote config file must contain a JSON object: ${o}`);let a={},i=r,l=n.dirname(o);for(let[e,t]of Object.entries(i)){if(!t4.includes(e))throw new N("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${o}.`);let r=ek(e);if(!r)throw new N("INVALID_ARGS",`Unknown remote config key "${e}" in remote config file ${o}.`);let i=eS(r,t,`remote config file ${o}`,e);a[e]="string"==typeof i&&t7.has(e)?B(i,{cwd:l,env:s}):i}return a}({configPath:e.cliFlags.remoteConfig,cwd:e.cwd,env:e.env})),t.remoteConfig=e.cliFlags.remoteConfig,t}({cliFlags:t.flags,cwd:s,env:r}),b=et((l=(i={command:t.command,cwd:s,cliFlags:t.flags,env:r}).env??process.env,y=et({},function(e){let t={};for(let r of e)et(t,function(e,t){let r,s;if(!m.existsSync(e)){if(t)throw new N("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{r=m.readFileSync(e,"utf8")}catch(t){throw new N("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{s=JSON.parse(r)}catch(t){throw new N("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new N("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[s,o]of Object.entries(e)){let e=ek(s);if(!e)throw new N("INVALID_ARGS",`Unknown config key "${s}" in ${t}.`);if(!e.config.enabled)throw new N("INVALID_ARGS",`Unsupported config key "${s}" in ${t}.`);r[s]=eS(e,o,t,s)}return r}(s,`config file ${e}`)}(r.path,r.required));return t}((u=i.cwd,p=i.cliFlags.config,d=l,(D=p??d.AGENT_DEVICE_CONFIG)?[{path:(c=D,f=u,h=d,B(c,{cwd:f,env:h})),required:!0}]:[{path:(g=d,n.join(P("~",{env:g}),".agent-device","config.json")),required:!1},{path:n.resolve(u,"agent-device.json"),required:!1}]))),et(y,function(e,t){let r={};for(let s of eD.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&&(r[s.key]=eS(s,t.value,`environment variable ${t.name}`,t.name))}return r}(l,i.command))),o),v=function(e,t){let r=t?.strictFlags??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),s=[...e.warnings],o=et({json:!1,help:!1,version:!1},t?.defaultFlags??{});et(o,e.flags);let a=eu(e.command),i=e.providedFlags.filter(t=>!eA(t.key,e.command));if(i.length>0){var n,l;let t=i.map(e=>e.token),a=(n=e.command,l=t,n?1===l.length?`Flag ${l[0]} is not supported for command ${n}.`:`Flags ${l.join(", ")} are not supported for command ${n}.`: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 N("INVALID_ARGS",a);for(let e of(s.push(`${a} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),i))delete o[e.key]}for(let t of Object.keys(o))void 0!==o[t]&&(eA(t,e.command)||delete o[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 N("INVALID_ARGS","back accepts only one explicit mode flag: use either --in-app or --system.")}(e),a?.defaults)for(let[e,t]of Object.entries(a.defaults))void 0===o[e]&&(o[e]=t);if("batch"===e.command&&1!=+!!o.steps+ +!!o.stepsFile)throw new N("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:e.command,positionals:e.positionals,flags:o,warnings:s}}(t,{strictFlags:a?.strictFlags,defaultFlags:b}),"open"===t.command&&t.flags.remoteConfig&&function(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&void 0===e[r]&&(e[r]=s)}(v.flags,function(e){let t={};for(let r of t6){let s=e[r];void 0!==s&&(t[r]=s)}return t}(b)),w=v}catch(t){z({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=F(t,{diagnosticId:j().diagnosticId,logPath:K({force:!0})??void 0});o?eN({success:!1,error:e}):e_(e,{showDetails:s}),process.exit(1);return}for(let e of w.warnings)process.stderr.write(`Warning: ${e}
|
|
48
|
-
`);w.
|
|
49
|
-
`)
|
|
50
|
-
`),process.exit(0));let
|
|
48
|
+
`)}function t3(e){return"passed"===e.status&&e.attempts>1}function t5(e){return(Math.max(0,e)/1e3).toFixed(3)}function t8(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function t4(e,t={}){let r=t7(t),s={...e};return r.defaultPlatform&&void 0===s.platform&&(s.platform=r.defaultPlatform),s}function t7(e){var t,r,s,a;let o,i=e.env??process.env,n=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 T("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(i.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??i.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:n,lockPolicy:(r=e.policyOverrides,s=i,a=l,(o=r?.sessionLock??r?.sessionLockConflicts??t6(s.AGENT_DEVICE_SESSION_LOCK)??t6(s.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||function(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;default:return!1}}(s.AGENT_DEVICE_SESSION_LOCKED)||a?"reject":void 0))}}function t6(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new T("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let t9=["stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],re=new Set(["stateDir","iosSimulatorDeviceSet","metroProjectRoot","metroRuntimeFile"]),rt=["remoteConfig","session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],rr="agent-device",rs="--agent-device-run-update-check";async function ra(e){let t=Date.now(),r=ro(e.cachePath);try{let s=await rn()??void 0;if(!s||0>=rl(s,e.currentVersion))return void ri(e.cachePath,{checkedAt:new Date(t).toISOString()});ri(e.cachePath,{checkedAt:new Date(t).toISOString(),latestVersion:s,prompted:r.latestVersion===s&&!0===r.prompted})}catch{ri(e.cachePath,{...r,checkedAt:new Date(t).toISOString()})}}function ro(e){try{let t=JSON.parse(h.readFileSync(e,"utf8"));return{checkedAt:"string"==typeof t.checkedAt?t.checkedAt:void 0,latestVersion:"string"==typeof t.latestVersion?t.latestVersion:void 0,prompted:!0===t.prompted}}catch{return{}}}function ri(e,t){try{h.mkdirSync(l.dirname(e),{recursive:!0}),h.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
49
|
+
`,"utf8")}catch{}}async function rn(){let e=await fetch(`https://registry.npmjs.org/${rr}/latest`,{signal:AbortSignal.timeout(3500),headers:{accept:"application/json"}});if(!e.ok)return;let t=await e.json();return"string"==typeof t.version&&t.version.trim().length>0?t.version.trim():void 0}function rl(e,t){return e.localeCompare(t,void 0,{numeric:!0})}if((n=process.argv[1])&&d(l.resolve(n)).href===import.meta.url){let e=function(e){if(e[0]!==rs)return null;let t=e[1]?.trim(),r=e[2]?.trim();return t&&r?{cachePath:t,currentVersion:r}:null}(process.argv.slice(2));e&&ra(e).catch(()=>{process.exitCode=0})}let ru={sendToDaemon:eq};async function rp(e,t=ru){let r=C(),s=j(),a=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),o=e.includes("--json"),i=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 Y({session:i,requestId:r,command:e[0],debug:a},async()=>{var i,n,d,c,m,f,g,y,w,b;let v;try{let t,r,s,a,o,u,p,b,D;i={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,s=[],a=[],o=!0;for(let i=0;i<e.length;i+=1){let n=e[i];if(o&&"--"===n){o=!1;continue}if(!o){r?s.push(n):r=e_(n);continue}let l=n.startsWith("--"),u=n.startsWith("-")&&n.length>1;if(!l&&!u){r?s.push(n):r=e_(n);continue}let[p,d]=l?eP(n):[n,void 0],c=eu.get(p);if(!c){if(function(e,t,r){var s;if(s=r,!/^-\d+(\.\d+)?$/.test(s)||!e)return!1;let a=ed(e);return!a||!!a.allowsExtraPositionals||0!==a.positionalArgs.length&&(t.length<a.positionalArgs.length||a.positionalArgs.some(e=>e.includes("?")))}(r,s,n)){r?s.push(n):r=n;continue}throw new T("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,r,s){if(void 0!==e.setValue){if(void 0!==r)throw new T("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 T("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 T("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:r,consumeNext:!1}}return void 0===s||ex(s)||!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("\\"))}(s)?{value:!0,consumeNext:!1}:{value:s,consumeNext:!0}}let a=r??s;if(void 0===a||void 0===r&&ex(a))throw new T("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:a,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(a))throw new T("INVALID_ARGS",`Invalid ${eN(t)}: ${a}`);return{value:a,consumeNext:void 0===r}}let o=Number(a);if(!Number.isFinite(o)||"number"==typeof e.min&&o<e.min||"number"==typeof e.max&&o>e.max)throw new T("INVALID_ARGS",`Invalid ${eN(t)}: ${a}`);return{value:Math.floor(o),consumeNext:void 0===r}}(c,p,d,e[i+1]);m.consumeNext&&(i+=1);let f=t[c.key];if(c.multiple){let e=Array.isArray(f)?[...f,m.value]:void 0===f?[m.value]:[f,m.value];t[c.key]=e}else t[c.key]=m.value;a.push({key:c.key,token:p})}return{command:r,positionals:s,flags:t,warnings:[],providedFlags:a}}(e),r=i?.env??process.env,s=i?.cwd??process.cwd(),a=function(e){if(!e.cliFlags.remoteConfig)return{};let t=function(e,t){let r={};for(let s of t){let t=eS(s);if(!t)continue;let a=t.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);a&&(r[s]=eL(t,a.value,`environment variable ${a.name}`,a.name))}return r}(e.env,rt);return es(t,function(e){let t,r,s=e.env??process.env,a=J(e.configPath,{cwd:e.cwd,env:s});if(!h.existsSync(a))throw new T("INVALID_ARGS",`Remote config file not found: ${a}`);try{t=h.readFileSync(a,"utf8")}catch(e){throw new T("INVALID_ARGS",`Failed to read remote config file: ${a}`,{cause:e instanceof Error?e.message:String(e)})}try{r=JSON.parse(t)}catch(e){throw new T("INVALID_ARGS",`Invalid JSON in remote config file: ${a}`,{cause:e instanceof Error?e.message:String(e)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new T("INVALID_ARGS",`Remote config file must contain a JSON object: ${a}`);let o={},i=r,n=l.dirname(a);for(let[e,t]of Object.entries(i)){if(!t9.includes(e))throw new T("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${a}.`);let r=eS(e);if(!r)throw new T("INVALID_ARGS",`Unknown remote config key "${e}" in remote config file ${a}.`);let i=eL(r,t,`remote config file ${a}`,e);o[e]="string"==typeof i&&re.has(e)?J(i,{cwd:n,env:s}):i}return o}({configPath:e.cliFlags.remoteConfig,cwd:e.cwd,env:e.env})),t.remoteConfig=e.cliFlags.remoteConfig,t}({cliFlags:t.flags,cwd:s,env:r}),p=es((o=(n={command:t.command,cwd:s,cliFlags:t.flags,env:r}).env??process.env,u=es({},function(e){let t={};for(let r of e)es(t,function(e,t){let r,s;if(!h.existsSync(e)){if(t)throw new T("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{r=h.readFileSync(e,"utf8")}catch(t){throw new T("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{s=JSON.parse(r)}catch(t){throw new T("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new T("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[s,a]of Object.entries(e)){let e=eS(s);if(!e)throw new T("INVALID_ARGS",`Unknown config key "${s}" in ${t}.`);if(!e.config.enabled)throw new T("INVALID_ARGS",`Unsupported config key "${s}" in ${t}.`);r[s]=eL(e,a,t,s)}return r}(s,`config file ${e}`)}(r.path,r.required));return t}((d=n.cwd,c=n.cliFlags.config,m=o,(D=c??m.AGENT_DEVICE_CONFIG)?[{path:(f=D,g=d,y=m,J(f,{cwd:g,env:y})),required:!0}]:[{path:(w=m,l.join(x("~",{env:w}),".agent-device","config.json")),required:!1},{path:l.resolve(d,"agent-device.json"),required:!1}]))),es(u,function(e,t){let r={};for(let s of eI.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&&(r[s.key]=eL(s,t.value,`environment variable ${t.name}`,t.name))}return r}(o,n.command))),a),b=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),s=[...e.warnings],a=es({json:!1,help:!1,version:!1},t?.defaultFlags??{});es(a,e.flags);let o=ed(e.command),i=e.providedFlags.filter(t=>!e$(t.key,e.command));if(i.length>0){var n,l;let t=i.map(e=>e.token),o=(n=e.command,l=t,n?1===l.length?`Flag ${l[0]} is not supported for command ${n}.`:`Flags ${l.join(", ")} are not supported for command ${n}.`: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 T("INVALID_ARGS",o);for(let e of(s.push(`${o} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),i))delete a[e.key]}for(let t of Object.keys(a))void 0!==a[t]&&(e$(t,e.command)||delete a[t]);if(function(e){if("back"===e.command&&!(new Set(e.providedFlags.filter(e=>"backMode"===e.key).map(e=>e.token)).size<=1))throw new T("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===a[e]&&(a[e]=t);if("batch"===e.command&&1!=+!!a.steps+ +!!a.stepsFile)throw new T("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return function(e){if(e.flags.help)return e;if("snapshot"===e.command&&e.flags.snapshotDiff){let{snapshotDiff:t,...r}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:r,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:a,warnings:s})}(t,{strictFlags:i?.strictFlags,defaultFlags:p}),"open"===t.command&&t.flags.remoteConfig&&function(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&void 0===e[r]&&(e[r]=s)}(b.flags,function(e){let t={};for(let r of rt){let s=e[r];void 0!==s&&(t[r]=s)}return t}(p)),v=b}catch(t){H({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=U(t,{diagnosticId:G().diagnosticId,logPath:X({force:!0})??void 0});o?eT({success:!1,error:e}):eM(e,{showDetails:a}),process.exit(1);return}for(let e of v.warnings)process.stderr.write(`Warning: ${e}
|
|
50
|
+
`);v.flags.version&&(process.stdout.write(`${s}
|
|
51
|
+
`),process.exit(0));let k="help"===v.command,I=v.flags.help;if(k||I){k&&v.positionals.length>1&&(eM(new T("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=k?v.positionals[0]:v.command;e||(process.stdout.write(`${ef}
|
|
52
|
+
`),process.exit(0));let t=function(e){var t,r;let s=ed(e);if(!s)return null;let a=(t=e,(r=s).usageOverride?r.usageOverride:[t,...r.positionalArgs.map(em),...r.allowedFlags.flatMap(e=>(ep.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),o=eh(new Set(s.allowedFlags)),i=eh(en),n=[];return o.length>0&&n.push(eg("Command flags:",o)),n.push(eg("Global flags:",i)),`agent-device ${a}
|
|
51
53
|
|
|
52
54
|
${s.helpDescription}
|
|
53
55
|
|
|
54
56
|
Usage:
|
|
55
|
-
agent-device ${
|
|
57
|
+
agent-device ${a}
|
|
56
58
|
|
|
57
59
|
${n.join("\n\n")}
|
|
58
|
-
`}(
|
|
59
|
-
`),process.exit(1)}
|
|
60
|
-
`),process.exit(1));let{command:
|
|
61
|
-
`),
|
|
62
|
-
`)
|
|
63
|
-
|
|
64
|
-
`:"";if(
|
|
65
|
-
`;let f
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
`),
|
|
69
|
-
`),
|
|
70
|
-
`),
|
|
71
|
-
`),
|
|
72
|
-
`),
|
|
73
|
-
`),
|
|
74
|
-
`),
|
|
75
|
-
`),
|
|
76
|
-
`),
|
|
77
|
-
`),
|
|
78
|
-
`);
|
|
79
|
-
`)}if(
|
|
80
|
-
`)
|
|
81
|
-
`)
|
|
82
|
-
`)}
|
|
83
|
-
`),
|
|
84
|
-
`)
|
|
60
|
+
`}(e_(e));t&&(process.stdout.write(t),process.exit(0)),eM(new T("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${ef}
|
|
61
|
+
`),process.exit(1)}v.command||(process.stdout.write(`${ef}
|
|
62
|
+
`),process.exit(1));let{command:A,positionals:E}=v,P=t7({policyOverrides:v.flags,configuredPlatform:v.flags.platform,configuredSession:v.flags.session}),_=P.lockPolicy?{...v.flags}:t4(v.flags,{policyOverrides:v.flags,configuredPlatform:v.flags.platform,configuredSession:v.flags.session}),O=function(e){let{json:t,config:r,remoteConfig:s,help:a,version:o,sessionLock:i,sessionLocked:n,sessionLockConflicts:l,...u}=e;return u}(_),R=K(_.stateDir),F=_.session??"default";!function(e){var t,r,s,a,o,i,n;let u,d,c;if(!(!(!(t=e).command||"help"===t.command||"test"===t.command||t.flags.help||t.flags.version||t.flags.json||process.env.CI?.trim()||"test"===process.env.NODE_ENV||process.env.AGENT_DEVICE_NO_UPDATE_NOTIFIER?.trim())&&process.stderr.isTTY))return;let m=Date.now(),f=l.join(e.stateDir,"update-check.json"),h=ro(f);r=h,s=e.currentVersion,!r.latestVersion||0>=rl(r.latestVersion,s)||!0===r.prompted||(process.stderr.write(`Update available: ${rr} ${e.currentVersion} -> ${h.latestVersion}. Run \`npm install -g ${rr}@latest\` to upgrade the CLI and bundled skills.
|
|
63
|
+
`),ri(f,{...h,prompted:!0})),a=h,o=m,(void 0===(u=function(e){if(!e)return;let t=Date.parse(e);return Number.isNaN(t)?void 0:t}(a.checkedAt))||o-u>=12096e5)&&(i=f,n=e.currentVersion,c=(d=p(import.meta.url)).endsWith(".ts")?["--experimental-strip-types"]:[],S(process.execPath,[...c,d,rs,i,n]))}({command:A,currentVersion:s,stateDir:R.baseDir,flags:_});let C=_.daemonBaseUrl,j=!_.verbose||_.json||C?null:function(e){try{let t=0,r=!1,s=setInterval(()=>{if(!r&&h.existsSync(e))try{let r=h.statSync(e);if(r.size<t&&(t=0),r.size<=t)return;let s=h.openSync(e,"r");try{let e=Buffer.alloc(r.size-t);h.readSync(s,e,0,e.length,t),t=r.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{h.closeSync(s)}}catch{}},200);return()=>{r=!0,clearInterval(s)}}catch{return null}}(R.logPath),V=function(e={},t={}){let r=t.transport??eq,s=async(t,s=[],a={})=>{let o={...e,...a},i=await r({session:tV(e.session,a.session),command:t,positionals:s,flags:tF({stateDir:o.stateDir,daemonBaseUrl:o.daemonBaseUrl,daemonAuthToken:o.daemonAuthToken,daemonTransport:o.daemonTransport,daemonServerMode:o.daemonServerMode,tenant:o.tenant,sessionIsolation:o.sessionIsolation,runId:o.runId,leaseId:o.leaseId,platform:o.platform,target:o.target,device:o.device,udid:o.udid,serial:o.serial,iosSimulatorDeviceSet:o.iosSimulatorDeviceSet,androidDeviceAllowlist:o.androidDeviceAllowlist,runtime:o.simulatorRuntimeId,boot:o.boot,reuseExisting:o.reuseExisting,surface:o.surface,activity:o.activity,relaunch:o.relaunch,shutdown:o.shutdown,saveScript:o.saveScript,noRecord:o.noRecord,metroHost:o.metroHost,metroPort:o.metroPort,bundleUrl:o.bundleUrl,launchUrl:o.launchUrl,snapshotInteractiveOnly:o.interactiveOnly,snapshotCompact:o.compact,snapshotDepth:o.depth,snapshotScope:o.scope,snapshotRaw:o.raw,overlayRefs:o.overlayRefs,verbose:o.debug}),runtime:o.runtime,meta:tF({requestId:o.requestId,cwd:o.cwd,debug:o.debug,lockPolicy:o.lockPolicy,lockPlatform:o.lockPlatform,tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId,sessionIsolation:o.sessionIsolation,installSource:o.installSource,retainMaterializedPaths:o.retainMaterializedPaths,materializedPathRetentionMs:o.materializedPathRetentionMs,materializationId:o.materializationId})});if(!i.ok)throw new T(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});return i.data??{}},a=async(e={})=>{let t=await s("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(tj)};return{devices:{list:async(e={})=>{let t=await s("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(tU)}},sessions:{list:async(e={})=>await a(e),close:async(t={})=>{let r=tV(e.session,t.session),a=(await s("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,a=await s("ensure-simulator",[],{...r,simulatorRuntimeId:t}),o=tS(a,"udid"),i=tS(a,"device");return{udid:o,device:i,runtime:tS(a,"runtime"),created:!0===a.created,booted:!0===a.booted,iosSimulatorDeviceSet:tL(a,"ios_simulator_device_set"),identifiers:{deviceId:o,deviceName:i,udid:o}}}},apps:{install:async t=>tC(await s("install",[t.app,t.appPath],t),tV(e.session,t.session)),reinstall:async t=>tC(await s("reinstall",[t.app,t.appPath],t),tV(e.session,t.session)),installFromSource:async t=>(function(e,t){let r=t$(e,"bundleId"),s=t$(e,"packageName"),a=r??s??t$(e,"appId"),o=t$(e,"launchTarget")??s??r??a;if(!o)throw new T("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:t$(e,"appName"),appId:a,bundleId:r,packageName:s,launchTarget:o,installablePath:t$(e,"installablePath"),archivePath:t$(e,"archivePath"),materializationId:t$(e,"materializationId"),materializationExpiresAt:t$(e,"materializationExpiresAt"),identifiers:L({session:t,bundleId:r,packageName:s,appId:a})}})(await s("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),tV(e.session,t.session)),open:async t=>{let r=tV(e.session,t.session),a=t.url?[t.app,t.url]:[t.app],o=await s("open",a,t),i=function(e){let t=e.platform,r=t$(e,"id"),s=t$(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!s)return;let a=tP(e,"target"),o=$(t,r,s);return{platform:t,target:a,id:r,name:s,identifiers:o,ios:"ios"===t?{udid:t$(e,"device_udid")??r,simulatorSetPath:tL(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:t$(e,"serial")??r}:void 0}}(o),n=t$(o,"appBundleId");return{session:r,appName:t$(o,"appName"),appBundleId:n,appId:n,startup:function(e){if(tR(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:t$(e,"appTarget"),appBundleId:t$(e,"appBundleId")}}(o.startup),runtime:function(e){if(!tR(e))return;let t=e.platform,r=t$(e,"metroHost"),s="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:s,bundleUrl:t$(e,"bundleUrl"),launchUrl:t$(e,"launchUrl")}}(o.runtime),device:i,identifiers:{session:r,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:n,appBundleId:n}}},close:async(t={})=>{let r=tV(e.session,t.session),a=(await s("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await s("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:tS(t,"materializationId"),identifiers:{}}}},metro:{prepare:async t=>await tI({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,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(t={})=>{var r;let a=tV(e.session,t.session),o=await s("snapshot",[],t),i=t$(o,"appBundleId");return{nodes:Array.isArray(r=o.nodes)?r:[],truncated:!0===o.truncated,appName:t$(o,"appName"),appBundleId:i,warnings:Array.isArray(o.warnings)?o.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:a,appId:i,appBundleId:i}}},screenshot:async(t={})=>{let r=tV(e.session,t.session),a=await s("screenshot",t.path?[t.path]:[],t);return{path:tS(a,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!tR(e))continue;let t=t$(e,"ref"),s=tN(e,"rect"),a=tN(e,"overlayRect"),o=function(e,t){let r=e[t];if(!tR(r))return;let s="number"==typeof r.x?r.x:void 0,a="number"==typeof r.y?r.y:void 0;if(void 0!==s&&void 0!==a)return{x:s,y:a}}(e,"center");t&&s&&a&&o&&r.push({ref:t,label:t$(e,"label"),rect:s,overlayRect:a,center:o})}return r}(a),identifiers:{session:r}}}}}}({session:F,requestId:r,stateDir:_.stateDir,daemonBaseUrl:_.daemonBaseUrl,daemonAuthToken:_.daemonAuthToken,daemonTransport:_.daemonTransport,daemonServerMode:_.daemonServerMode,tenant:_.tenant,sessionIsolation:_.sessionIsolation,runId:_.runId,leaseId:_.leaseId,lockPolicy:P.lockPolicy,lockPlatform:P.defaultPlatform,cwd:process.cwd(),debug:!!_.verbose},{transport:t.sendToDaemon}),B=async e=>await t.sendToDaemon({session:F,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:r,debug:!!_.verbose,cwd:process.cwd(),tenantId:_.tenant,runId:_.runId,leaseId:_.leaseId,sessionIsolation:_.sessionIsolation,lockPolicy:P.lockPolicy,lockPlatform:P.defaultPlatform}});try{if("batch"===A){if(E.length>0)throw new T("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=h.readFileSync(e.stepsFile,"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new T("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return D(t)})(_).map((e,t)=>({...e,flags:P.lockPolicy&&void 0===_.platform?{...e.flags??{}}:t4(e.flags??{},{policyOverrides:_,configuredPlatform:_.platform,configuredSession:_.session,inheritedPlatform:_.platform})})),t={...O,batchSteps:e};delete t.steps,delete t.stepsFile;let r=await B({command:"batch",positionals:E,flags:t});if(!r.ok)throw new T(r.error.code,r.error.message,{...r.error.details??{},hint:r.error.hint,diagnosticId:r.error.diagnosticId,logPath:r.error.logPath});_.json?eT({success:!0,data:r.data??{}}):function(e){let t="number"==typeof e.total?e.total:0,r="number"==typeof e.executed?e.executed:0,s="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let o of(process.stdout.write(`Batch completed: ${r}/${t} steps${void 0!==s?` in ${s}ms`:""}
|
|
64
|
+
`),Array.isArray(e.results)?e.results:[])){var a;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,s="number"==typeof o.durationMs?o.durationMs:void 0,i=o.data&&"object"==typeof o.data?o.data:void 0,n=o.error&&"object"==typeof o.error?o.error:void 0,l=r?M(i)??t:(a=n,("string"==typeof a?.message&&a.message.length>0?a.message:null)??t),u=void 0!==e?`${e}. `:"- ",p=void 0!==s?` (${s}ms)`:"";process.stdout.write(`${u}${r?"OK":"FAILED"} ${l}${p}
|
|
65
|
+
`)}}(r.data??{}),j&&j();return}if("runtime"===A)throw new T("INVALID_ARGS","runtime command was removed. Use open --remote-config <path> --relaunch for remote Metro launches, or metro prepare --remote-config <path> for inspection.");if(await t0({command:A,positionals:E,flags:_,client:V})){j&&j();return}"test"===A&&(({json:_.json}).json||process.stderr.write("Running replay suite...\n"));let e=await B({command:A,positionals:E,flags:O});if(e.ok){if(_.json){if("test"===A){let t=t1({suite:e.data??{},json:!0,reportJunit:_.reportJunit});j&&j(),0!==t&&process.exit(t);return}eT({success:!0,data:e.data??{}}),j&&j();return}if("snapshot"===A){process.stdout.write(eO(e.data??{},{raw:_.snapshotRaw,flatten:_.snapshotInteractiveOnly})),j&&j();return}if("test"===A){let t=t1({suite:e.data??{},verbose:_.verbose,reportJunit:_.reportJunit});j&&j(),0!==t&&process.exit(t);return}if("diff"===A&&"snapshot"===E[0]){process.stdout.write(function(e){var t,r,s,a;let o=!0===e.baselineInitialized,i=e.summary??{},n=eR(i.additions),l=eR(i.removals),p=eR(i.unchanged),d=eF(),c=eC(e),m=c.length>0?`${c.join("\n")}
|
|
66
|
+
`:"";if(o)return`${m}Baseline initialized (${p} lines).
|
|
67
|
+
`;let f=(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 s of t){let t=Math.max(0,s-1),a=Math.min(e.length-1,s+1);for(let e=t;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(e.lines)?e.lines:[]).map(e=>{var t,r,s,a;let o="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=o.startsWith(" ")?`+${o}`:`+ ${o}`;return d?(t=e,r="green",u(r,t)):e}if("removed"===e.kind){let e=o.startsWith(" ")?`-${o}`:`- ${o}`;return d?(s=e,u("red",s)):e}return d?(a=o,u("dim",a)):o}),h=f.length>0?`${f.join("\n")}
|
|
68
|
+
`:"";if(!d)return`${m}${h}${n} additions, ${l} removals, ${p} unchanged
|
|
69
|
+
`;let g=`${(t=String(n),r="green",u(r,t))} additions, ${(s=String(l),u("red",s))} removals, ${(a=String(p),u("dim",a))} unchanged`;return`${m}${h}${g}
|
|
70
|
+
`}(e.data??{})),j&&j();return}if("get"===A){let t=E[0];if("text"===t){let t=e.data?.text??"";process.stdout.write(`${t}
|
|
71
|
+
`),j&&j();return}if("attrs"===t){let t=e.data?.node??{};process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
72
|
+
`),j&&j();return}}if("find"===A){let t=e.data;if("string"==typeof t?.text){process.stdout.write(`${t.text}
|
|
73
|
+
`),j&&j();return}if("boolean"==typeof t?.found){process.stdout.write(`Found: ${t.found}
|
|
74
|
+
`),j&&j();return}if(t?.node){process.stdout.write(`${JSON.stringify(t.node,null,2)}
|
|
75
|
+
`),j&&j();return}}if("is"===A){let t=e.data?.predicate??"assertion";process.stdout.write(`Passed: is ${t}
|
|
76
|
+
`),j&&j();return}if("boot"===A){let t=e.data?.platform??"unknown",r=e.data?.device??e.data?.id??"unknown";process.stdout.write(`Boot ready: ${r} (${t})
|
|
77
|
+
`),j&&j();return}if("ensure-simulator"===A){let t=e.data,r="string"==typeof t?.udid?t.udid:"unknown",s="string"==typeof t?.device?t.device:"unknown",a="string"==typeof t?.runtime?t.runtime:"",o=t?.created===!0,i=t?.booted===!0;process.stdout.write(`${o?"Created":"Reused"}: ${s} ${r}${i?" (booted)":""}
|
|
78
|
+
`),a&&process.stdout.write(`Runtime: ${a}
|
|
79
|
+
`),j&&j();return}if("screenshot"===A){let t="string"==typeof e.data?.path?e.data.path:"";t&&process.stdout.write(`${t}
|
|
80
|
+
`),j&&j();return}if("record"===A){let t=e.data,r="string"==typeof t?.outPath?t.outPath:"";r&&process.stdout.write(`${r}
|
|
81
|
+
`),j&&j();return}if("logs"===A){let t=e.data,r="string"==typeof t?.path?t.path:"";if(r){process.stdout.write(`${r}
|
|
82
|
+
`);let e="boolean"==typeof t?.active?t.active:void 0,s="string"==typeof t?.state?t.state:void 0,a="string"==typeof t?.backend?t.backend:void 0,o="number"==typeof t?.sizeBytes?t.sizeBytes:void 0,i=t?.started===!0,n=t?.stopped===!0,l=t?.marked===!0,u=t?.cleared===!0,p=t?.restarted===!0,d="number"==typeof t?.removedRotatedFiles?t.removedRotatedFiles:void 0;if(!_.json&&(void 0!==e||s||a||void 0!==o)){let t=[void 0!==e?`active=${e}`:"",s?`state=${s}`:"",a?`backend=${a}`:"",void 0!==o?`sizeBytes=${o}`:""].filter(Boolean).join(" ");t&&process.stderr.write(`${t}
|
|
83
|
+
`)}if(!_.json&&(i||n||l||u||p||void 0!==d)){let e=[i?"started=true":"",n?"stopped=true":"",l?"marked=true":"",u?"cleared=true":"",p?"restarted=true":"",void 0!==d?`removedRotatedFiles=${d}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
84
|
+
`)}if(t?.hint&&!_.json&&process.stderr.write(`${t.hint}
|
|
85
|
+
`),Array.isArray(t?.notes)&&!_.json)for(let e of t.notes)"string"==typeof e&&e.length>0&&process.stderr.write(`${e}
|
|
86
|
+
`)}j&&j();return}if("clipboard"===A){let t=e.data,r=(E[0]??("string"==typeof t?.action?t.action:"")).toLowerCase();if("read"===r){let e="string"==typeof t?.text?t.text:"";process.stdout.write(`${e}
|
|
87
|
+
`),j&&j();return}if("write"===r){process.stdout.write("Clipboard updated\n"),j&&j();return}}if("network"===A){let t=e.data,r="string"==typeof t?.path?t.path:"";r&&process.stdout.write(`${r}
|
|
88
|
+
`);let s=Array.isArray(t?.entries)?t.entries:[];if(0===s.length)process.stdout.write("No recent HTTP(s) entries found.\n");else for(let e of s){let t="string"==typeof e.method?e.method:"HTTP",r="string"==typeof e.url?e.url:"<unknown-url>",s="number"==typeof e.status?` status=${e.status}`:"",a="string"==typeof e.timestamp?`${e.timestamp} `:"",o="number"==typeof e.durationMs?` durationMs=${e.durationMs}`:"";process.stdout.write(`${a}${t} ${r}${s}${o}
|
|
85
89
|
`),"string"==typeof e.headers&&process.stdout.write(` headers: ${e.headers}
|
|
86
90
|
`),"string"==typeof e.requestBody&&process.stdout.write(` request: ${e.requestBody}
|
|
87
91
|
`),"string"==typeof e.responseBody&&process.stdout.write(` response: ${e.responseBody}
|
|
88
|
-
`)}let
|
|
92
|
+
`)}let a="boolean"==typeof t?.active?t.active:void 0,o="string"==typeof t?.state?t.state:void 0,i="string"==typeof t?.backend?t.backend:void 0,n="number"==typeof t?.scannedLines?t.scannedLines:void 0,l="number"==typeof t?.matchedLines?t.matchedLines:void 0,u="string"==typeof t?.include?t.include:void 0,p=[void 0!==a?`active=${a}`:"",o?`state=${o}`:"",i?`backend=${i}`:"",u?`include=${u}`:"",void 0!==n?`scannedLines=${n}`:"",void 0!==l?`matchedLines=${l}`:""].filter(Boolean).join(" ");if(p&&process.stderr.write(`${p}
|
|
89
93
|
`),Array.isArray(t?.notes))for(let e of t.notes)"string"==typeof e&&e.length>0&&process.stderr.write(`${e}
|
|
90
|
-
`);
|
|
91
|
-
`),
|
|
92
|
-
`),
|
|
93
|
-
`),
|
|
94
|
+
`);j&&j();return}if("click"===A||"press"===A){let t=e.data?.ref??"",r=e.data?.x,s=e.data?.y;if(t&&"number"==typeof r&&"number"==typeof s){process.stdout.write(`Tapped @${t} (${r}, ${s})
|
|
95
|
+
`),j&&j();return}}if(e.data&&"object"==typeof e.data){let t=e.data;if("devices"===A){let e=(Array.isArray(t.devices)?t.devices:[]).map(e=>{let t=e?.name??e?.id??"unknown",r=e?.platform??"unknown",s=e?.kind?` ${e.kind}`:"",a=e?.target?` target=${e.target}`:"",o="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${r}${s}${a})${o}`});process.stdout.write(`${e.join("\n")}
|
|
96
|
+
`),j&&j();return}if("apps"===A){let e=(Array.isArray(t.apps)?t.apps:[]).map(e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e.bundleId??e.package,r=e.name??e.label;return r&&t?`${r} (${t})`:t?String(t):JSON.stringify(e)}return String(e)});process.stdout.write(`${e.join("\n")}
|
|
97
|
+
`),j&&j();return}if("appstate"===A){let e=t?.platform,r=t?.appBundleId,s=t?.appName,a=t?.source,o=t?.package,i=t?.activity;if("ios"===e){process.stdout.write(`Foreground app: ${s??r??"unknown"}
|
|
94
98
|
`),r&&process.stdout.write(`Bundle: ${r}
|
|
95
|
-
`),
|
|
96
|
-
`),
|
|
99
|
+
`),a&&process.stdout.write(`Source: ${a}
|
|
100
|
+
`),j&&j();return}if("android"===e){process.stdout.write(`Foreground app: ${o??"unknown"}
|
|
97
101
|
`),i&&process.stdout.write(`Activity: ${i}
|
|
98
|
-
`),
|
|
99
|
-
`),
|
|
100
|
-
`),
|
|
102
|
+
`),j&&j();return}}if("perf"===A){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
103
|
+
`),j&&j();return}let r=M(t);if(r){process.stdout.write(`${r}
|
|
104
|
+
`),j&&j();return}}j&&j();return}throw new T(e.error.code,e.error.message,{...e.error.details??{},hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath})}catch(r){let e=N(r),t=U(e,{diagnosticId:G().diagnosticId,logPath:X({force:!0})??void 0});if("close"===A&&"COMMAND_FAILED"===(b=e).code&&(b.details?.kind==="daemon_startup_failed"||b.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof b.details?.infoPath||"string"==typeof b.details?.lockPath))){_.json&&eT({success:!0,data:{closed:"session",source:"no-daemon"}}),j&&j();return}if(_.json)eT({success:!1,error:t});else if(eM(t,{showDetails:_.verbose}),_.verbose)try{let e=R.logPath;if(h.existsSync(e)){let t=h.readFileSync(e,"utf8").split("\n"),r=t.slice(Math.max(0,t.length-200)).join("\n");r.trim().length>0&&process.stderr.write(`
|
|
101
105
|
[daemon log]
|
|
102
106
|
${r}
|
|
103
|
-
`)}}catch{}
|
|
107
|
+
`)}}catch{}j&&j(),process.exit(1)}})}d(process.argv[1]??"").href===import.meta.url&&rp(process.argv.slice(2)).catch(e=>{eM(U(N(e)),{showDetails:!0}),process.exit(1)}),rp(process.argv.slice(2));
|