agent-device 0.13.3 → 0.14.1
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 +68 -63
- package/android-snapshot-helper/README.md +75 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.14.1.apk +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.14.1.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.14.1.manifest.json +17 -0
- package/dist/src/221.js +4 -0
- package/dist/src/3918.js +29 -29
- package/dist/src/8161.js +3 -3
- package/dist/src/8656.js +1 -1
- package/dist/src/9152.js +1 -1
- package/dist/src/9542.js +2 -2
- package/dist/src/9818.js +1 -1
- package/dist/src/989.js +1 -1
- package/dist/src/android-snapshot-helper.d.ts +182 -0
- package/dist/src/android-snapshot-helper.js +1 -0
- package/dist/src/index.d.ts +19 -0
- package/dist/src/internal/bin.js +413 -69
- package/dist/src/internal/daemon.js +22 -20
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +26 -2
- package/package.json +29 -9
- package/skills/agent-device/SKILL.md +20 -62
- package/skills/dogfood/SKILL.md +9 -168
- package/skills/react-devtools/SKILL.md +15 -31
- package/skills/agent-device/references/bootstrap-install.md +0 -244
- package/skills/agent-device/references/coordinate-system.md +0 -28
- package/skills/agent-device/references/debugging.md +0 -138
- package/skills/agent-device/references/exploration.md +0 -362
- package/skills/agent-device/references/macos-desktop.md +0 -88
- package/skills/agent-device/references/remote-tenancy.md +0 -188
- package/skills/agent-device/references/verification.md +0 -134
- package/skills/dogfood/references/issue-taxonomy.md +0 -83
- package/skills/dogfood/templates/dogfood-report-template.md +0 -52
- package/skills/react-devtools/references/commands.md +0 -91
- package/skills/react-devtools/references/profiling.md +0 -74
package/dist/src/internal/bin.js
CHANGED
|
@@ -1,105 +1,449 @@
|
|
|
1
|
-
let e,t,s,r,o,n,a;import i from"node:path";import{styleText as l}from"node:util";import{pathToFileURL as c}from"node:url";import u from"node:fs";import p from"node:crypto";import{buildMobileSnapshotPresentation as d,SESSION_SURFACES as m,formatSnapshotLine as f,SETTINGS_USAGE_OVERRIDE as g,parseBatchStepsJson as h,createAgentDevice as y,isEnvTruthy as w,displayNodeLabel as v,localCommandPolicy as b,parseDeviceRotation as I,parseWaitArgs as D,buildSnapshotDisplayLines as A}from"../3918.js";import{resolveRemoteConfigProfile as k,resolveRemoteConfigPath as S,REMOTE_CONFIG_FIELD_SPECS as $,parseSourceValue as x,buildPrimaryEnvVarName as L}from"../remote-config.js";import{asAppError as N,normalizeError as C,AppError as _}from"../9152.js";import{ensureCompanionTunnel as R,stopCompanionTunnel as E}from"../1974.js";import{REACT_DEVTOOLS_COMPANION_RUN_ARG as O}from"../2301.js";import{createRequestId as P,serializeSessionListEntry as T,serializeSnapshotResult as U,serializeCloseResult as M,readVersion as F,getDiagnosticsMeta as B,emitDiagnostic as V,serializeOpenResult as j,serializeDeployResult as G,readCommandMessage as H,resolveDaemonPaths as q,withDiagnosticsScope as K,flushDiagnosticsToSessionFile as J,serializeEnsureSimulatorResult as z,serializeInstallFromSourceResult as W,serializeDevice as Y}from"../8161.js";import{stopMetroTunnel as Z}from"../metro.js";import{runCmdStreaming as X,runCmd as Q}from"../9818.js";import{resolveUserPath as ee,expandUserHomePath as et}from"../3267.js";import{createLocalArtifactAdapter as es}from"../io.js";import{createAgentDeviceClient as er,CLIENT_COMMANDS as eo,sendToDaemon as en}from"../9542.js";import{splitSelectorFromArgs as ea}from"../940.js";import{maybeRunUpgradeNotifier as ei}from"../113.js";function el(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}let ec=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],eu=["snapshotDepth","snapshotScope","snapshotRaw"],ep=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"leaseBackend",names:["--lease-backend"],type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"],usageLabel:"--lease-backend ios-simulator|ios-instance|android-instance",usageDescription:"Lease backend for remote tenant connection admission"},{key:"force",names:["--force"],type:"boolean",usageLabel:"--force",usageDescription:"Force connection state replacement when reconnecting"},{key:"noLogin",names:["--no-login"],type:"boolean",usageLabel:"--no-login",usageDescription:"Connect: fail instead of starting implicit cloud login"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","apple"],usageLabel:"--platform ios|macos|android|linux|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:m,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 for direct bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional bridge origin for remote 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:"githubActionsArtifact",names:["--github-actions-artifact"],type:"string",usageLabel:"--github-actions-artifact <owner/repo:artifact>",usageDescription:"install-from-source: GitHub Actions artifact resolved by a remote daemon"},{key:"installSource",names:[],type:"string"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"quality",names:["--quality"],type:"int",min:5,max:10,usageLabel:"--quality <5-10>",usageDescription:"Record: scale recording resolution from 5 (50%) through 10 (native resolution)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"replayEnv",names:["-e","--env"],type:"string",multiple:!0,usageLabel:"-e KEY=VALUE, --env KEY=VALUE",usageDescription:"Replay/Test: inject or override a ${KEY} variable for the script (repeatable)"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Test: maximum wall-clock time per script attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG; diff screenshot: also write a separate current-screen overlay guide"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"screenshotMaxSize",names:["--max-size"],type:"int",min:1,usageLabel:"--max-size <px>",usageDescription:"Screenshot: downscale so the longest edge is at most <px>"},{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)"}],ed=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","leaseBackend","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),em={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},connect:{usageOverride:"connect --remote-config <path> [--tenant <id>] [--run-id <id>] [--lease-backend <backend>] [--force] [--no-login]",helpDescription:"Connect to a remote daemon, authenticate when needed, and save remote session state",summary:"Connect to remote daemon",positionalArgs:[],allowedFlags:["force","noLogin","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps","launchUrl"],skipCapabilityCheck:!0},disconnect:{helpDescription:"Disconnect remote daemon state, stop owned Metro companion, and release lease",summary:"Disconnect remote daemon",positionalArgs:[],allowedFlags:["shutdown"],skipCapabilityCheck:!0},connection:{usageOverride:"connection status",listUsageOverride:"connection status",helpDescription:"Inspect active remote connection state",summary:"Inspect remote connection",positionalArgs:["status"],allowedFlags:[],skipCapabilityCheck:!0},auth:{usageOverride:"auth status|login|logout",listUsageOverride:"auth status|login|logout",helpDescription:"Manage cloud CLI authentication",summary:"Manage cloud authentication",positionalArgs:["status|login|logout"],allowedFlags:[],skipCapabilityCheck:!0},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{usageOverride:"install-from-source <url> | install-from-source --github-actions-artifact <owner/repo:artifact>",listUsageOverride:"install-from-source <url> | install-from-source --github-actions-artifact",helpDescription:"Install app from a URL or remote-resolved source",summary:"Install app from a source",positionalArgs:["url?"],allowedFlags:["header","githubActionsArtifact","installSource","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",...ec]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [current.png] [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind","current?"],allowedFlags:[...ec,"baseline","threshold","out","overlayRefs"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare (--public-base-url <url> | --proxy-base-url <url>) [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]\n agent-device metro reload [--metro-host <host>] [--metro-port <port>] [--bundle-url <url>]",listUsageOverride:"metro prepare --public-base-url <url> | --proxy-base-url <url>; metro reload",helpDescription:"Prepare a local Metro runtime or ask Metro to reload connected React Native apps",summary:"Prepare Metro or reload apps",positionalArgs:["prepare|reload"],allowedFlags:["metroHost","metroPort","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps","bundleUrl"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss the device keyboard",summary:"Inspect or dismiss the device keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics",summary:"Show performance metrics",positionalArgs:[],allowedFlags:[]},"react-devtools":{usageOverride:"react-devtools [...args]",listUsageOverride:"react-devtools [...args]",helpDescription:"Run pinned agent-react-devtools commands for React Native component trees, props/state/hooks, and render profiling",summary:"Inspect and profile React Native component trees",positionalArgs:["args?"],allowsExtraPositionals:!0,allowedFlags:[],skipCapabilityCheck:!0},back:{usageOverride:"back [--in-app|--system]",helpDescription:"Navigate back with explicit app or system semantics",summary:"Go back",positionalArgs:[],allowedFlags:["backMode"]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},rotate:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",summary:"Rotate device orientation",positionalArgs:["orientation"],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...eu]},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",...eu]},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:[...eu]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate","replayEnv"],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","replayEnv","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",...eu]},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:[...eu,"delayMs"]},scroll:{usageOverride:"scroll <direction> [amount] [--pixels <n>]",helpDescription:"Scroll in direction (relative amount or explicit pixels)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:["pixels"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, --max-size to downscale, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen","screenshotMaxSize"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--quality <5-10>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","quality","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...eu]},settings:{usageOverride:g,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, animation scales, 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|animations 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}},ef=new Map,eg=new Map;for(let e of ep){for(let t of e.names)ef.set(t,e);let t=eg.get(e.key);t?t.push(e):eg.set(e.key,[e])}function eh(e){if(e)return em[e]}function ey(){return Object.keys(em)}function ew(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}let ev=(e=`agent-device <command> [args] [--json]
|
|
1
|
+
let e,t,s,o,r,a,n,i;import l from"node:path";import{styleText as c}from"node:util";import{pathToFileURL as p}from"node:url";import d from"node:fs";import u from"node:crypto";import{buildMobileSnapshotPresentation as m,SESSION_SURFACES as f,formatSnapshotLine as g,SETTINGS_USAGE_OVERRIDE as h,parseBatchStepsJson as v,createAgentDevice as y,isEnvTruthy as w,displayNodeLabel as b,localCommandPolicy as k,parseDeviceRotation as I,parseWaitArgs as A,buildSnapshotDisplayLines as D}from"../3918.js";import{resolveRemoteConfigProfile as S,resolveRemoteConfigPath as x,REMOTE_CONFIG_FIELD_SPECS as $,parseSourceValue as L,buildPrimaryEnvVarName as N}from"../remote-config.js";import{asAppError as R,normalizeError as C,AppError as _}from"../9152.js";import{ensureCompanionTunnel as E,stopCompanionTunnel as O}from"../1974.js";import{REACT_DEVTOOLS_COMPANION_RUN_ARG as U}from"../2301.js";import{createRequestId as P,serializeSessionListEntry as T,serializeSnapshotResult as M,serializeCloseResult as F,readVersion as B,getDiagnosticsMeta as j,emitDiagnostic as V,serializeOpenResult as G,serializeDeployResult as q,readCommandMessage as H,resolveDaemonPaths as K,withDiagnosticsScope as J,flushDiagnosticsToSessionFile as z,serializeEnsureSimulatorResult as W,serializeInstallFromSourceResult as Y,serializeDevice as Z}from"../8161.js";import{stopMetroTunnel as X}from"../metro.js";import{runCmdStreaming as Q,runCmd as ee}from"../9818.js";import{resolveUserPath as et,expandUserHomePath as es}from"../3267.js";import{createLocalArtifactAdapter as eo}from"../io.js";import{createAgentDeviceClient as er,CLIENT_COMMANDS as ea,sendToDaemon as en}from"../9542.js";import{splitSelectorFromArgs as ei}from"../940.js";import{maybeRunUpgradeNotifier as el}from"../113.js";function ec(e,t){for(let[s,o]of Object.entries(t))void 0!==o&&(e[s]=o);return e}let ep=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],ed=["snapshotDepth","snapshotScope","snapshotRaw"],eu={workflow:{summary:"Normal agent-device bootstrap, exploration, and validation loop",body:`agent-device help workflow
|
|
2
|
+
|
|
3
|
+
Version-matched operating guide for normal agent-device work.
|
|
4
|
+
|
|
5
|
+
Core loop:
|
|
6
|
+
devices/apps -> open -> snapshot or snapshot -i -> get/is/find/wait or press/fill/scroll/back -> verify -> close
|
|
7
|
+
|
|
8
|
+
Command shape:
|
|
9
|
+
Plans should use agent-device commands, not raw platform tools, pseudo commands, package-manager aliases, or helper prose.
|
|
10
|
+
Put subcommand first, then positionals, then flags:
|
|
11
|
+
agent-device open com.example.app --session checkout --platform android --relaunch
|
|
12
|
+
agent-device record start ./checkout.mp4 --session checkout
|
|
13
|
+
Snapshot refs look like @e12. After snapshot -i, use the exact @eN ref from that output.
|
|
14
|
+
If the exact ref is not known yet, first output snapshot -i, then use a concrete example shape like press @e12 in the next command; do not write @<ref>, @ref, @Label_Name, or @eN placeholders.
|
|
15
|
+
Close means agent-device close. App-owned back means back; system back means back --system.
|
|
16
|
+
Taps are press or click. Gestures are direct commands: swipe, longpress, pinch.
|
|
17
|
+
|
|
18
|
+
Bootstrap:
|
|
19
|
+
agent-device devices --platform ios
|
|
20
|
+
agent-device apps --platform android
|
|
21
|
+
agent-device open MyApp --platform ios --device "iPhone 17 Pro"
|
|
22
|
+
agent-device open <discovered-app-id> --session checkout --platform android
|
|
23
|
+
agent-device install com.example.app ./dist/app.apk --platform android
|
|
24
|
+
agent-device reinstall com.example.app ./build/MyApp.app --platform ios
|
|
25
|
+
agent-device install-from-source --github-actions-artifact org/repo:app-debug --platform android
|
|
26
|
+
agent-device open com.example.app --platform android --relaunch
|
|
27
|
+
If app id is unknown, plan devices, apps, then open <discovered-app-id>. Discovery is not enough when the task asks to open/start the app.
|
|
28
|
+
Install arguments are app/package id then artifact path. If the task says install, use install; use reinstall only when explicitly requested. Fresh runtime state is open --relaunch after install.
|
|
29
|
+
Do not open artifact paths or invent package ids. If apps lookup misses the target and no URL/artifact is provided, ask or stop.
|
|
30
|
+
|
|
31
|
+
Snapshots and refs:
|
|
32
|
+
snapshot reads visible state. snapshot -i gets current interactive refs.
|
|
33
|
+
Snapshot legend:
|
|
34
|
+
@e12 [button] label="Add to cart" id="add-cart" enabled hittable -> press @e12 or press 'id="add-cart"'.
|
|
35
|
+
@e13 [textinput] label="Notes" preview="Leave at side..." truncated -> snapshot -s @e13 before reading.
|
|
36
|
+
[off-screen below] 4 items: "Privacy", "About" -> scroll down, then snapshot -i; those are hints, not refs.
|
|
37
|
+
Re-snapshot after navigation, submit, modal/list/reload/dynamic changes.
|
|
38
|
+
Off-screen summaries are scroll hints; use scroll, not swipe, then snapshot -i.
|
|
39
|
+
Missing target in a long list: use a short manual scroll + snapshot loop with a max attempt count; do not rely on unbounded scrollintoview.
|
|
40
|
+
Truncated text/input previews: do not use get text first; expand with snapshot -s @ref (for example snapshot -s @e7), then read the scoped output.
|
|
41
|
+
Rare iOS accessibility gaps: if a row ref is shown disabled/hittable:false and press @ref reports success but no UI change, or a horizontal tab/filter bar is collapsed into one composite/seekbar with no child refs, run agent-device snapshot -i -c --json to read rects, compute the target center, press x y, then diff snapshot -i. Coordinates are fallback-only; document why you used them.
|
|
42
|
+
|
|
43
|
+
Selectors:
|
|
44
|
+
Use selectors as positional targets: id="field-email" or label="Allow".
|
|
45
|
+
Do not use CSS selectors, pseudo refs, --selector, --text, or raw x/y when refs/selectors exist.
|
|
46
|
+
agent-device fill 'id="catalog-search"' "tart" --delay-ms 80
|
|
47
|
+
agent-device press 'id="submit-order"'
|
|
48
|
+
agent-device is visible 'label="Online"'
|
|
49
|
+
agent-device get text 'id="quantity-value"'
|
|
50
|
+
|
|
51
|
+
Text entry:
|
|
52
|
+
fill replaces; type appends to focused field.
|
|
53
|
+
agent-device fill @e5 "qa@example.com"
|
|
54
|
+
agent-device fill 'id="field-email"' "qa@example.com"
|
|
55
|
+
agent-device press 'id="product-note"'
|
|
56
|
+
agent-device type "Handle with care" --delay-ms 80
|
|
57
|
+
Empty replacement is not a supported clear-field command: do not plan fill <target> "" or fill <target> ''. Prefer a visible clear/reset control; if the app exposes none, report the tool gap instead of inventing a clear command.
|
|
58
|
+
Debounced field with no result selector: agent-device wait 1000. Keyboard read-only: keyboard status/get. Blocked control: try keyboard dismiss when supported.
|
|
59
|
+
On iOS, prefer keyboard dismiss before manually pressing visible Done; the runner can use safe native keyboard controls and still reports unsupported layouts explicitly. If it returns UNSUPPORTED_OPERATION, prefer a visible app dismiss control, or use back --system only when system navigation is an acceptable side effect.
|
|
60
|
+
Search-as-you-type fields on iOS can drop characters when driven too fast; use --delay-ms on fill/type before trying clipboard paste.
|
|
61
|
+
iOS Allow Paste prompt cannot be exercised under XCUITest. To test paste-driven app behavior, prefill first with agent-device clipboard write "some text"; test the system prompt manually.
|
|
62
|
+
Android non-ASCII can fail on some system images. Try fill/type normally; agent-device uses safer fallbacks. If the shell reports unsupported non-ASCII input, configure a trusted ADB keyboard IME outside the command plan and restore the previous IME afterward.
|
|
63
|
+
|
|
64
|
+
Session ordering:
|
|
65
|
+
Stateful commands against one --session must run serially. Do not run open/press/fill/type/scroll/back/alert/replay/batch/close commands in parallel against the same session.
|
|
66
|
+
It is fine to parallelize independent read-only collection or commands that use different sessions/devices.
|
|
67
|
+
|
|
68
|
+
Read-only and waits:
|
|
69
|
+
Read-only visible/state question: use snapshot/get/is/find.
|
|
70
|
+
agent-device snapshot
|
|
71
|
+
agent-device get text 'id="product-title"'
|
|
72
|
+
agent-device get attrs @e4
|
|
73
|
+
agent-device is visible 'label="Online"'
|
|
74
|
+
agent-device wait text "Refreshing metrics..." 3000
|
|
75
|
+
agent-device wait 'label="Ready"' 3000
|
|
76
|
+
agent-device find "Increment" press --json
|
|
77
|
+
For async/list text presence, prefer wait text over is visible when no interaction is needed.
|
|
78
|
+
Use snapshot -i only when refs are needed for an action or targeted query.
|
|
79
|
+
Ambiguous find: add --first or --last. If info is not visible/exposed, report that gap instead of typing/searching/navigating to reveal it.
|
|
80
|
+
|
|
81
|
+
Navigation and gestures:
|
|
82
|
+
Use scroll for lists; swipe for coordinate gestures/carousels.
|
|
83
|
+
If app-owned back is ambiguous or has just misrouted, prefer a visible nav/back button ref, tab-bar ref, or deep link over repeated back/system back.
|
|
84
|
+
Keep count/pause/pattern on one swipe; flags are --count, --pause-ms, --pattern ping-pong.
|
|
85
|
+
longpress duration and pinch scale/center are positional:
|
|
86
|
+
agent-device longpress 300 500 800
|
|
87
|
+
agent-device swipe 320 500 40 500 --count 8 --pause-ms 30 --pattern ping-pong
|
|
88
|
+
agent-device pinch 0.5 200 400
|
|
89
|
+
|
|
90
|
+
Validation and evidence:
|
|
91
|
+
Nearby mutation diff: agent-device diff snapshot -i.
|
|
92
|
+
Expected text/selector verification must include the exact text or selector via wait, is, get, or find; bare screenshots/snapshots are insufficient for named expectations.
|
|
93
|
+
Prefer provided testIDs/ids/selectors for verification; use visible text when no durable selector is provided.
|
|
94
|
+
If task says snapshot, use snapshot. If it asks visual evidence, use screenshot.
|
|
95
|
+
Icon/tappable visual proof: screenshot --overlay-refs. Flag is --overlay-refs.
|
|
96
|
+
Startup/CPU/memory: perf --json or metrics. Replay maintenance: replay -u ./flow.ad.
|
|
97
|
+
Recording: record start/stop. Tracing: trace start ./trace.log, trace stop ./trace.log. Paths are positional.
|
|
98
|
+
Stable known flow: batch ./steps.json, not workflow batch.
|
|
99
|
+
Inline batch JSON example:
|
|
100
|
+
agent-device batch --steps '[{"command":"open","positionals":["settings"],"flags":{}},{"command":"wait","positionals":["100"],"flags":{}}]'
|
|
101
|
+
Batch step keys are command, positionals, flags, and optional runtime. Never use args, step, text, or target as batch step fields.
|
|
102
|
+
Android animations: settings animations off/on, not animations disable/restore.
|
|
103
|
+
Debug logs: logs clear --restart, logs mark, reproduce, then logs path; do not split clear/restart into separate stop/start commands.
|
|
104
|
+
Network headers: network dump --include headers; do not write network log headers.
|
|
105
|
+
Remote config: connect --remote-config ./remote-config.json, open, snapshot, disconnect.
|
|
106
|
+
macOS menu bar: open ... --platform macos --surface menubar; snapshot -i --platform macos --surface menubar.
|
|
107
|
+
|
|
108
|
+
React Native dev loop:
|
|
109
|
+
JS-only change with Metro connected:
|
|
110
|
+
agent-device metro reload
|
|
111
|
+
agent-device find "Home"
|
|
112
|
+
Do not use agent-device reload. Use open --relaunch for native startup reset.
|
|
113
|
+
Warning/error overlays can obscure UI and intercept taps. If snapshot -i shows one, dismiss/close its visible control (for example Dismiss or Close) if it is not the task target, then diff snapshot -i or snapshot -i before tapping the real UI.
|
|
114
|
+
Expo Go is a host shell. Use a provided project URL instead of inventing a bundle id; if no URL is provided but a target/app name is provided, open that target and do not inspect project files to find one. On iOS, prefer host + URL when the host shell is known because direct URL open can report success while leaving the runner/shell focused; verify with snapshot -i after opening:
|
|
115
|
+
agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios
|
|
116
|
+
agent-device snapshot -i --platform ios
|
|
117
|
+
Direct iOS URL open remains valid when no host shell is known, but verify that the app UI loaded:
|
|
118
|
+
agent-device open exp://127.0.0.1:8081 --platform ios
|
|
119
|
+
Android uses the URL target directly; do not write open <app> <url> there:
|
|
120
|
+
agent-device open exp://127.0.0.1:8081 --platform android
|
|
121
|
+
If apps lookup misses the project but shows Expo Go/dev-client and a project URL is available, open the URL/host shell; if no URL is available, ask instead of inventing an app id.
|
|
122
|
+
Expo Dev Client/development builds: open the installed dev-client app id/name; if a dev-client URL is provided, open that URL next. For Metro setup use metro prepare --kind expo.
|
|
123
|
+
|
|
124
|
+
React DevTools minimum loop:
|
|
125
|
+
Keep the agent-device react-devtools prefix on every React DevTools command:
|
|
126
|
+
agent-device react-devtools status
|
|
127
|
+
agent-device react-devtools wait --connected
|
|
128
|
+
agent-device react-devtools profile start
|
|
129
|
+
interact with normal agent-device commands
|
|
130
|
+
agent-device react-devtools profile stop
|
|
131
|
+
agent-device react-devtools profile slow --limit 5
|
|
132
|
+
agent-device react-devtools profile rerenders --limit 5
|
|
133
|
+
|
|
134
|
+
Escalate:
|
|
135
|
+
help debugging logs, network, alerts, traces, flaky runtime failures
|
|
136
|
+
help react-devtools React Native performance, profiling, props/state/hooks, slow renders, rerenders
|
|
137
|
+
help remote remote/cloud config, tenant, lease, local service tunnels
|
|
138
|
+
help macos desktop, frontmost-app, menu bar surfaces
|
|
139
|
+
help dogfood exploratory QA report workflow`},debugging:{summary:"Targeted failure evidence without dumping stale context",body:`agent-device help debugging
|
|
140
|
+
|
|
141
|
+
Use this when behavior fails, hangs, times out, throws alerts, or needs runtime evidence.
|
|
142
|
+
|
|
143
|
+
Logs:
|
|
144
|
+
Keep log windows small. Prefer clear, mark, reproduce, then path.
|
|
145
|
+
agent-device logs clear --restart
|
|
146
|
+
agent-device logs mark "before diagnostics retry"
|
|
147
|
+
agent-device press 'id="load-diagnostics"'
|
|
148
|
+
agent-device logs path
|
|
149
|
+
Do not cat a full stale log into agent context. Open or grep only the relevant window when needed.
|
|
150
|
+
logs clear --restart is the compact command to clear old logs and start a fresh capture; do not split it into logs stop, logs clear, logs start.
|
|
151
|
+
|
|
152
|
+
Network:
|
|
153
|
+
Use network dump for recent session HTTP traffic parsed from app logs.
|
|
154
|
+
agent-device network dump --include headers
|
|
155
|
+
agent-device network dump 20 --include all
|
|
156
|
+
Use this instead of logs path when the question is request/response metadata.
|
|
157
|
+
network log is a supported alias, but network dump --include headers is the clearest plan form. Do not write network log headers.
|
|
158
|
+
|
|
159
|
+
Alerts:
|
|
160
|
+
Native alerts:
|
|
161
|
+
agent-device alert wait 3000
|
|
162
|
+
agent-device alert accept
|
|
163
|
+
agent-device alert dismiss
|
|
164
|
+
If alert accept says no alert but a permission sheet is visibly on screen, treat it as normal UI:
|
|
165
|
+
agent-device snapshot -i
|
|
166
|
+
agent-device press 'label="Allow"'
|
|
167
|
+
|
|
168
|
+
Diagnostics and traces:
|
|
169
|
+
Use --debug for CLI/daemon diagnostic ids and log paths.
|
|
170
|
+
Use trace for low-level session diagnostics around one repro:
|
|
171
|
+
agent-device trace start ./traces/diagnostics.trace
|
|
172
|
+
agent-device press 'id="load-diagnostics"'
|
|
173
|
+
agent-device trace stop ./traces/diagnostics.trace
|
|
174
|
+
The trace path is positional. Do not use --path for trace start or trace stop.
|
|
175
|
+
|
|
176
|
+
Stabilizers:
|
|
177
|
+
Android animation-sensitive flows:
|
|
178
|
+
agent-device settings animations off
|
|
179
|
+
agent-device snapshot
|
|
180
|
+
agent-device settings animations on
|
|
181
|
+
Re-enable settings you changed before finishing.
|
|
182
|
+
|
|
183
|
+
React Native internals:
|
|
184
|
+
If the question is about React Native performance, profiling, props, state, hooks, render causes, slow components, or rerenders, use help react-devtools instead of inferring from screenshots or logs.`},"react-devtools":{summary:"React Native performance, profiling, and component internals",body:`agent-device help react-devtools
|
|
185
|
+
|
|
186
|
+
Use this for React Native performance/profiling and internals that the accessibility tree cannot expose: components, props, state, hooks, ownership, slow renders, and rerenders.
|
|
187
|
+
|
|
188
|
+
Core commands:
|
|
189
|
+
agent-device react-devtools start
|
|
190
|
+
agent-device react-devtools stop
|
|
191
|
+
agent-device react-devtools status
|
|
192
|
+
agent-device react-devtools wait --connected
|
|
193
|
+
agent-device react-devtools wait --component <ComponentName>
|
|
194
|
+
agent-device react-devtools count
|
|
195
|
+
agent-device react-devtools get tree --depth 3
|
|
196
|
+
agent-device react-devtools find <ComponentName>
|
|
197
|
+
agent-device react-devtools find <ComponentName> --exact
|
|
198
|
+
agent-device react-devtools get component @c5
|
|
199
|
+
agent-device react-devtools errors
|
|
200
|
+
agent-device react-devtools profile start
|
|
201
|
+
agent-device react-devtools profile stop
|
|
202
|
+
agent-device react-devtools profile slow --limit 5
|
|
203
|
+
agent-device react-devtools profile rerenders --limit 5
|
|
204
|
+
agent-device react-devtools profile report @c5
|
|
205
|
+
agent-device react-devtools profile timeline --limit 20
|
|
206
|
+
agent-device react-devtools profile export profile.json
|
|
207
|
+
agent-device react-devtools profile diff before.json after.json --limit 10
|
|
208
|
+
|
|
209
|
+
Profiling loop:
|
|
210
|
+
1. Verify the app is connected: react-devtools status, then wait --connected if needed.
|
|
211
|
+
2. Start profiling immediately before the interaction.
|
|
212
|
+
3. Drive the interaction with normal agent-device commands.
|
|
213
|
+
4. Stop profiling.
|
|
214
|
+
5. Inspect slow components and rerenders.
|
|
215
|
+
6. Use profile report @cN for render causes and changed props/state/hooks; use get component @cN for current props/state/hooks.
|
|
216
|
+
|
|
217
|
+
Rules:
|
|
218
|
+
Start with get tree --depth 3 or find <name>; use find --exact when fuzzy results are noisy.
|
|
219
|
+
@c refs reset after reload/remount. After reload, wait --connected and inspect again.
|
|
220
|
+
Keep the profile window narrow; unrelated navigation makes render data noisy.
|
|
221
|
+
For cross-platform validation with explicit device selectors, prefer isolated --state-dir and restart react-devtools between platforms.
|
|
222
|
+
Remote Android runs normally through agent-device react-devtools; the CLI manages the needed local service tunnel. Expo support depends on the SDK's bundled React Native runtime.
|
|
223
|
+
|
|
224
|
+
Example:
|
|
225
|
+
agent-device react-devtools status
|
|
226
|
+
agent-device react-devtools wait --connected
|
|
227
|
+
agent-device react-devtools profile start
|
|
228
|
+
agent-device fill 'id="catalog-search"' "tart" --delay-ms 80
|
|
229
|
+
agent-device react-devtools profile stop
|
|
230
|
+
agent-device react-devtools profile slow --limit 5
|
|
231
|
+
agent-device react-devtools profile rerenders --limit 5
|
|
232
|
+
agent-device react-devtools profile report @c5
|
|
233
|
+
|
|
234
|
+
Use snapshot, screenshot, logs, network, and perf for device/app runtime evidence. Use react-devtools only when component internals or React rendering behavior matters.`},remote:{summary:"Remote config, tenant, lease, and remote host flow",body:`agent-device help remote
|
|
235
|
+
|
|
236
|
+
Use remote config when a profile owns daemon URL, auth, tenant, run, lease, device scope, and Metro hints. Do not restate those as individual flags unless overriding intentionally.
|
|
237
|
+
|
|
238
|
+
Normal flow:
|
|
239
|
+
agent-device connect --remote-config ./remote-config.json
|
|
240
|
+
agent-device open com.example.app
|
|
241
|
+
agent-device snapshot
|
|
242
|
+
agent-device disconnect
|
|
243
|
+
|
|
244
|
+
Script flow, per-command config:
|
|
245
|
+
agent-device open com.example.app --remote-config ./remote-config.json
|
|
246
|
+
agent-device snapshot --remote-config ./remote-config.json
|
|
247
|
+
agent-device disconnect --remote-config ./remote-config.json
|
|
248
|
+
|
|
249
|
+
Rules:
|
|
250
|
+
connect and disconnect are top-level commands. Do not write agent-device remote connect or agent-device remote disconnect.
|
|
251
|
+
Prefer --remote-config over --daemon-base-url, --tenant, --run-id, and --lease-id in ordinary remote flows.
|
|
252
|
+
For self-contained scripts, pass the same --remote-config to every operational command, including disconnect; a preceding connect is optional but not required.
|
|
253
|
+
For remote artifact installs, use install-from-source <url> or install-from-source --github-actions-artifact org/repo:artifact; do not download CI artifacts locally first.
|
|
254
|
+
After connect, let the active remote connection supply runtime hints.
|
|
255
|
+
For remote Android React DevTools, run agent-device react-devtools normally. The CLI opens the needed local service tunnel for the DevTools daemon and cleans it up when the command exits.
|
|
256
|
+
Use --debug when remote connection or transport errors need diagnostic ids and remote log hints.`},macos:{summary:"macOS desktop, frontmost-app, and menu bar surfaces",body:`agent-device help macos
|
|
257
|
+
|
|
258
|
+
Use macOS only when the task targets desktop apps, desktop surfaces, or menu bar extras.
|
|
259
|
+
|
|
260
|
+
Open and inspect:
|
|
261
|
+
agent-device open TextEdit --platform macos
|
|
262
|
+
agent-device snapshot -i --platform macos
|
|
263
|
+
|
|
264
|
+
Surfaces:
|
|
265
|
+
--surface app normal app session
|
|
266
|
+
--surface frontmost-app inspect whichever app is frontmost
|
|
267
|
+
--surface desktop desktop-wide surface
|
|
268
|
+
--surface menubar menu bar extras and menu bar-only apps
|
|
269
|
+
|
|
270
|
+
Menu bar app example:
|
|
271
|
+
agent-device open "Agent Device Tester Menu" --platform macos --surface menubar
|
|
272
|
+
agent-device snapshot -i --platform macos --surface menubar
|
|
273
|
+
|
|
274
|
+
Context menu example:
|
|
275
|
+
agent-device click @e66 --button secondary --platform macos
|
|
276
|
+
agent-device snapshot -i --platform macos
|
|
277
|
+
|
|
278
|
+
Rules:
|
|
279
|
+
Use open and snapshot -i for menu bar inspection. Do not output inspect as a command.
|
|
280
|
+
Context menus are not ambient UI: secondary-click a visible target, then re-snapshot and use the new menu-item refs.
|
|
281
|
+
Do not let iOS simulator-set scoping hide macOS desktop targets.
|
|
282
|
+
Prefer refs/selectors over raw coordinates.
|
|
283
|
+
macOS snapshot rects are window-space; use current refs or overlay refs instead of guessing coordinates.`},dogfood:{summary:"Exploratory QA workflow with reproducible evidence",body:`agent-device help dogfood
|
|
284
|
+
|
|
285
|
+
Use this when asked to dogfood, exploratory test, bug hunt, QA, or find issues in an app.
|
|
286
|
+
|
|
287
|
+
Goal:
|
|
288
|
+
Find user-visible issues from runtime behavior. Do not read app source or invent findings from code.
|
|
289
|
+
Produce a concise report with severity, repro commands, expected/actual behavior, and evidence paths.
|
|
290
|
+
|
|
291
|
+
Loop:
|
|
292
|
+
1. Identify target app/platform; ask only if missing.
|
|
293
|
+
2. Create output dirs and open a named session. If auth or OTP is required, sign in or ask the user for the code.
|
|
294
|
+
3. Capture baseline snapshot -i and screenshot.
|
|
295
|
+
4. Map top-level navigation, then exercise primary flows and edge states.
|
|
296
|
+
5. For each issue, capture evidence and write the finding immediately, then continue.
|
|
297
|
+
6. Close the session and reconcile the report summary.
|
|
298
|
+
Keep stateful commands serial within the same session. Parallel runs can pollute text fields, focus, alerts, and navigation state.
|
|
299
|
+
|
|
300
|
+
Coverage:
|
|
301
|
+
Navigation, forms, empty/error/loading states, offline or retry behavior, permissions, settings, accessibility labels, orientation/keyboard, and obvious performance stalls.
|
|
302
|
+
React Native warning/error overlays can be real findings or test blockers. Capture them, dismiss if unrelated, re-snapshot, and report them.
|
|
303
|
+
Expo Go/dev-client shells: use the provided exp:// or dev-client URL and record whether the shell, project load, or app UI is being tested. On iOS dogfood, prefer agent-device open "Expo Go" <url> when Expo Go is the known shell, then snapshot -i to confirm the project UI rather than the runner splash.
|
|
304
|
+
Categories: visual, functional, UX, content, performance, diagnostics, permissions, accessibility.
|
|
305
|
+
Severity: critical blocks a core flow/data/crashes; high breaks a major feature; medium has friction or workaround; low is polish.
|
|
306
|
+
|
|
307
|
+
Evidence commands:
|
|
308
|
+
mkdir -p ./dogfood-output/screenshots ./dogfood-output/videos ./dogfood-output/traces
|
|
309
|
+
agent-device --session qa open <app> --platform ios
|
|
310
|
+
agent-device --session qa snapshot -i
|
|
311
|
+
agent-device --session qa screenshot ./dogfood-output/screenshots/initial.png
|
|
312
|
+
agent-device --session qa screenshot ./dogfood-output/screenshots/issue-001.png --overlay-refs
|
|
313
|
+
agent-device --session qa logs clear --restart
|
|
314
|
+
agent-device --session qa logs mark "issue-001 repro"
|
|
315
|
+
agent-device --session qa logs path
|
|
316
|
+
agent-device --session qa record start ./dogfood-output/videos/issue-001.mp4
|
|
317
|
+
agent-device --session qa record stop
|
|
318
|
+
agent-device --session qa close
|
|
319
|
+
|
|
320
|
+
Evidence rules:
|
|
321
|
+
Interactive/behavioral issues need step screenshots and usually a repro video.
|
|
322
|
+
Static/on-load issues can use one screenshot; set repro video to N/A.
|
|
323
|
+
Use screenshot --overlay-refs when showing the tappable target or broken state helps repro.
|
|
324
|
+
|
|
325
|
+
Report shape:
|
|
326
|
+
./dogfood-output/report.md
|
|
327
|
+
Include date, platform, target app, session, scope, severity counts, and issues.
|
|
328
|
+
For each finding: ID, severity, category, title, affected flow/screen, repro commands, expected, actual, evidence files, notes.
|
|
329
|
+
Target 5-10 well-evidenced issues when available. If no issues are found, report coverage completed and residual risk instead of claiming the app is bug-free.
|
|
330
|
+
|
|
331
|
+
Rules:
|
|
332
|
+
Findings must come from observed runtime behavior, not source reads.
|
|
333
|
+
Re-snapshot after each mutation.
|
|
334
|
+
Keep commands in the report reproducible; use selectors or refs from fresh snapshots, not guessed coordinates.
|
|
335
|
+
Prefer refs for exploration and selectors for deterministic replay.
|
|
336
|
+
Use logs, network, screenshot --overlay-refs, trace, perf, or react-devtools only when they add evidence to a specific issue.
|
|
337
|
+
Never delete screenshots, videos, traces, or report artifacts during a session.
|
|
338
|
+
Escalate to help debugging or help react-devtools when runtime symptoms require those tools.`}},em=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"leaseBackend",names:["--lease-backend"],type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"],usageLabel:"--lease-backend ios-simulator|ios-instance|android-instance",usageDescription:"Lease backend for remote tenant connection admission"},{key:"force",names:["--force"],type:"boolean",usageLabel:"--force",usageDescription:"Force connection state replacement when reconnecting"},{key:"noLogin",names:["--no-login"],type:"boolean",usageLabel:"--no-login",usageDescription:"Connect: fail instead of starting implicit cloud login"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","apple"],usageLabel:"--platform ios|macos|android|linux|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:f,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 for direct bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional bridge origin for remote 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:"githubActionsArtifact",names:["--github-actions-artifact"],type:"string",usageLabel:"--github-actions-artifact <owner/repo:artifact>",usageDescription:"install-from-source: GitHub Actions artifact resolved by a remote daemon"},{key:"installSource",names:[],type:"string"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"quality",names:["--quality"],type:"int",min:5,max:10,usageLabel:"--quality <5-10>",usageDescription:"Record: scale recording resolution from 5 (50%) through 10 (native resolution)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"replayEnv",names:["-e","--env"],type:"string",multiple:!0,usageLabel:"-e KEY=VALUE, --env KEY=VALUE",usageDescription:"Replay/Test: inject or override a ${KEY} variable for the script (repeatable)"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Test: maximum wall-clock time per script attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG; diff screenshot: also write a separate current-screen overlay guide"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"screenshotMaxSize",names:["--max-size"],type:"int",min:1,usageLabel:"--max-size <px>",usageDescription:"Screenshot: downscale so the longest edge is at most <px>"},{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)"}],ef=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","leaseBackend","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),eg={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},connect:{usageOverride:"connect --remote-config <path> [--tenant <id>] [--run-id <id>] [--lease-backend <backend>] [--force] [--no-login]",helpDescription:"Connect to a remote daemon, authenticate when needed, and save remote session state. AGENT_DEVICE_CLOUD_BASE_URL is the bridge/control-plane API origin; use AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_... for CI/service-token automation.",summary:"Connect to remote daemon",positionalArgs:[],allowedFlags:["force","noLogin","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps","launchUrl"],skipCapabilityCheck:!0},disconnect:{helpDescription:"Disconnect remote daemon state, stop owned Metro companion, and release lease",summary:"Disconnect remote daemon",positionalArgs:[],allowedFlags:["shutdown"],skipCapabilityCheck:!0},connection:{usageOverride:"connection status",listUsageOverride:"connection status",helpDescription:"Inspect active remote connection state",summary:"Inspect remote connection",positionalArgs:["status"],allowedFlags:[],skipCapabilityCheck:!0},auth:{usageOverride:"auth status|login|logout",listUsageOverride:"auth status|login|logout",helpDescription:"Manage cloud CLI authentication",summary:"Manage cloud authentication",positionalArgs:["status|login|logout"],allowedFlags:[],skipCapabilityCheck:!0},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{usageOverride:"install-from-source <url> | install-from-source --github-actions-artifact <owner/repo:artifact>",listUsageOverride:"install-from-source <url> | install-from-source --github-actions-artifact",helpDescription:"Install app from a URL or remote-resolved source",summary:"Install app from a source",positionalArgs:["url?"],allowedFlags:["header","githubActionsArtifact","installSource","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{usageOverride:"snapshot [--diff] [-i] [-c] [-d <depth>] [-s <scope>] [--raw]",helpDescription:"Capture accessibility tree or diff against the previous session baseline",positionalArgs:[],allowedFlags:["snapshotDiff",...ep]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [current.png] [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind","current?"],allowedFlags:[...ep,"baseline","threshold","out","overlayRefs"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare (--public-base-url <url> | --proxy-base-url <url>) [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]\n agent-device metro reload [--metro-host <host>] [--metro-port <port>] [--bundle-url <url>]",listUsageOverride:"metro prepare --public-base-url <url> | --proxy-base-url <url>; metro reload",helpDescription:"Prepare a local Metro runtime or ask Metro to reload connected React Native apps",summary:"Prepare Metro or reload apps",positionalArgs:["prepare|reload"],allowedFlags:["metroHost","metroPort","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps","bundleUrl"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss the device keyboard",summary:"Inspect or dismiss the device keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics",summary:"Show performance metrics",positionalArgs:[],allowedFlags:[]},"react-devtools":{usageOverride:"react-devtools [...args]",listUsageOverride:"react-devtools [...args]",helpDescription:"Run pinned agent-react-devtools commands for React Native performance profiling, component trees, props/state/hooks, and render analysis",summary:"Profile React Native performance and component renders",positionalArgs:["args?"],allowsExtraPositionals:!0,allowedFlags:[],skipCapabilityCheck:!0},back:{usageOverride:"back [--in-app|--system]",helpDescription:"Navigate back with explicit app or system semantics",summary:"Go back",positionalArgs:[],allowedFlags:["backMode"]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},rotate:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",summary:"Rotate device orientation",positionalArgs:["orientation"],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...ed]},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",...ed]},get:{usageOverride:"get text|attrs <@ref|selector>",helpDescription:"Return exposed element text/attributes by ref or selector; use snapshot -s @ref for truncated previews",summary:"Get exposed text or attrs by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...ed]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate","replayEnv"],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","replayEnv","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",...ed]},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:[...ed,"delayMs"]},scroll:{usageOverride:"scroll <direction> [amount] [--pixels <n>]",helpDescription:"Scroll in direction (relative amount or explicit pixels)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:["pixels"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, --max-size to downscale, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen","screenshotMaxSize"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--quality <5-10>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","quality","hideTouches"]},trace:{usageOverride:"trace start <path> | trace stop <path>",listUsageOverride:"trace start <path> | trace stop <path>",helpDescription:"Start/stop trace log capture; when an artifact path is requested, pass the same positional path to start and stop",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...ed]},settings:{usageOverride:h,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, animation scales, 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|animations 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}},eh=new Map,ev=new Map;for(let e of em){for(let t of e.names)eh.set(t,e);let t=ev.get(e.key);t?t.push(e):ev.set(e.key,[e])}function ey(e){if(e)return eg[e]}function ew(){return Object.keys(eg)}function eb(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}let ek=(e=`agent-device <command> [args] [--json]
|
|
2
339
|
|
|
3
340
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
-
`,t=eD("Commands:",
|
|
341
|
+
`,t=eD("Commands:",ew().map(e=>{let t=eg[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 s=t.positionalArgs.map(s=>{var o,r,a;let n,i,l,c;return o=e,r=t,i=(n=(a=s).endsWith("?"))?a.slice(0,-1):a,c=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==r.usageOverride&&r.usageOverride.startsWith(`${o} ${i}`),n?l?`[${i}]`:c?i:`[${i}]`:c?i:`<${i}>`});return[e,...s].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),s=eA("Flags:",eI(ef)),o=eS("Agent Quickstart:",["Default loop: devices/apps -> open -> snapshot -i -> press/fill/get/is/wait/find -> verify -> close.",'Use selectors or refs as positional targets: id="submit", label="Allow", or @e12 from snapshot -i.',"Plain snapshot reads state; snapshot -i is required to refresh interactive refs.","Read-only visible/state question: use snapshot/get/is/find; use snapshot -i only when refs are needed.","Truncated text/input preview: expand first with snapshot -s @e12, not get text.","RN warning/error overlays can block taps: snapshot -i, dismiss/close, then diff snapshot -i.",'Expo Go/dev clients: use the provided URL when given; on iOS prefer open "Expo Go" <url> when the host shell is known.',"Install flows: install/install-from-source first, then open the installed id with --relaunch.",'Text: fill \'id="field-email"\' "qa@example.com" replaces; type appends after press.','Clearing text: do not use fill <target> ""; use a visible clear/reset control or report that clearing is unsupported.',"Run mutating commands serially against one session; parallelize only read-only commands or separate sessions.","Clipboard limits: iOS Allow Paste cannot be automated through XCUITest; prefill with clipboard write. Android non-ASCII should use fill/type, not raw adb input.","After mutation: diff snapshot -i. Off-screen hints: scroll, then snapshot -i.","Raw coordinates are fallback-only: use snapshot -i -c --json rects when iOS refs no-op or child refs are missing.",'Batch JSON steps use "command", "positionals", "flags"; never "args" or "step".',"Navigation: app-owned back uses back; system back uses back --system.","Verification commands must name the expected text/selector; bare screenshots/snapshots are not enough.","Debug evidence: logs clear --restart/mark/path; trace start ./path; trace stop ./path; network dump --include headers.","Use agent-device commands in final plans; raw platform tools, pseudo commands, and helper prose are wrong.","Full operating guide: agent-device help workflow. Exploratory QA: agent-device help dogfood."]),r=eD("Agent Workflows:",[{label:"help workflow",description:"Normal bootstrap, exploration, and validation loop"},{label:"help debugging",description:"Logs, network, alerts, diagnostics, and traces"},{label:"help react-devtools",description:"React Native performance, profiling, component tree, and renders"},{label:"help remote",description:"Remote/cloud config, tenants, leases, and local service tunnels"},{label:"help macos",description:"Desktop, frontmost-app, and menu bar surfaces"},{label:"help dogfood",description:"Exploratory QA report workflow"}]),a=eS("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),n=eD("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"},{label:"AGENT_DEVICE_DAEMON_AUTH_TOKEN",description:"Remote daemon service/API token"},{label:"AGENT_DEVICE_CLOUD_BASE_URL",description:"Bridge/control-plane API origin for cloud auth and /api-keys"}]),i=eS("Examples:",["agent-device open Settings --platform ios","agent-device open TextEdit --platform macos","agent-device snapshot -i","agent-device react-devtools get tree --depth 3",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"]),`${e}
|
|
5
342
|
${t}
|
|
6
343
|
|
|
7
344
|
${s}
|
|
8
345
|
|
|
346
|
+
${o}
|
|
347
|
+
|
|
9
348
|
${r}
|
|
10
349
|
|
|
11
|
-
${
|
|
350
|
+
${a}
|
|
12
351
|
|
|
13
352
|
${n}
|
|
14
353
|
|
|
15
|
-
${
|
|
16
|
-
`);function
|
|
17
|
-
(none)`;let s=Math.max(...t.map(e=>e.label.length))+2,
|
|
18
|
-
(none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let
|
|
19
|
-
`)}function
|
|
354
|
+
${i}
|
|
355
|
+
`);function eI(e){return em.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function eA(e,t){return eD(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function eD(e,t){if(0===t.length)return`${e}
|
|
356
|
+
(none)`;let s=Math.max(...t.map(e=>e.label.length))+2,o=[e];for(let e of t)o.push(` ${e.label.padEnd(s)}${e.description}`);return o.join("\n")}function eS(e,t){return 0===t.length?`${e}
|
|
357
|
+
(none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let ex=new Set(["config","remoteConfig","help","version","batchSteps","githubActionsArtifact"]),e$={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eL=function(){let e=new Map;for(let t of em){let s=e.get(t.key);s?s.push(t):e.set(t.key,[t])}let t=new Map;for(let e of ef)t.set(e,new Set(["*"]));for(let e of ew()){let s=ey(e);if(s)for(let o of s.allowedFlags){let s=t.get(o);s&&s.has("*")||(s?s.add(e):t.set(o,new Set([e])))}}return[...e.entries()].map(([e,s])=>({key:e,flagDefinitions:s,config:{enabled:!ex.has(e),key:e},env:{names:[N(e),...e$[e]??[]]},supportsCommand(s){let o=t.get(e);return!!o&&(!!o.has("*")||!!s&&o.has(s))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),eN=new Map(eL.map(e=>[e.key,e]));function eR(e,t){return eN.get(e)?.supportsCommand(t)??!1}function eC(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let s=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===s.type){let t=e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...s,setValue:void 0,enumValues:t}}return s}function e_(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function eE(e){return e.replace(/^-+/,"")}function eO(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?e_(e):[e,void 0];return void 0!==eh.get(t)}function eU(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function eP(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
358
|
+
`)}function eT(e,t={}){let s=e instanceof _?C(e):e;process.stderr.write(`Error (${s.code}): ${s.message}
|
|
20
359
|
`),s.hint&&process.stderr.write(`Hint: ${s.hint}
|
|
21
360
|
`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}
|
|
22
361
|
`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}
|
|
23
362
|
`),t.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}
|
|
24
|
-
`)}function
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
Runtime: ${s.runtime}`:`${e}: ${s.device} ${s.udid}${t}`}),!0},tg=async({positionals:e,flags:t,client:s})=>{let r=(e[0]??"").toLowerCase();if("reload"===r){let e=await s.metro.reload({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs});return tc(t,e,()=>`Reloaded React Native apps via ${e.reloadUrl}`),!0}if("prepare"!==r)throw new _("INVALID_ARGS","metro requires a subcommand: prepare or reload");if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new _("INVALID_ARGS","metro prepare requires --public-base-url <url> or --proxy-base-url <url>.");let o=await s.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,bridgeScope:t.tenant&&t.runId&&t.leaseId?{tenantId:t.tenant,runId:t.runId,leaseId:t.leaseId}:void 0,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile});return tc(t,o,()=>JSON.stringify(o,null,2)),!0},th=async({flags:e,client:t})=>{let s=await t.apps.list({...tl(e),appsFilter:e.appsFilter});return tc(e,{apps:s},()=>s.join("\n")),!0};function ty(e,t,s,r){var o;return"number"==typeof s||"string"==typeof(o=s)&&/^\d+$/.test(o.trim())?{kind:"github-actions-artifact",owner:e,repo:t,artifactId:function(e,t){let s="number"==typeof e?e:"string"==typeof e?Number(e):NaN;if(!Number.isInteger(s))throw new _("INVALID_ARGS",`${t} must be an integer.`);return s}(s,r)}:{kind:"github-actions-artifact",owner:e,repo:t,artifactName:tv(s,r)}}function tw(e,t){let s=e.indexOf("/");if(s<=0||s===e.length-1||-1!==e.indexOf("/",s+1))throw new _("INVALID_ARGS",`${t} must use owner/repo.`);let r={owner:e.slice(0,s).trim(),repo:e.slice(s+1).trim()};if(!r.owner||!r.repo)throw new _("INVALID_ARGS",`${t} must use owner/repo.`);return r}function tv(e,t){let s="string"==typeof e&&e.trim().length>0?e.trim():void 0;if(!s)throw new _("INVALID_ARGS",`${t} must be a non-empty string.`);return s}let tb=async({positionals:e,flags:t,client:s})=>{let r=G(await tA("install",e,t,s));return tu(t,r),!0},tI=async({positionals:e,flags:t,client:s})=>{let r=G(await tA("reinstall",e,t,s));return tu(t,r),!0},tD=async({positionals:e,flags:t,client:s})=>{let r=W(await tk(e,t,s));return tu(t,r),!0};async function tA(e,t,s,r){let o=t[0],n=t[1];if(!o||!n)throw new _("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let a={app:o,appPath:n,...tl(s)};return"install"===e?await r.apps.install(a):await r.apps.reinstall(a)}async function tk(e,t,s){let r=function(e,t){let s=e[0]?.trim();if(e.length>1)throw new _("INVALID_ARGS","install-from-source accepts either one <url> positional or --github-actions-artifact");let r=t.githubActionsArtifact?function(e,t="--github-actions-artifact"){let s=e.indexOf(":");if(s<=0||s===e.length-1)throw new _("INVALID_ARGS",`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:r,repo:o}=tw(e.slice(0,s),t);return ty(r,o,e.slice(s+1),`${t} artifact`)}(t.githubActionsArtifact):void 0,o=t.installSource;if(1!=+!!s+ +!!r+ +!!o)throw new _("INVALID_ARGS","install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource");return r||o||{kind:"url",url:s,headers:function(e){if(!e||0===e.length)return;let t={};for(let s of e){let e=s.indexOf(":");if(e<=0)throw new _("INVALID_ARGS",`Invalid --header value "${s}". Expected "name:value".`);let r=s.slice(0,e).trim(),o=s.slice(e+1).trim();if(!r)throw new _("INVALID_ARGS",`Invalid --header value "${s}". Header name cannot be empty.`);t[r]=o}return t}(t.header)}}(e,t);if("url"!==r.kind&&t.header&&t.header.length>0)throw new _("INVALID_ARGS","install-from-source --header is only supported for URL sources");return await s.apps.installFromSource({...tl(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:r})}let tS=async({positionals:e,flags:t,client:s})=>{let r=j(await s.apps.open({app:e[0],url:e[1],surface:t.surface,activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,...tl(t)}));return tu(t,r),!0},t$=async({positionals:e,flags:t,client:s})=>{let r=M(e[0]?await s.apps.close({app:e[0],shutdown:t.shutdown}):await s.sessions.close({shutdown:t.shutdown}));return tu(t,r),!0},tx=async({flags:e,client:t})=>{var s,r,o,n;if(!e.remoteConfig)throw new _("INVALID_ARGS","connect requires --remote-config <path>.");let a=e.tenant,i=e.runId;if(!a)throw new _("INVALID_ARGS","connect requires tenant in remote config or via --tenant <id>.");if(!i)throw new _("INVALID_ARGS","connect requires runId in remote config or via --run-id <id>.");if(!e.daemonBaseUrl)throw new _("INVALID_ARGS","connect requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.");let l=q(e.stateDir).baseDir,c=e.session?null:e2({stateDir:l}),u=e.session??c?.session??function(e){for(let t=0;t<8;t+=1){let t=`adc-${p.randomBytes(3).toString("hex")}`;if(!eW({stateDir:e,session:t}))return t}return`adc-${Date.now().toString(36)}-${p.randomBytes(2).toString("hex")}`}(l),d=k({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),m=eQ(d.resolvedPath),f=eZ(e),g=c?.session===u?c:eW({stateDir:l,session:u});if(g&&(s=g,r={flags:e,session:u,remoteConfigPath:d.resolvedPath,remoteConfigHash:m,desiredLeaseBackend:tr(e),daemon:f},s.remoteConfigPath!==r.remoteConfigPath||s.remoteConfigHash!==r.remoteConfigHash||s.session!==r.session||s.tenant!==r.flags.tenant||s.runId!==r.flags.runId||void 0!==r.desiredLeaseBackend&&s.leaseBackend!==r.desiredLeaseBackend||void 0!==r.flags.platform&&s.platform!==r.flags.platform||void 0!==r.flags.target&&s.target!==r.flags.target||(o=s.daemon,n=r.daemon,(o?.baseUrl??void 0)!==(n?.baseUrl??void 0)||(o?.transport??void 0)!==(n?.transport??void 0)||(o?.serverMode??void 0)!==(n?.serverMode??void 0)))&&!e.force)throw new _("INVALID_ARGS","A different remote connection is already active for this session. Re-run connect with --force to replace it.",{session:u,remoteConfig:g.remoteConfigPath});let h=new Date().toISOString(),y={version:1,session:u,remoteConfigPath:d.resolvedPath,remoteConfigHash:m,daemon:f,tenant:a,runId:i,leaseId:g&&!e.force?g.leaseId:void 0,leaseBackend:g&&!e.force?g.leaseBackend:tr(e),platform:e.platform??(g&&!e.force?g.platform:void 0),target:e.target??(g&&!e.force?g.target:void 0),runtime:g&&!e.force?g.runtime:void 0,metro:g&&!e.force?g.metro:void 0,connectedAt:g&&!e.force?g.connectedAt:h,updatedAt:h};eY({stateDir:l,state:y}),g&&e.force&&(await te(g.metro),await tt({stateDir:l,state:g}),await ts(t,g));let w=function(e,t){if(!t.runtime&&(to(e)||t_(t.remoteConfigPath)))return tC(t.remoteConfigPath)}(e,y);return tc(e,tR(y,w),()=>[`Connected remote session "${u}" tenant "${a}" run "${i}" ${y.leaseId?`lease ${y.leaseId}`:"lease pending"}`,w?.message].filter(e=>!!e).join("\n")),!0},tL=async({flags:e,client:t})=>{let s=e.session??"default",r=q(e.stateDir).baseDir,o=eW({stateDir:r,session:s})??(e.session?null:e2({stateDir:r}));if(!o)return tc(e,{connected:!1,session:s},()=>`No remote connection for "${s}".`),!0;let n=o.session;try{await t.sessions.close({shutdown:e.shutdown})}catch{}await te(o.metro),await tt({stateDir:r,state:o});let a=!1;if(o.leaseId)try{a=(await t.leases.release({tenant:o.tenant,runId:o.runId,leaseId:o.leaseId})).released}catch{}return eX({stateDir:r,session:n}),tc(e,{connected:!1,session:n,released:a},()=>`Disconnected remote session "${n}".`),!0},tN=async({positionals:e,flags:t})=>{if("status"!==e[0])throw new _("INVALID_ARGS","connection accepts only: status");let s=t.session??"default",r=q(t.stateDir).baseDir,o=eW({stateDir:r,session:s})??(t.session?null:e2({stateDir:r}));if(!o)return tc(t,{connected:!1,session:s},()=>`No remote connection for "${s}".`),!0;let n=function(e){if(!e.runtime&&t_(e.remoteConfigPath))return tC(e.remoteConfigPath)}(o);return tc(t,tR(o,n),()=>[`Connected remote session "${o.session}".`,`tenant=${o.tenant} runId=${o.runId} leaseId=${o.leaseId??"pending"} backend=${o.leaseBackend??"pending"}`,`remoteConfig=${o.remoteConfigPath}`,o.runtime?"metro=prepared":"metro=not-prepared",n?.message].filter(e=>!!e).join("\n")),!0};function tC(e){let t=`agent-device metro prepare --remote-config ${e}`;return{status:"deferred",nextStep:t,message:`Metro runtime is not prepared yet; it will be prepared automatically on first open, or run "${t}" to inspect it before launch.`}}function t_(e){try{let t=k({configPath:e,cwd:process.cwd(),env:process.env}).profile;return!!(t.metroPublicBaseUrl||t.metroProxyBaseUrl||t.metroProjectRoot||t.metroKind)}catch{return!1}}function tR(e,t){return{connected:!0,session:e.session,tenant:e.tenant,runId:e.runId,leaseAllocated:!!e.leaseId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,platform:e.platform,target:e.target,remoteConfig:e.remoteConfigPath,remoteConfigHash:e.remoteConfigHash,daemonBaseUrlFingerprint:function(e){if(e)return p.createHash("sha256").update(e).digest("hex").slice(0,12)}(e.daemon?.baseUrl),metro:e.metro?{prepared:!0,projectRoot:e.metro.projectRoot}:{prepared:!1},...t?{runtimePreparation:t}:{},connectedAt:e.connectedAt,updatedAt:e.updatedAt}}async function tE(e){return await tO({command:e.command,flags:e.flags,stateDir:e.stateDir,allowInteractiveLogin:"connect"===e.command&&!e.flags.noLogin,env:e.env})}async function tO(e){let t=e.env??e.io?.env??process.env;if(!e.flags.daemonBaseUrl)return{flags:e.flags,source:"none"};if(tK(e.flags.daemonAuthToken))return{flags:e.flags,source:"flag"};if(tK(t.AGENT_DEVICE_DAEMON_AUTH_TOKEN))return{flags:e.flags,source:"env"};if(!function(e,t){if("1"===t.AGENT_DEVICE_CLOUD_AUTH||"true"===t.AGENT_DEVICE_CLOUD_AUTH||tK(t.AGENT_DEVICE_CLOUD_BASE_URL))return!0;try{let t=new URL(e).hostname.toLowerCase();return"agent-device.dev"===t||t.endsWith(".agent-device.dev")}catch{return!1}}(e.flags.daemonBaseUrl,t))return{flags:e.flags,source:"none"};let s=tT({stateDir:e.stateDir});if(s&&!tq(s.expiresAt,e.io?.now)){let r=await tM({session:s,flags:e.flags,env:t,io:e.io});return{flags:{...e.flags,daemonAuthToken:r.accessToken},source:"cli-session"}}if(!e.allowInteractiveLogin){if(e.flags.noLogin)throw new _("UNAUTHORIZED","Remote daemon authentication is required.",{hint:"Run agent-device auth login, unset --no-login, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN."});throw tV(e.command,t)}let r=await tP({stateDir:e.stateDir,flags:e.flags,env:t,io:e.io});return{flags:{...e.flags,daemonAuthToken:r.accessToken},source:"login"}}async function tP(e){let t,s,r,o=e.env??e.io?.env??process.env,n=(c=o,p=e.io,t=p?.stdinIsTTY??process.stdin.isTTY,s=p?.stdoutIsTTY??process.stdout.isTTY,"true"!==(d=c).CI&&"true"!==d.GITHUB_ACTIONS&&"true"!==d.BUILDKITE&&t&&s?(m=c).SSH_TTY||m.SSH_CONNECTION||"true"===m.CODESPACES||m.GITPOD_WORKSPACE_ID||"true"===m.REMOTE_CONTAINERS?"device-code":"local-browser":"non-interactive");if("non-interactive"===n)throw tV(e.commandLabel??"agent-device connect",o);let a=tj(o),l=await tB({baseUrl:a,pathName:"/api/control-plane/device-auth/start",body:{client:"agent-device",tenant:e.flags.tenant,runId:e.flags.runId,daemonBaseUrl:e.flags.daemonBaseUrl,session:e.flags.session},fetchImpl:e.io?.fetch});var c,p,d,m,f,g,h=l;if(!tK(h.deviceCode)||!tK(h.userCode)||!tK(h.verificationUri))throw new _("COMMAND_FAILED","Cloud auth start returned an unusable response.");let y=l.verificationUriComplete??l.verificationUri,w="local-browser"===n?l.verificationUri:(f=l.verificationUri,g=l.userCode,(r=new URL(f)).searchParams.set("user_code",g),r.toString());"local-browser"===n?(tH(e.io,`Opening ${l.verificationUri}...
|
|
28
|
-
`),await tG(y,e.io)):tH(e.io,`Open this URL on your machine:
|
|
29
|
-
|
|
363
|
+
`)}function eM(e){return e&&e.summaryLines.length>0?`
|
|
364
|
+
${e.summaryLines.join("\n")}`:""}function eF(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function eB(e){return e>0?`+${e}`:String(e)}function ej(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:"",s=e.regionIndex?` r${e.regionIndex}`:"";return`${e.likelyKind}${t}${s}`}function eV(e){return e.min===e.max?eB(e.min):`${eB(e.min)}..${eB(e.max)}`}function eG(e){let t=process.cwd(),s=l.relative(t,e);return""!==s&&(s.startsWith("..")||l.isAbsolute(s))?e:""===s?".":`.${l.sep}${s}`}function eq(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function eH(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function eK(e,t){return t?c("dim",e):e}function eJ(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function ez(e,t){var s;let o="scroll-area"===(s=e.type)||"list"===s||"collection"===s||"table"===s?s:null;if(!o)return[];let r=[];if(e.node.hiddenContentAbove&&"below"!==t&&r.push(`[content above ${o} hidden]`),e.node.hiddenContentBelow&&"above"!==t&&r.push(`[content below ${o} hidden]`),0===r.length)return[];let a=" ".repeat(e.depth+1);return r.map(e=>`${a}${e}`)}let eW={slug:"react-devtools-companion",runArg:U,displayName:"React DevTools companion"};async function eY(e){return await E({...e,definition:eW,localBaseUrl:e.localBaseUrl??"http://127.0.0.1:8097",registerPath:"/api/react-devtools/companion/register",unregisterPath:"/api/react-devtools/companion/unregister",devicePort:e.devicePort??8097})}async function eZ(e){return await O({...e,definition:eW})}function eX(e){var t;let s,o=e3(e);if(!d.existsSync(o))return null;try{s=JSON.parse(d.readFileSync(o,"utf8"))}catch(t){return e7(e,t),null}return!(!(t=s)||"object"!=typeof t||Array.isArray(t))&&1===t.version&&"string"==typeof t.session&&"string"==typeof t.remoteConfigPath&&"string"==typeof t.remoteConfigHash&&(void 0===t.daemon||"object"==typeof t.daemon&&null!==t.daemon&&!Array.isArray(t.daemon))&&"string"==typeof t.tenant&&"string"==typeof t.runId&&(void 0===t.leaseId||"string"==typeof t.leaseId)&&(void 0===t.leaseBackend||"string"==typeof t.leaseBackend)&&"string"==typeof t.connectedAt&&"string"==typeof t.updatedAt?s:(e7(e),null)}function eQ(e){let t=e3({stateDir:e.stateDir,session:e.state.session});d.mkdirSync(l.dirname(t),{recursive:!0}),e6(t,e.state),e6(e5(e.stateDir),{session:e.state.session})}function e0(e){return{baseUrl:function(e){if(!e)return;let t=new URL(e);for(let e of(t.username="",t.password="",[...t.searchParams.keys()]))/(auth|key|password|secret|token)/i.test(e)&&t.searchParams.delete(e);return t.toString().replace(/\/+$/,"")}(e.daemonBaseUrl),transport:e.daemonTransport,serverMode:e.daemonServerMode}}function e1(e){d.rmSync(e3(e),{force:!0});let t=e5(e.stateDir);e4(e.stateDir)===e.session&&d.rmSync(t,{force:!0})}function e2(e){try{return u.createHash("sha256").update(d.readFileSync(e)).digest("hex")}catch(t){throw new _("INVALID_ARGS",`Remote config file not found: ${e}`,{cause:t instanceof Error?t.message:String(t)})}}function e3(e){return l.join(e.stateDir,"remote-connections",`${function(e){let t=e.replaceAll(/[^a-zA-Z0-9._-]/g,"_");if(!t)return"default";if(t===e)return t;let s=u.createHash("sha256").update(e).digest("hex").slice(0,8);return`${t}-${s}`}(e.session)}.json`)}function e5(e){return l.join(e,"remote-connections",".active-session.json")}function e8(e){let t=e4(e.stateDir);return t?eX({stateDir:e.stateDir,session:t}):null}function e4(e){let t=e5(e);if(d.existsSync(t))try{let e=JSON.parse(d.readFileSync(t,"utf8"));return"string"==typeof e.session?e.session:void 0}catch{return}}function e6(e,t){d.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
365
|
+
`,{encoding:"utf8",mode:384}),d.chmodSync(e,384)}function e7(e,t){V({level:"warn",phase:"remote_connection_state_invalid",data:{session:e.session,cause:t instanceof Error?t.message:t?String(t):void 0}}),e1(e)}let e9=new Set(["connect","connection","close","disconnect","ensure-simulator","metro","session"]),te=new Set(["open"]);async function tt(e){let t,s,{command:o,flags:r,client:a}=e;if(!r.remoteConfig)return{flags:r,runtime:e.runtime};let n=K(r.stateDir).baseDir,i=S({configPath:r.remoteConfig,cwd:process.cwd(),env:process.env}),l={...function(e){let t={};for(let s of $){let o=e[s.key];void 0!==o&&(t[s.key]=o)}return t}(i.profile),...r,remoteConfig:i.resolvedPath},c=eX({stateDir:n,session:l.session??"default"});if(c&&c.remoteConfigPath!==i.resolvedPath)throw new _("INVALID_ARGS","A different remote connection is already active for this session. Run connect --force or disconnect before using a different --remote-config.",{session:c.session,activeRemoteConfig:c.remoteConfigPath,requestedRemoteConfig:i.resolvedPath});let p=c??function(e,t){if(!e.tenant)throw new _("INVALID_ARGS","remote command requires tenant in remote config or via --tenant <id>.");if(!e.runId)throw new _("INVALID_ARGS","remote command requires runId in remote config or via --run-id <id>.");if(!e.daemonBaseUrl)throw new _("INVALID_ARGS","remote command requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.");let s=new Date().toISOString();return{version:1,session:e.session??"default",remoteConfigPath:t,remoteConfigHash:e2(t),daemon:e0(e),tenant:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend??tn(e),platform:e.platform,target:e.target,connectedAt:s,updatedAt:s}}(l,i.resolvedPath),d={...l,session:p.session},u=function(e,t){if(e)return tl(e,t)?e:void 0}(p.runtime,d.platform)??e.runtime,m=p,f=!c;if(g=o,!e9.has(g)){let e=p.leaseBackend??function(e,t){let s=tn(e);if(s)return s;throw new _("INVALID_ARGS",`${t} requires --platform ios|android or --lease-backend when the remote connection has not resolved a lease yet.`)}(r,o);var g,h,v,y,w,b=p,k=r,I=e;if(b.leaseBackend&&b.leaseBackend!==I)throw new _("INVALID_ARGS","Active remote connection is already bound to a different lease backend. Re-run connect --force to replace it.",{session:b.session,leaseBackend:b.leaseBackend});if(b.platform&&k.platform&&b.platform!==k.platform)throw new _("INVALID_ARGS","Active remote connection is already bound to a different platform. Re-run connect --force to replace it.",{session:b.session,platform:b.platform});if(b.target&&k.target&&b.target!==k.target)throw new _("INVALID_ARGS","Active remote connection is already bound to a different target. Re-run connect --force to replace it.",{session:b.session,target:b.target});let t=await tc(a,m,e);d.leaseId=t.leaseId,d.leaseBackend=e,d.platform=m.platform??d.platform,d.target=m.target??d.target,(m.leaseId!==t.leaseId||m.leaseBackend!==e)&&(m={...m,leaseId:t.leaseId,leaseBackend:e,platform:m.platform??r.platform,target:m.target??r.target,updatedAt:new Date().toISOString()},f=!0)}if(h=o,v=e.batchSteps,(te.has(h)||"batch"===h&&v&&v.some(e=>{let t=e.command.trim().toLowerCase();return te.has(t)&&void 0===e.runtime}))&&ti(d)&&(!m.leaseId&&d.leaseId&&(m={...m,leaseId:d.leaseId,leaseBackend:d.leaseBackend}),e.forceRuntimePrepare||!u||!tl(u,d.platform))){if(!m.leaseId)throw new _("INVALID_ARGS",`${o} requires a resolved remote lease before Metro runtime can be prepared.`);let e=await ts(d,a,p.remoteConfigPath,p.session,{tenantId:p.tenant,runId:p.runId,leaseId:m.leaseId});u=e.runtime;let r=(y=m.metro,w=e.cleanup,y?.projectRoot!==w?.projectRoot||y?.profileKey!==w?.profileKey||y?.consumerKey!==w?.consumerKey);t=r?m.metro:void 0,s=r?e.cleanup:void 0,m={...m,runtime:e.runtime,metro:e.cleanup,updatedAt:new Date().toISOString()},f=!0}if(f)try{eQ({stateDir:n,state:m})}catch(e){throw await to(s),e}return await to(t),{flags:{...d,session:m.session,leaseId:m.leaseId,leaseBackend:m.leaseBackend,platform:m.platform??d.platform,target:m.target??d.target},runtime:u}}async function ts(e,t,s,o,r){if(!e.metroProjectRoot&&!e.metroPublicBaseUrl&&!e.metroProxyBaseUrl)return{};if("ios"!==e.platform&&"android"!==e.platform)throw new _("INVALID_ARGS",'Deferred Metro preparation requires platform "ios" or "android".');if(!e.metroPublicBaseUrl&&!e.metroProxyBaseUrl)throw new _("INVALID_ARGS","Deferred Metro preparation requires metroPublicBaseUrl or metroProxyBaseUrl when Metro settings are provided.");let a=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,bridgeScope:r,launchUrl:e.launchUrl,companionProfileKey:s,companionConsumerKey:o,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return{runtime:"ios"===e.platform?a.iosRuntime:a.androidRuntime,cleanup:e.metroProxyBaseUrl?{projectRoot:a.projectRoot,profileKey:s,consumerKey:o}:void 0}}async function to(e){if(e)try{await X(e)}catch{}}async function tr(e){try{await eZ({projectRoot:process.cwd(),stateDir:e.stateDir,profileKey:e.state.remoteConfigPath,consumerKey:e.state.session})}catch{}}async function ta(e,t){if(t.leaseId)try{await e.leases.release({tenant:t.tenant,runId:t.runId,leaseId:t.leaseId,daemonBaseUrl:t.daemon?.baseUrl,daemonTransport:t.daemon?.transport,daemonServerMode:t.daemon?.serverMode})}catch{}}function tn(e){return e.leaseBackend?e.leaseBackend:"android"===e.platform?"android-instance":"ios"===e.platform?"ios-instance":void 0}function ti(e){return!!(e.metroPublicBaseUrl||e.metroProxyBaseUrl||e.metroProjectRoot||e.metroKind)}function tl(e,t){return!e.platform||!t||"ios"!==t&&"android"!==t||e.platform===t}async function tc(e,t,s){if(t.leaseId&&t.leaseBackend===s){let o=await tp(e,t.leaseId,{tenant:t.tenant,runId:t.runId,leaseBackend:s});if(o)return o}return await e.leases.allocate({tenant:t.tenant,runId:t.runId,leaseBackend:s})}async function tp(e,t,s){try{return await e.leases.heartbeat({tenant:s.tenant,runId:s.runId,leaseId:t,leaseBackend:s.leaseBackend})}catch(e){var o;if((o=e)instanceof _&&"UNAUTHORIZED"===o.code&&(o.details?.reason==="LEASE_NOT_FOUND"||o.details?.reason==="LEASE_EXPIRED"||o.details?.reason==="LEASE_REVOKED"))return;throw e}}function td(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function tu(e,t,s){var o;if(e.json)return void eP({success:!0,data:t});let r=s?.();r&&(o=r,process.stdout.write(o.endsWith("\n")?o:`${o}
|
|
366
|
+
`))}function tm(e,t){tu(e,t,()=>H(t))}let tf=async({positionals:e,flags:t,client:s})=>{if("list"!==(e[0]??"list"))throw new _("INVALID_ARGS","session only supports list");let o={sessions:(await s.sessions.list()).map(T)};return tu(t,o,()=>JSON.stringify(o,null,2)),!0},tg=async({flags:e,client:t})=>{let s=await t.devices.list(td(e));return tu(e,{devices:s.map(Z)},()=>s.map(th).join("\n")),!0};function th(e){let t=e.kind?` ${e.kind}`:"",s=e.target?` target=${e.target}`:"",o="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${s})${o}`}let tv=async({flags:e,client:t})=>{if(!e.device)throw new _("INVALID_ARGS","ensure-simulator requires --device <name>");let s=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet});return tu(e,W(s),()=>{let e=s.created?"Created":"Reused",t=s.booted?" (booted)":"";return s.runtime?`${e}: ${s.device} ${s.udid}${t}
|
|
367
|
+
Runtime: ${s.runtime}`:`${e}: ${s.device} ${s.udid}${t}`}),!0},ty=async({positionals:e,flags:t,client:s})=>{let o=(e[0]??"").toLowerCase();if("reload"===o){let e=await s.metro.reload({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs});return tu(t,e,()=>`Reloaded React Native apps via ${e.reloadUrl}`),!0}if("prepare"!==o)throw new _("INVALID_ARGS","metro requires a subcommand: prepare or reload");if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new _("INVALID_ARGS","metro prepare requires --public-base-url <url> or --proxy-base-url <url>.");let r=await s.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,bridgeScope:t.tenant&&t.runId&&t.leaseId?{tenantId:t.tenant,runId:t.runId,leaseId:t.leaseId}:void 0,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile});return tu(t,r,()=>JSON.stringify(r,null,2)),!0},tw=async({flags:e,client:t})=>{let s=await t.apps.list({...td(e),appsFilter:e.appsFilter});return tu(e,{apps:s},()=>s.join("\n")),!0};function tb(e,t,s,o){var r;return"number"==typeof s||"string"==typeof(r=s)&&/^\d+$/.test(r.trim())?{kind:"github-actions-artifact",owner:e,repo:t,artifactId:function(e,t){let s="number"==typeof e?e:"string"==typeof e?Number(e):NaN;if(!Number.isInteger(s))throw new _("INVALID_ARGS",`${t} must be an integer.`);return s}(s,o)}:{kind:"github-actions-artifact",owner:e,repo:t,artifactName:tI(s,o)}}function tk(e,t){let s=e.indexOf("/");if(s<=0||s===e.length-1||-1!==e.indexOf("/",s+1))throw new _("INVALID_ARGS",`${t} must use owner/repo.`);let o={owner:e.slice(0,s).trim(),repo:e.slice(s+1).trim()};if(!o.owner||!o.repo)throw new _("INVALID_ARGS",`${t} must use owner/repo.`);return o}function tI(e,t){let s="string"==typeof e&&e.trim().length>0?e.trim():void 0;if(!s)throw new _("INVALID_ARGS",`${t} must be a non-empty string.`);return s}let tA=async({positionals:e,flags:t,client:s})=>{let o=q(await tx("install",e,t,s));return tm(t,o),!0},tD=async({positionals:e,flags:t,client:s})=>{let o=q(await tx("reinstall",e,t,s));return tm(t,o),!0},tS=async({positionals:e,flags:t,client:s})=>{let o=Y(await t$(e,t,s));return tm(t,o),!0};async function tx(e,t,s,o){let r=t[0],a=t[1];if(!r||!a)throw new _("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let n={app:r,appPath:a,...td(s)};return"install"===e?await o.apps.install(n):await o.apps.reinstall(n)}async function t$(e,t,s){let o=function(e,t){let s=e[0]?.trim();if(e.length>1)throw new _("INVALID_ARGS","install-from-source accepts either one <url> positional or --github-actions-artifact");let o=t.githubActionsArtifact?function(e,t="--github-actions-artifact"){let s=e.indexOf(":");if(s<=0||s===e.length-1)throw new _("INVALID_ARGS",`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:o,repo:r}=tk(e.slice(0,s),t);return tb(o,r,e.slice(s+1),`${t} artifact`)}(t.githubActionsArtifact):void 0,r=t.installSource;if(1!=+!!s+ +!!o+ +!!r)throw new _("INVALID_ARGS","install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource");return o||r||{kind:"url",url:s,headers:function(e){if(!e||0===e.length)return;let t={};for(let s of e){let e=s.indexOf(":");if(e<=0)throw new _("INVALID_ARGS",`Invalid --header value "${s}". Expected "name:value".`);let o=s.slice(0,e).trim(),r=s.slice(e+1).trim();if(!o)throw new _("INVALID_ARGS",`Invalid --header value "${s}". Header name cannot be empty.`);t[o]=r}return t}(t.header)}}(e,t);if("url"!==o.kind&&t.header&&t.header.length>0)throw new _("INVALID_ARGS","install-from-source --header is only supported for URL sources");return await s.apps.installFromSource({...td(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:o})}let tL=async({positionals:e,flags:t,client:s})=>{let o=G(await s.apps.open({app:e[0],url:e[1],surface:t.surface,activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,...td(t)}));return tm(t,o),!0},tN=async({positionals:e,flags:t,client:s})=>{let o=F(e[0]?await s.apps.close({app:e[0],shutdown:t.shutdown}):await s.sessions.close({shutdown:t.shutdown}));return tm(t,o),!0},tR=async({flags:e,client:t})=>{var s,o,r,a;if(!e.remoteConfig)throw new _("INVALID_ARGS","connect requires --remote-config <path>.");let n=e.tenant,i=e.runId;if(!n)throw new _("INVALID_ARGS","connect requires tenant in remote config or via --tenant <id>.");if(!i)throw new _("INVALID_ARGS","connect requires runId in remote config or via --run-id <id>.");if(!e.daemonBaseUrl)throw new _("INVALID_ARGS","connect requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.");let l=K(e.stateDir).baseDir,c=e.session?null:e8({stateDir:l}),p=e.session??c?.session??function(e){for(let t=0;t<8;t+=1){let t=`adc-${u.randomBytes(3).toString("hex")}`;if(!eX({stateDir:e,session:t}))return t}return`adc-${Date.now().toString(36)}-${u.randomBytes(2).toString("hex")}`}(l),d=S({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),m=e2(d.resolvedPath),f=e0(e),g=c?.session===p?c:eX({stateDir:l,session:p});if(g&&(s=g,o={flags:e,session:p,remoteConfigPath:d.resolvedPath,remoteConfigHash:m,desiredLeaseBackend:tn(e),daemon:f},s.remoteConfigPath!==o.remoteConfigPath||s.remoteConfigHash!==o.remoteConfigHash||s.session!==o.session||s.tenant!==o.flags.tenant||s.runId!==o.flags.runId||void 0!==o.desiredLeaseBackend&&s.leaseBackend!==o.desiredLeaseBackend||void 0!==o.flags.platform&&s.platform!==o.flags.platform||void 0!==o.flags.target&&s.target!==o.flags.target||(r=s.daemon,a=o.daemon,(r?.baseUrl??void 0)!==(a?.baseUrl??void 0)||(r?.transport??void 0)!==(a?.transport??void 0)||(r?.serverMode??void 0)!==(a?.serverMode??void 0)))&&!e.force)throw new _("INVALID_ARGS","A different remote connection is already active for this session. Re-run connect with --force to replace it.",{session:p,remoteConfig:g.remoteConfigPath});let h=new Date().toISOString(),v={version:1,session:p,remoteConfigPath:d.resolvedPath,remoteConfigHash:m,daemon:f,tenant:n,runId:i,leaseId:g&&!e.force?g.leaseId:void 0,leaseBackend:g&&!e.force?g.leaseBackend:tn(e),platform:e.platform??(g&&!e.force?g.platform:void 0),target:e.target??(g&&!e.force?g.target:void 0),runtime:g&&!e.force?g.runtime:void 0,metro:g&&!e.force?g.metro:void 0,connectedAt:g&&!e.force?g.connectedAt:h,updatedAt:h};eQ({stateDir:l,state:v}),g&&e.force&&(await to(g.metro),await tr({stateDir:l,state:g}),await ta(t,g));let y=tE(v),w=function(e,t){if(!t.runtime&&(ti(e)||tU(t.remoteConfigPath)))return tO(t.remoteConfigPath)}(e,v);return tu(e,tP(v,w),()=>[`Connected remote session "${p}" tenant "${n}" run "${i}" ${v.leaseId?`lease ${v.leaseId}`:"lease pending"}`,y?.message,w?.message].filter(e=>!!e).join("\n")),!0},tC=async({flags:e,client:t})=>{let s=e.session??"default",o=K(e.stateDir).baseDir,r=eX({stateDir:o,session:s})??(e.session?null:e8({stateDir:o}));if(!r)return tu(e,{connected:!1,session:s},()=>`No remote connection for "${s}".`),!0;let a=r.session;try{await t.sessions.close({shutdown:e.shutdown})}catch{}await to(r.metro),await tr({stateDir:o,state:r});let n=!1;if(r.leaseId)try{n=(await t.leases.release({tenant:r.tenant,runId:r.runId,leaseId:r.leaseId})).released}catch{}return e1({stateDir:o,session:a}),tu(e,{connected:!1,session:a,released:n},()=>`Disconnected remote session "${a}".`),!0},t_=async({positionals:e,flags:t})=>{if("status"!==e[0])throw new _("INVALID_ARGS","connection accepts only: status");let s=t.session??"default",o=K(t.stateDir).baseDir,r=eX({stateDir:o,session:s})??(t.session?null:e8({stateDir:o}));if(!r)return tu(t,{connected:!1,session:s},()=>`No remote connection for "${s}".`),!0;let a=tE(r),n=function(e){if(!e.runtime&&tU(e.remoteConfigPath))return tO(e.remoteConfigPath)}(r);return tu(t,tP(r,n),()=>[`Connected remote session "${r.session}".`,`tenant=${r.tenant} runId=${r.runId} leaseId=${r.leaseId??"pending"} backend=${r.leaseBackend??"pending"}`,`remoteConfig=${r.remoteConfigPath}`,r.runtime?"metro=prepared":"metro=not-prepared",a?.message,n?.message].filter(e=>!!e).join("\n")),!0};function tE(e){if(!e.leaseId)return{status:"deferred",nextSteps:["agent-device install-from-source <artifact-url> --platform ios|android","agent-device open <app-id> --relaunch","agent-device snapshot -i","agent-device devices"],message:"Lease allocation is pending; run install-from-source, open, snapshot, or devices when ready to allocate or refresh the lease."+(void 0===e.platform&&void 0===e.leaseBackend?" Add --platform ios|android if the profile does not set a platform.":"")}}function tO(e){let t=`agent-device metro prepare --remote-config ${e}`;return{status:"deferred",nextStep:t,message:`Metro runtime is not prepared yet; it will be prepared automatically on first open, or run "${t}" to inspect it before launch.`}}function tU(e){try{let t=S({configPath:e,cwd:process.cwd(),env:process.env}).profile;return!!(t.metroPublicBaseUrl||t.metroProxyBaseUrl||t.metroProjectRoot||t.metroKind)}catch{return!1}}function tP(e,t){let s=tE(e);return{connected:!0,session:e.session,tenant:e.tenant,runId:e.runId,leaseAllocated:!!e.leaseId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,platform:e.platform,target:e.target,remoteConfig:e.remoteConfigPath,remoteConfigHash:e.remoteConfigHash,daemonBaseUrlFingerprint:function(e){if(e)return u.createHash("sha256").update(e).digest("hex").slice(0,12)}(e.daemon?.baseUrl),metro:e.metro?{prepared:!0,projectRoot:e.metro.projectRoot}:{prepared:!1},...s?{leasePreparation:s}:{},...t?{runtimePreparation:t}:{},connectedAt:e.connectedAt,updatedAt:e.updatedAt}}async function tT(e){return await tM({command:e.command,flags:e.flags,stateDir:e.stateDir,allowInteractiveLogin:"connect"===e.command&&!e.flags.noLogin,env:e.env})}async function tM(e){let t=e.env??e.io?.env??process.env;if(!e.flags.daemonBaseUrl)return{flags:e.flags,source:"none"};if(tY(e.flags.daemonAuthToken))return{flags:e.flags,source:"flag"};if(tY(t.AGENT_DEVICE_DAEMON_AUTH_TOKEN))return{flags:e.flags,source:"env"};if(!function(e,t){if("1"===t.AGENT_DEVICE_CLOUD_AUTH||"true"===t.AGENT_DEVICE_CLOUD_AUTH||tY(t.AGENT_DEVICE_CLOUD_BASE_URL))return!0;try{let t=new URL(e).hostname.toLowerCase();return"agent-device.dev"===t||t.endsWith(".agent-device.dev")}catch{return!1}}(e.flags.daemonBaseUrl,t))return{flags:e.flags,source:"none"};let s=tB({stateDir:e.stateDir});if(s&&!tW(s.expiresAt,e.io?.now)){let o=await tV({session:s,flags:e.flags,env:t,io:e.io});return{flags:{...e.flags,daemonAuthToken:o.accessToken},source:"cli-session"}}if(!e.allowInteractiveLogin){if(e.flags.noLogin)throw new _("UNAUTHORIZED","Remote daemon authentication is required.",{hint:"Run agent-device auth login, unset --no-login, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN."});throw tH(e.command,t)}let o=await tF({stateDir:e.stateDir,flags:e.flags,env:t,io:e.io});return{flags:{...e.flags,daemonAuthToken:o.accessToken},source:"login"}}async function tF(e){let t,s,o,r=e.env??e.io?.env??process.env,a=(c=r,p=e.io,t=p?.stdinIsTTY??process.stdin.isTTY,s=p?.stdoutIsTTY??process.stdout.isTTY,"true"!==(u=c).CI&&"true"!==u.GITHUB_ACTIONS&&"true"!==u.BUILDKITE&&t&&s?(m=c).SSH_TTY||m.SSH_CONNECTION||"true"===m.CODESPACES||m.GITPOD_WORKSPACE_ID||"true"===m.REMOTE_CONTAINERS?"device-code":"local-browser":"non-interactive");if("non-interactive"===a)throw tH(e.commandLabel??"agent-device connect",r);let n=tK(r),i=await tq({baseUrl:n,pathName:"/api/control-plane/device-auth/start",body:{client:"agent-device",tenant:e.flags.tenant,runId:e.flags.runId,daemonBaseUrl:e.flags.daemonBaseUrl,session:e.flags.session},fetchImpl:e.io?.fetch});var c,p,u,m,f,g,h=i;if(!tY(h.deviceCode)||!tY(h.userCode)||!tY(h.verificationUri))throw new _("COMMAND_FAILED","Cloud auth start returned an unusable response.");let v=i.verificationUriComplete??i.verificationUri,y="local-browser"===a?i.verificationUri:(f=i.verificationUri,g=i.userCode,(o=new URL(f)).searchParams.set("user_code",g),o.toString());"local-browser"===a?(tz(e.io,`Opening ${i.verificationUri}...
|
|
368
|
+
`),await tJ(v,e.io)):tz(e.io,`Open this URL on your machine:
|
|
369
|
+
${y}
|
|
30
370
|
|
|
31
371
|
Waiting for approval for 10 minutes...
|
|
32
|
-
`);let
|
|
33
|
-
`,{mode:384});try{
|
|
372
|
+
`);let w=await tG({cloudBaseUrl:n,deviceCode:i.deviceCode,expiresIn:i.expiresIn,interval:i.interval,fetchImpl:e.io?.fetch,now:e.io?.now}),b=w.cliSession?.refreshCredential??w.cliSession?.refreshToken;if(!tY(w.accessToken)||!tY(b))throw new _("UNAUTHORIZED","Device authorization did not return CLI credentials.");let k=new Date(e.io?.now?.()??Date.now()).toISOString(),I={version:1,id:w.cliSession?.id??`cli-${Date.now().toString(36)}`,cloudBaseUrl:n,workspaceId:w.cliSession?.workspaceId,accountId:w.cliSession?.accountId,name:w.cliSession?.name,refreshCredential:b,createdAt:k,expiresAt:w.cliSession?.expiresAt};return function(e){let t=tj(e.stateDir);d.mkdirSync(l.dirname(t),{recursive:!0,mode:448}),d.writeFileSync(t,`${JSON.stringify(e.session,null,2)}
|
|
373
|
+
`,{mode:384});try{d.chmodSync(t,384)}catch{}}({stateDir:e.stateDir,session:I}),{accessToken:w.accessToken,expiresAt:w.expiresAt,session:I}}function tB(e){let t=tj(e.stateDir);if(!d.existsSync(t))return null;try{let e=JSON.parse(d.readFileSync(t,"utf8"));if(1!==e.version||!tY(e.id)||!tY(e.cloudBaseUrl)||!tY(e.refreshCredential)||!tY(e.createdAt))return null;return e}catch{return null}}function tj(e){return l.join(e,"auth","cli-session.json")}async function tV(e){let t=tK(e.env,e.session.cloudBaseUrl),s=await tq({baseUrl:t,pathName:"/api/control-plane/cli-session/refresh",body:{refreshCredential:e.session.refreshCredential,tenant:e.flags.tenant,runId:e.flags.runId,daemonBaseUrl:e.flags.daemonBaseUrl,session:e.flags.session},fetchImpl:e.io?.fetch});if(tY(s.accessToken))return{accessToken:s.accessToken,expiresAt:s.expiresAt};if("revoked"===s.status||"revoked"===s.error)throw new _("UNAUTHORIZED","Stored cloud CLI session was revoked.",{hint:"Run agent-device auth login again, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.",status:s.status,error:s.error});throw new _("UNAUTHORIZED","Failed to refresh CLI session.",{hint:"Run agent-device auth login again, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.",status:s.status,error:s.error})}async function tG(e){let t=e.now??Date.now,s=Math.min((e.expiresIn??600)*1e3,6e5),o=t()+s,r=Math.max(1e3,(e.interval??5)*1e3);for(;t()<o;){let t=await tq({baseUrl:e.cloudBaseUrl,pathName:"/api/control-plane/device-auth/poll",body:{deviceCode:e.deviceCode},fetchImpl:e.fetchImpl});if("approved"===t.status||tY(t.accessToken))return t;if("slow_down"===t.status||"slow_down"===t.error)r+=1e3;else if("authorization_pending"!==t.status&&"authorization_pending"!==t.error)throw new _("UNAUTHORIZED","Device authorization was not approved.",{status:t.status,error:t.error});await tZ(r)}throw new _("TIMEOUT","Device authorization expired before approval.")}async function tq(e){let t=e.fetchImpl??fetch,s=await t(new URL(e.pathName,e.baseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(15e3)}),o=await s.text(),r={};if(o.trim().length>0)try{r=JSON.parse(o)}catch(e){throw new _("COMMAND_FAILED",`Cloud auth endpoint returned invalid JSON (${s.status}).`,{status:s.status},e instanceof Error?e:void 0)}if(!s.ok)throw new _("UNAUTHORIZED","Cloud auth endpoint rejected the request.",{status:s.status,response:r});return r}function tH(e,t){let s=tK(t);return new _("UNAUTHORIZED",`${e} cannot perform interactive login in CI or a non-interactive shell.`,{hint:`Create a service/API token: ${new URL("/api-keys",s).toString()} Then set AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_...`})}function tK(e,t){let s=e.AGENT_DEVICE_CLOUD_BASE_URL??t??"https://cloud.agent-device.dev";try{return new URL(s).toString().replace(/\/+$/,"")}catch(e){throw new _("INVALID_ARGS","Invalid AGENT_DEVICE_CLOUD_BASE_URL.",{cloudBaseUrl:s},e instanceof Error?e:void 0)}}async function tJ(e,t){if(t?.openBrowser)return void await t.openBrowser(e);let s=process.platform;try{"darwin"===s?await ee("open",[e],{allowFailure:!0,timeoutMs:5e3}):"win32"===s?await ee("cmd",["/c","start","",e],{allowFailure:!0,timeoutMs:5e3}):await ee("xdg-open",[e],{allowFailure:!0,timeoutMs:5e3})}catch{tz(t,`Open this URL on your machine:
|
|
34
374
|
${e}
|
|
35
|
-
`)}}function
|
|
36
|
-
`:"",
|
|
37
|
-
`:"";
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
|
|
41
|
-
${
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
${
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
`:"";if(
|
|
48
|
-
`;let
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
`
|
|
52
|
-
`}
|
|
53
|
-
`):tu(r,o),!0}};function tQ(e){return null===e?{}:{timeoutMs:e}}function t0(e){let{suite:t,json:s,verbose:r,reportJunit:o}=e;return(o&&function(e,t){let s=i.dirname(e);try{u.mkdirSync(s,{recursive:!0}),u.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="${t3(e.durationMs)}">`];for(let s of e.tests)t.push(...function(e){let t=t8(i.basename(e.file)),s=t8("."===i.dirname(e.file)?e.file:i.dirname(e.file)),r=t8(e.file),o=t3(e.durationMs),n=[` <testcase classname="${s}" name="${t}" file="${r}" time="${o}">`];"failed"===e.status?n.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 s=e.error.details?JSON.stringify(e.error.details,null,2):void 0;return s&&t.push(`details: ${s}`),t.join("\n")}(e))}</failure>`):"skipped"===e.status&&n.push(` <skipped message="${t8(e.message)}" />`);let a=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 a&&n.push(` <system-out>${t8(a)}</system-out>`),n.push(" </testcase>"),n}(s));return t.push(" </testsuite>"),t.push("</testsuites>"),`${t.join("\n")}
|
|
54
|
-
`}(t),"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new _("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(o,t),s)?(eO({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let s=e.tests.filter(t2);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return t1(e);let t="passed"===e.status?t2(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",s="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",r=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${s}${r}
|
|
375
|
+
`)}}function tz(e,t){(e?.stderr??process.stderr).write(t)}function tW(e,t){if(!e)return!1;let s=Date.parse(e);return!Number.isFinite(s)||s<=(t?.()??Date.now())}function tY(e){return"string"==typeof e&&e.trim().length>0}async function tZ(e){await new Promise(t=>setTimeout(t,e))}let tX=async({positionals:e,flags:t})=>{let s=e[0]??"status",o=K(t.stateDir).baseDir;if("status"===s){var r;let e,s=(e=tB({stateDir:(r={stateDir:o}).stateDir}))?{authenticated:!0,source:"cli-session",sessionId:e.id,cloudBaseUrl:e.cloudBaseUrl,workspaceId:e.workspaceId,accountId:e.accountId,name:e.name,createdAt:e.createdAt,expiresAt:e.expiresAt,expired:tW(e.expiresAt,r.now)}:{authenticated:!1,source:"none"};return tu(t,s,()=>{var e;return(e=s).authenticated?["Authenticated with cloud CLI session.",`cloud=${e.cloudBaseUrl}`,`session=${e.sessionId}`,e.workspaceId?`workspace=${e.workspaceId}`:null,e.accountId?`account=${e.accountId}`:null,e.expiresAt?`expiresAt=${e.expiresAt}`:null,e.expired?"status=expired":null].filter(e=>!!e).join("\n"):"Not authenticated."}),!0}if("login"===s){let e=await tF({stateDir:o,flags:t,commandLabel:"agent-device auth login"});return tu(t,{authenticated:!0,source:"cli-session",sessionId:e.session.id,cloudBaseUrl:e.session.cloudBaseUrl,workspaceId:e.session.workspaceId,accountId:e.session.accountId,expiresAt:e.session.expiresAt,agentTokenExpiresAt:e.expiresAt},()=>"Authenticated with cloud CLI session."),!0}if("logout"===s){let e,s=(e=tj({stateDir:o}.stateDir),!!d.existsSync(e)&&(d.rmSync(e,{force:!0}),!0));return tu(t,{authenticated:!1,removed:s},()=>s?"Removed stored cloud CLI session.":"No stored cloud CLI session."),!0}throw new _("INVALID_ARGS","auth accepts only: status, login, logout")},tQ=async({flags:e,client:t})=>{let s=M(await t.capture.snapshot({...td(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return tu(e,s,()=>(function(e,t={}){var s,o,r,a,n,i;let l,c,p,d,u,f=e.nodes,h=Array.isArray(f)?f:[],v="string"==typeof e.backend?e.backend:void 0,y=t.raw||"macos-helper"===v?null:m(h),w=!!e.truncated,k=y?.nodes??h,I=t.raw||"macos-helper"===v?null:function(e,t,s,o){let r=e.visibility;if(r&&"object"==typeof r&&"boolean"==typeof r.partial&&"number"==typeof r.visibleNodeCount&&"number"==typeof r.totalNodeCount&&Array.isArray(r.reasons))return{partial:r.partial,visibleNodeCount:r.visibleNodeCount,totalNodeCount:r.totalNodeCount,reasons:r.reasons.filter(e=>"string"==typeof e)};let a=t?.hiddenCount??0,n=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return a>0?{partial:!0,visibleNodeCount:s,totalNodeCount:o,reasons:["offscreen-nodes"]}:n?{partial:!0,visibleNodeCount:s,totalNodeCount:s,reasons:[]}:null}(e,y,k.length,h.length),A=(s=h.length,o=I,l=w?" (truncated)":"",o?.partial?o.totalNodeCount>o.visibleNodeCount?`Snapshot: ${o.visibleNodeCount} visible nodes (${o.totalNodeCount} total)${l}`:`Snapshot: ${o.visibleNodeCount} visible nodes${l}`:`Snapshot: ${s} nodes${l}`),S=(c="string"==typeof(r=e).appName?r.appName:void 0,p="string"==typeof r.appBundleId?r.appBundleId:void 0,d=[],c&&d.push(`Page: ${c}`),p&&d.push(`App: ${p}`),d.length>0?`${d.join("\n")}
|
|
376
|
+
`:""),x=(a=e,n=h,i=t,u=eJ(a),!i.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let s of e){let e=(s.type??"").toLowerCase(),o=b(s).trim().toLowerCase();if(!o)continue;let r=`${e}|${o}`;t.set(r,(t.get(r)??0)+1)}let s=0;for(let e of t.values())e>1&&(s+=e);return s>=8}(n)&&u.push("Warning: possible repeated nav subtree detected."),u),$=x.length>0?`${x.join("\n")}
|
|
377
|
+
`:"";return 0===h.length?`${S}${A}
|
|
378
|
+
${$}`:t.raw?`${S}${A}
|
|
379
|
+
${$}${h.map(e=>JSON.stringify(e)).join("\n")}
|
|
380
|
+
`:t.flatten?`${S}${A}
|
|
381
|
+
${$}${D(k,{summarizeTextSurfaces:!0}).flatMap(e=>[g(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...ez({...e,depth:0})]).join("\n")}${eM(y)}
|
|
382
|
+
`:`${S}${A}
|
|
383
|
+
${$}${(function(e){let t=[],s=[],o=e=>{for(;s.length>0&&e<=s[s.length-1].depth;)t.push(...ez(s.pop(),"below"))};for(let r of e)o(r.depth),t.push(r.text),t.push(...ez(r,"above")),r.node.hiddenContentBelow&&s.push(r);return o(0),t})(D(k,{summarizeTextSurfaces:!0})).join("\n")}${eM(y)}
|
|
384
|
+
`})(s,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},t0=async({positionals:e,flags:t,client:s})=>{let o=await s.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs,maxSize:t.screenshotMaxSize,...void 0!==t.screenshotFullscreen?{fullscreen:t.screenshotFullscreen}:{}});return tu(t,{path:o.path,...o.overlayRefs?{overlayRefs:o.overlayRefs}:{}},()=>o.overlayRefs?`Annotated ${o.overlayRefs.length} refs onto ${o.path}`:o.path),!0},t1=async({positionals:e,flags:t,client:s})=>{var o;if("snapshot"===e[0]){let e=await s.capture.diff({...td(t),kind:"snapshot",out:t.out,interactiveOnly:t.snapshotInteractiveOnly,compact:t.snapshotCompact,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw});return tu(t,e,()=>(function(e){var t;let s=!0===e.baselineInitialized,o=e.summary??{},r=eq(o.additions),a=eq(o.removals),n=eq(o.unchanged),i=eH(),l=eJ(e),p=l.length>0?`${l.join("\n")}
|
|
385
|
+
`:"";if(s)return`${p}Baseline initialized (${n} lines).
|
|
386
|
+
`;let d=(function(e){if(0===e.length)return e;let t=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===t.length)return e;let s=Array(e.length).fill(!1);for(let o of t){let t=Math.max(0,o-1),r=Math.min(e.length-1,o+1);for(let e=t;e<=r;e+=1)s[e]=!0}return e.filter((e,t)=>s[t])})(Array.isArray(e.lines)?e.lines:[]).map(e=>{let t="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=t.startsWith(" ")?`+${t}`:`+ ${t}`;return i?c("green",e):e}if("removed"===e.kind){let e=t.startsWith(" ")?`-${t}`:`- ${t}`;return i?c("red",e):e}return i?c("dim",t):t}),u=d.length>0?`${d.join("\n")}
|
|
387
|
+
`:"";if(!i)return`${p}${u}${r} additions, ${a} removals, ${n} unchanged
|
|
388
|
+
`;let m=`${(t=String(r),c("green",t))} additions, ${c("red",String(a))} removals, ${c("dim",String(n))} unchanged`;return`${p}${u}${m}
|
|
389
|
+
`})(e)),!0}if("screenshot"!==e[0])return!1;let r=t.baseline;if(!r||"string"!=typeof r)throw new _("INVALID_ARGS","diff screenshot requires --baseline <path>");let a=et(r),n="string"==typeof t.out?et(t.out):void 0,i=e[1];if(e.length>2)throw new _("INVALID_ARGS","diff screenshot accepts at most one current screenshot path");let l=y({backend:(o=s,{platform:function(e){switch(e.platform){case"android":case"linux":case"macos":return e.platform;default:return"ios"}}(t),captureScreenshot:async(e,t,s)=>{let r=await o.capture.screenshot({path:t,session:e.session,overlayRefs:s?.overlayRefs,fullscreen:s?.fullscreen,surface:s?.surface});return{path:r.path,...r.overlayRefs?{overlayRefs:r.overlayRefs}:{}}}}),artifacts:eo(),sessions:{get:e=>({name:e}),set:()=>{}},policy:k()}),p=await l.capture.diffScreenshot({session:t.session,baseline:{kind:"path",path:a},current:i?{kind:"path",path:et(i)}:{kind:"live"},...n?{out:{kind:"path",path:n}}:{},threshold:function(e){if(null!=e&&""!==e)return Number(e)}(t.threshold),overlayRefs:t.overlayRefs,surface:t.surface});return tu(t,p,()=>{var e,t,s,o;let r,a,n,i,l,d,u,m;return r=eH(),a=!0===p.match,n=p.dimensionMismatch,(i=[]).push(...function(e,t){if(!0===e.match){let e=t?c("green","✓"):"✓";return[`${e} Screenshots match.`]}let s=e.dimensionMismatch,o=t?c("red","✗"):"✗";if(s){let e=s.expected,t=s.actual;return[`${o} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let r=eq(e.differentPixels),a=eq(e.mismatchPercentage),n=0===a&&r>0?"<0.01":String(a),i=`${n}% pixels differ`;return[`${o} ${t?c("red",i):i}`]}(p,r)),i.push(...function(e,t,s){if(t)return[];let o=[];if(e.diffPath){let t=eG(e.diffPath),r=s?c("dim","Diff image:"):"Diff image:",a=s?c("green",t):t;o.push(` ${r} ${a}`)}if(e.currentOverlayPath){let t=eG(e.currentOverlayPath),r=s?c("dim","Current overlay:"):"Current overlay:",a=s?c("green",t):t,n=eq(e.currentOverlayRefCount),i=n>0?` (${n} refs)`:"";o.push(` ${r} ${a}${i}`)}return o}(p,a,r)),a||n||(i.push(...(e=p,t=r,l=eq(e.differentPixels),d=eq(e.totalPixels),u=t?c("red",String(l)):String(l),[` ${u} different / ${d} total pixels`])),i.push(...(s=p,o=r,0===(m=function(e){let t=[];for(let s of(e.ocr?.movementClusters??[]).slice(0,2))t.push(`text movement cluster: ${function(e){let t=e.slice(0,4).map(e=>JSON.stringify(e)),s=e.length>t.length?` +${e.length-t.length} more`:"";return`${t.join(", ")}${s}`}(s.texts)} dx=${eV(s.xRange)}px dy=${eV(s.yRange)}px`);let s=(e.nonTextDeltas??[]).filter(e=>["icon","toggle","chevron"].includes(e.likelyKind)).slice(0,3);s.length>0&&t.push(`non-text controls: ${s.map(ej).join("; ")}`);let o=(e.nonTextDeltas??[]).filter(e=>"separator"===e.likelyKind).slice(0,2);return o.length>0&&t.push(`non-text boundaries: ${o.map(ej).join("; ")}`),t.slice(0,6)}(s)).length?[]:[` ${eK("Hints:",o)}`,...m.map(e=>` - ${e}`)])),i.push(...function(e,t){let s=Array.isArray(e.regions)?e.regions:[];if(0===s.length)return[];let o=[` ${eK("Changed regions:",t)}`];for(let e of s.slice(0,5))o.push(...function(e){let t=0===e.shareOfDiffPercentage&&e.differentPixels>0?"<0.01":String(e.shareOfDiffPercentage),s=e.rect,o=[` ${e.index}. ${e.location} x=${s.x} y=${s.y} ${s.width}x${s.height}, ${t}% of diff, change=${e.dominantChange}`],r=function(e){let t=[e.size?`size=${e.size}`:null,e.shape?`shape=${e.shape}`:null,"number"==typeof e.densityPercentage?`density=${e.densityPercentage}%`:null,e.averageBaselineColorHex&&e.averageCurrentColorHex?`avgColor=${e.averageBaselineColorHex}->${e.averageCurrentColorHex}`:null,"number"==typeof e.baselineLuminance&&"number"==typeof e.currentLuminance?`luminance=${e.baselineLuminance}->${e.currentLuminance}`:null].filter(e=>null!==e);return t.length>0?t.join(" "):null}(e);r&&o.push(` ${r}`);let a=e.currentOverlayMatches?.[0];if(a){let e=a.label?` "${a.label}"`:"";o.push(` overlaps @${a.ref}${e}, ${a.regionCoveragePercentage}% of region`)}return o}(e));return o}(p,r)),i.push(...function(e,t){let s=e.ocr?.matches??[];if(0===s.length)return[];let o=s.slice(0,8),r=[` ${eK(`OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${o.length}/${s.length}; px):`,t)}`,` ${eK("item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint",t)}`];for(let[e,t]of o.entries()){let s=t.delta;r.push(` ${e+1} | ${JSON.stringify(t.text)} | ${eB(s.x)},${eB(s.y)} | ${eB(s.width)},${eB(s.height)} | ${eF(t.baselineRect)} | ${eF(t.currentRect)} | ${t.confidence} | ${t.possibleTextMetricMismatch?"ocr-bbox-size-change":"-"}`)}return r}(p,r)),i.push(...function(e,t){let s=e.nonTextDeltas??[];if(0===s.length)return[];let o=s.slice(0,8),r=[` ${eK(`Non-text visual deltas (showing ${o.length}/${s.length}; px):`,t)}`,` ${eK("item | region | slot | kind | bboxCurrent | nearestText",t)}`];for(let e of o)r.push(` ${e.index} | ${e.regionIndex?`r${e.regionIndex}`:"-"} | ${e.slot} | ${e.likelyKind} | ${eF(e.rect)} | ${e.nearestText?JSON.stringify(e.nearestText):"-"}`);return r}(p,r))),`${i.join("\n")}
|
|
390
|
+
`}),!0},t2={[ea.wait]:async({positionals:e,flags:t,client:s})=>(tm(t,await s.command.wait(function(e,t){let s=A(e);if(!s)throw new _("INVALID_ARGS","wait requires <ms>, text <text>, @ref, or <selector> [timeoutMs].");let o={...td(t),depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw};if("sleep"===s.kind)return{...o,durationMs:s.durationMs};if("text"===s.kind){if(!s.text)throw new _("INVALID_ARGS","wait requires text.");return{...o,text:s.text,...t3(s.timeoutMs)}}return"ref"===s.kind?{...o,ref:s.rawRef,...t3(s.timeoutMs)}:{...o,selector:s.selectorExpression,...t3(s.timeoutMs)}}(e,t))),!0),[ea.alert]:async({positionals:e,flags:t,client:s})=>(tm(t,await s.command.alert(function(e,t){if(e.length>2)throw new _("INVALID_ARGS","alert accepts at most action and timeout arguments.");let s=function(e){let t=e?.toLowerCase();if(void 0===t||"get"===t||"accept"===t||"dismiss"===t||"wait"===t)return t;throw new _("INVALID_ARGS","alert action must be get, accept, dismiss, or wait.")}(e[0]),o=function(e,t){if(void 0===e)return;let s=Number(e);if(Number.isFinite(s))return s;throw new _("INVALID_ARGS",`${t} must be a finite number.`)}(e[1],"alert timeout");return{...td(t),...s?{action:s}:{},...void 0!==o?{timeoutMs:o}:{}}}(e,t))),!0),[ea.appState]:async({flags:e,client:t})=>{let s=await t.command.appState(td(e));return tu(e,s,()=>(function(e){if("ios"===e.platform){let t=[`Foreground app: ${e.appName??e.appBundleId??"unknown"}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.source&&t.push(`Source: ${e.source}`),t.join("\n")}if("android"===e.platform){let t=[`Foreground app: ${e.package??"unknown"}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join("\n")}return null})(s)),!0},[ea.back]:async({flags:e,client:t})=>(tm(e,await t.command.back({...td(e),mode:e.backMode})),!0),[ea.home]:async({flags:e,client:t})=>(tm(e,await t.command.home(td(e))),!0),[ea.rotate]:async({positionals:e,flags:t,client:s})=>(tm(t,await s.command.rotate(function(e,t){if(e.length>1)throw new _("INVALID_ARGS","rotate accepts exactly one orientation argument.");return{...td(t),orientation:I(e[0])}}(e,t))),!0),[ea.appSwitcher]:async({flags:e,client:t})=>(tm(e,await t.command.appSwitcher(td(e))),!0),[ea.keyboard]:async({positionals:e,flags:t,client:s})=>(tm(t,await s.command.keyboard(function(e,t){if(e.length>1)throw new _("INVALID_ARGS","keyboard accepts at most one action argument.");let s=function(e){let t=e?.toLowerCase();if("get"===t)return"status";if(void 0===t||"status"===t||"dismiss"===t)return t;throw new _("INVALID_ARGS","keyboard action must be status, get, or dismiss.")}(e[0]);return{...td(t),...s?{action:s}:{}}}(e,t))),!0),[ea.clipboard]:async({positionals:e,flags:t,client:s})=>{var o,r;return o=t,r=await s.command.clipboard(function(e,t){let s=e[0]?.toLowerCase();if("read"!==s&&"write"!==s)throw new _("INVALID_ARGS","clipboard requires a subcommand: read or write.");let o=td(t);if("read"===s){if(1!==e.length)throw new _("INVALID_ARGS","clipboard read does not accept additional arguments.");return{...o,action:s}}if(e.length<2)throw new _("INVALID_ARGS","clipboard write requires text.");return{...o,action:s,text:e.slice(1).join(" ")}}(e,t)),o.json?tu(o,r):"read"===r.action?process.stdout.write(`${r.text}
|
|
391
|
+
`):tm(o,r),!0}};function t3(e){return null===e?{}:{timeoutMs:e}}function t5(e){let{suite:t,json:s,verbose:o,reportJunit:r}=e;return(r&&function(e,t){let s=l.dirname(e);try{d.mkdirSync(s,{recursive:!0}),d.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="${t6(e.durationMs)}">`];for(let s of e.tests)t.push(...function(e){let t=t7(l.basename(e.file)),s=t7("."===l.dirname(e.file)?e.file:l.dirname(e.file)),o=t7(e.file),r=t6(e.durationMs),a=[` <testcase classname="${s}" name="${t}" file="${o}" time="${r}">`];"failed"===e.status?a.push(` <failure message="${t7(e.error.message)}">${t7(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 s=e.error.details?JSON.stringify(e.error.details,null,2):void 0;return s&&t.push(`details: ${s}`),t.join("\n")}(e))}</failure>`):"skipped"===e.status&&a.push(` <skipped message="${t7(e.message)}" />`);let n=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 n&&a.push(` <system-out>${t7(n)}</system-out>`),a.push(" </testcase>"),a}(s));return t.push(" </testsuite>"),t.push("</testsuites>"),`${t.join("\n")}
|
|
392
|
+
`}(t),"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new _("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(r,t),s)?(eP({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let s=e.tests.filter(t4);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return t8(e);let t="passed"===e.status?t4(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",s="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",o=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${s}${o}
|
|
55
393
|
`),"skipped"===e.status&&process.stdout.write(` ${e.message??"skipped"}
|
|
56
|
-
`)}(t);else{for(let t of e.failures)
|
|
57
|
-
`)}(e)}let
|
|
58
|
-
`),function(e){return+(e.failed>0)}(e)}(t,{verbose:
|
|
394
|
+
`)}(t);else{for(let t of e.failures)t8(t);for(let e of s)!function(e){let t=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FLAKY ${e.file} after ${e.attempts} attempts${t}
|
|
395
|
+
`)}(e)}let o="number"==typeof e.durationMs?e.durationMs:void 0,r=s.length>0?`, ${s.length} flaky`:"";return process.stdout.write(`Test summary: ${e.passed} passed, ${e.failed} failed${r}${void 0!==o?` in ${o}ms`:""}
|
|
396
|
+
`),function(e){return+(e.failed>0)}(e)}(t,{verbose:o})}function t8(e){let t=e.attempts>1?` after ${e.attempts} attempts`:"",s=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FAIL ${e.file}${t}${s}
|
|
59
397
|
`),process.stdout.write(` ${e.error?.message??"Unknown test failure"}
|
|
60
398
|
`),e.error?.hint&&process.stdout.write(` hint: ${e.error.hint}
|
|
61
399
|
`),e.artifactsDir&&process.stdout.write(` artifacts: ${e.artifactsDir}
|
|
62
400
|
`),e.error?.logPath&&process.stdout.write(` log: ${e.error.logPath}
|
|
63
401
|
`),e.error?.diagnosticId&&process.stdout.write(` diagnostic: ${e.error.diagnosticId}
|
|
64
|
-
`)}function
|
|
65
|
-
`),Array.isArray(e.results)?e.results:[])){var
|
|
66
|
-
`)}}(
|
|
67
|
-
`),0;if("attrs"===e)return process.stdout.write(`${JSON.stringify(
|
|
68
|
-
`),0}if(e===
|
|
69
|
-
`),0;if("boolean"==typeof
|
|
70
|
-
`),0;if(
|
|
71
|
-
`),0}if(e===
|
|
72
|
-
`),0;if(e===
|
|
73
|
-
`),0}if(e===
|
|
74
|
-
`),0}if(e===
|
|
75
|
-
`);let
|
|
76
|
-
`);let
|
|
402
|
+
`)}function t4(e){return"passed"===e.status&&e.attempts>1}function t6(e){return(Math.max(0,e)/1e3).toFixed(3)}function t7(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}let t9={[ea.boot]:se(ea.boot,({client:e,flags:t})=>e.devices.boot({...td(t),headless:t.headless})),[ea.push]:se(ea.push,({client:e,positionals:t,flags:s})=>e.apps.push({...td(s),app:sr(t[0],"push requires bundleOrPackage"),payload:sr(t[1],"push requires payloadOrJson")})),[ea.perf]:se(ea.perf,({client:e,flags:t})=>e.observability.perf(td(t))),[ea.click]:se(ea.click,({client:e,positionals:t,flags:s})=>e.interactions.click({...ss(t),...st(s),...td(s),count:s.count,intervalMs:s.intervalMs,holdMs:s.holdMs,jitterPx:s.jitterPx,doubleTap:s.doubleTap,button:s.clickButton})),[ea.get]:se(ea.get,({client:e,positionals:t,flags:s})=>e.interactions.get({...function(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=e.join(" ").trim();if(!t)throw new _("INVALID_ARGS","get requires @ref or selector expression");return{selector:t}}(t.slice(1)),...st(s),...td(s),format:function(e){if("text"===e||"attrs"===e)return e;throw new _("INVALID_ARGS","get only supports text or attrs")}(t[0])})),[ea.replay]:se(ea.replay,({client:e,positionals:t,flags:s})=>e.replay.run({...td(s),path:sr(t[0],"replay requires path"),update:s.replayUpdate,env:s.replayEnv})),[ea.test]:se(ea.test,({client:e,positionals:t,flags:s})=>(({json:s.json}).json||process.stderr.write("Running replay suite...\n"),e.replay.test({...td(s),paths:t,update:s.replayUpdate,env:s.replayEnv,failFast:s.failFast,timeoutMs:s.timeoutMs,retries:s.retries,artifactsDir:s.artifactsDir,reportJunit:s.reportJunit}))),[ea.batch]:se(ea.batch,({client:e,flags:t})=>e.batch.run({...td(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out})),[ea.press]:se(ea.press,({client:e,positionals:t,flags:s})=>e.interactions.press({...ss(t),...st(s),...td(s),count:s.count,intervalMs:s.intervalMs,holdMs:s.holdMs,jitterPx:s.jitterPx,doubleTap:s.doubleTap})),[ea.longPress]:se(ea.longPress,({client:e,positionals:t,flags:s})=>e.interactions.longPress({...td(s),x:Number(t[0]),y:Number(t[1]),durationMs:sa(t[2])})),[ea.swipe]:se(ea.swipe,({client:e,positionals:t,flags:s})=>e.interactions.swipe({...td(s),from:{x:Number(t[0]),y:Number(t[1])},to:{x:Number(t[2]),y:Number(t[3])},durationMs:sa(t[4]),count:s.count,pauseMs:s.pauseMs,pattern:s.pattern})),[ea.focus]:se(ea.focus,({client:e,positionals:t,flags:s})=>e.interactions.focus({...td(s),x:Number(t[0]),y:Number(t[1])})),[ea.type]:se(ea.type,({client:e,positionals:t,flags:s})=>e.interactions.type({...td(s),text:t.join(" "),delayMs:s.delayMs})),[ea.fill]:se(ea.fill,({client:e,positionals:t,flags:s})=>e.interactions.fill({...function(e){if(e[0]?.startsWith("@")){let t=e.length>=3?e.slice(2).join(" "):e.slice(1).join(" ");return{ref:e[0],label:e.length>=3?e[1]:void 0,text:t}}let t=ei(e,{preferTrailingValue:!0});return t?{selector:t.selectorExpression,text:t.rest.join(" ")}:{x:Number(e[0]),y:Number(e[1]),text:e.slice(2).join(" ")}}(t),...st(s),...td(s),delayMs:s.delayMs})),[ea.scroll]:se(ea.scroll,({client:e,positionals:t,flags:s})=>e.interactions.scroll({...td(s),direction:function(e){if("up"===e||"down"===e||"left"===e||"right"===e)return e;throw new _("INVALID_ARGS",`Unknown direction: ${String(e)}`)}(t[0]),amount:sa(t[1]),pixels:s.pixels})),[ea.pinch]:se(ea.pinch,({client:e,positionals:t,flags:s})=>e.interactions.pinch({...td(s),scale:Number(t[0]),x:sa(t[1]),y:sa(t[2])})),[ea.triggerAppEvent]:se(ea.triggerAppEvent,({client:e,positionals:t,flags:s})=>e.apps.triggerEvent({...td(s),event:sr(t[0],"trigger-app-event requires event"),payload:t[1]?function(e,t){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}throw new _("INVALID_ARGS",`${t} must be a JSON object`)}(t[1],"trigger-app-event payload"):void 0})),[ea.record]:se(ea.record,({client:e,positionals:t,flags:s})=>e.recording.record({...td(s),action:so(t[0],"record"),path:t[1],fps:s.fps,quality:s.quality,hideTouches:s.hideTouches})),[ea.trace]:se(ea.trace,({client:e,positionals:t,flags:s})=>e.recording.trace({...td(s),action:so(t[0],"trace"),path:t[1]})),[ea.logs]:se(ea.logs,({client:e,positionals:t,flags:s})=>e.observability.logs({...td(s),action:function(e){if(void 0!==e){if("path"===e||"start"===e||"stop"===e||"doctor"===e||"mark"===e||"clear"===e)return e;throw new _("INVALID_ARGS","logs requires path, start, stop, doctor, mark, or clear")}}(t[0]),message:t.slice(1).join(" ")||void 0,restart:s.restart})),[ea.network]:se(ea.network,({client:e,positionals:t,flags:s})=>e.observability.network({...td(s),action:function(e){if(void 0!==e){if("dump"===e||"log"===e)return e;throw new _("INVALID_ARGS","network requires dump or log")}}(t[0]),limit:sa(t[1]),include:s.networkInclude??function(e){if(void 0!==e){if("summary"===e||"headers"===e||"body"===e||"all"===e)return e;throw new _("INVALID_ARGS","network include mode must be summary, headers, body, or all")}}(t[2])})),[ea.find]:se(ea.find,({client:e,positionals:t,flags:s})=>{var o;return e.interactions.find({...function(e){let t=function(e){if("text"===e||"label"===e||"value"===e||"role"===e||"id"===e)return e}(e[0]),s=void 0!==t,o=s?e[1]:e[0],r=s?2:1,a=e[r];if(void 0===a)return{locator:t,query:sr(o,"find requires query")};if("get"===a){let s=e[r+1];if("text"===s)return{locator:t,query:sr(o,"find requires query"),action:"getText"};if("attrs"===s)return{locator:t,query:sr(o,"find requires query"),action:"getAttrs"};throw new _("INVALID_ARGS","find get only supports text or attrs")}if("wait"===a)return{locator:t,query:sr(o,"find requires query"),action:"wait",timeoutMs:sa(e[r+1])};if("fill"===a||"type"===a)return{locator:t,query:sr(o,"find requires query"),action:a,value:e.slice(r+1).join(" ")};if("click"===a||"focus"===a||"exists"===a)return{locator:t,query:sr(o,"find requires query"),action:a};throw new _("INVALID_ARGS",`Unsupported find action: ${a}`)}(t),...{depth:(o=s).snapshotDepth,raw:o.snapshotRaw},...td(s),first:s.findFirst,last:s.findLast})}),[ea.is]:se(ea.is,({client:e,positionals:t,flags:s})=>e.interactions.is({...function(e){let t=e[0],s=ei(e.slice(1),{preferTrailingValue:"text"===t});if(!s)throw new _("INVALID_ARGS","is requires a selector expression");if("text"===t)return{predicate:t,selector:s.selectorExpression,value:s.rest.join(" ")};if("visible"===t||"hidden"===t||"exists"===t||"editable"===t||"selected"===t)return{predicate:t,selector:s.selectorExpression};throw new _("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text")}(t),...st(s),...td(s)})),[ea.settings]:se(ea.settings,({client:e,positionals:t,flags:s})=>e.settings.update(function(e,t){let s=td(t),o=e[0],r=e[1];if(("wifi"===o||"airplane"===o||"location"===o||"animations"===o)&&("on"===r||"off"===r)||"appearance"===o&&("light"===r||"dark"===r||"toggle"===r)||("faceid"===o||"touchid"===o)&&("match"===r||"nonmatch"===r||"enroll"===r||"unenroll"===r)||"fingerprint"===o&&("match"===r||"nonmatch"===r))return{...s,setting:o,state:r};if("permission"===o&&("grant"===r||"deny"===r||"reset"===r))return{...s,setting:o,state:r,permission:function(e){switch(e){case"camera":case"microphone":case"photos":case"contacts":case"contacts-limited":case"notifications":case"calendar":case"location":case"location-always":case"media-library":case"motion":case"reminders":case"siri":case"accessibility":case"screen-recording":case"input-monitoring":return e;default:throw new _("INVALID_ARGS","settings permission requires a permission target.")}}(e[2]),mode:function(e){if(void 0===e||"full"===e||"limited"===e)return e;throw new _("INVALID_ARGS","settings permission mode must be full or limited.")}(e[3])};throw new _("INVALID_ARGS","Invalid settings arguments.")}(t,s)))};function se(e,t){return async({positionals:s,flags:o,client:r})=>{let a=await t({client:r,positionals:s,flags:o}),n=function(e,t,s,o){if(s.json)return e===ea.test?t5({suite:o,json:!0,reportJunit:s.reportJunit}):(eP({success:!0,data:o}),0);if(e===ea.test)return t5({suite:o,verbose:s.verbose,reportJunit:s.reportJunit});if(e===ea.batch)return!function(e){let t="number"==typeof e.total?e.total:0,s="number"==typeof e.executed?e.executed:0,o="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let a of(process.stdout.write(`Batch completed: ${s}/${t} steps${void 0!==o?` in ${o}ms`:""}
|
|
403
|
+
`),Array.isArray(e.results)?e.results:[])){var r;if(!a||"object"!=typeof a)continue;let e="number"==typeof a.step?a.step:void 0,t="string"==typeof a.command?a.command:"step",s=!1!==a.ok,o="number"==typeof a.durationMs?a.durationMs:void 0,n=a.data&&"object"==typeof a.data?a.data:void 0,i=a.error&&"object"==typeof a.error?a.error:void 0,l=s?H(n)??t:(r=i,("string"==typeof r?.message&&r.message.length>0?r.message:null)??t),c=void 0!==e?`${e}. `:"- ",p=void 0!==o?` (${o}ms)`:"";process.stdout.write(`${c}${s?"OK":"FAILED"} ${l}${p}
|
|
404
|
+
`)}}(o),0;if(e===ea.get){let e=t[0];if("text"===e)return process.stdout.write(`${"string"==typeof o.text?o.text:""}
|
|
405
|
+
`),0;if("attrs"===e)return process.stdout.write(`${JSON.stringify(o.node??{},null,2)}
|
|
406
|
+
`),0}if(e===ea.find){if("string"==typeof o.text)return process.stdout.write(`${o.text}
|
|
407
|
+
`),0;if("boolean"==typeof o.found)return process.stdout.write(`Found: ${o.found}
|
|
408
|
+
`),0;if(o.node)return process.stdout.write(`${JSON.stringify(o.node,null,2)}
|
|
409
|
+
`),0}if(e===ea.is)return process.stdout.write(`Passed: is ${o.predicate??"assertion"}
|
|
410
|
+
`),0;if(e===ea.boot){let e=o.platform??"unknown",t=o.device??o.id??"unknown";return process.stdout.write(`Boot ready: ${t} (${e})
|
|
411
|
+
`),0}if(e===ea.record){let e="string"==typeof o.outPath?o.outPath:"";return e&&process.stdout.write(`${e}
|
|
412
|
+
`),0}if(e===ea.logs)return function(e,t){let s="string"==typeof e.path?e.path:"";if(!s)return;process.stdout.write(`${s}
|
|
413
|
+
`);let o=["active","state","backend","sizeBytes"].map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ");o&&!t.json&&process.stderr.write(`${o}
|
|
414
|
+
`);let r=["started","stopped","marked","cleared","restarted","removedRotatedFiles"].map(t=>{let s=e[t];return!0===s?`${t}=true`:"number"==typeof s?`${t}=${s}`:""}).filter(Boolean).join(" ");if(r&&!t.json&&process.stderr.write(`${r}
|
|
77
415
|
`),e.hint&&!t.json&&process.stderr.write(`${e.hint}
|
|
78
416
|
`),Array.isArray(e.notes)&&!t.json)for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
|
|
79
|
-
`)}(
|
|
80
|
-
`);let s=Array.isArray(e.entries)?e.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",s="string"==typeof e.url?e.url:"<unknown-url>",
|
|
417
|
+
`)}(o,s),0;if(e===ea.network)return function(e){let t="string"==typeof e.path?e.path:"";t&&process.stdout.write(`${t}
|
|
418
|
+
`);let s=Array.isArray(e.entries)?e.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",s="string"==typeof e.url?e.url:"<unknown-url>",o="number"==typeof e.status?` status=${e.status}`:"",r="string"==typeof e.timestamp?`${e.timestamp} `:"",a="number"==typeof e.durationMs?` durationMs=${e.durationMs}`:"";process.stdout.write(`${r}${t} ${s}${o}${a}
|
|
81
419
|
`),"string"==typeof e.headers&&process.stdout.write(` headers: ${e.headers}
|
|
82
420
|
`),"string"==typeof e.requestBody&&process.stdout.write(` request: ${e.requestBody}
|
|
83
421
|
`),"string"==typeof e.responseBody&&process.stdout.write(` response: ${e.responseBody}
|
|
84
|
-
`)}let
|
|
422
|
+
`)}let o=["active","state","backend","include","scannedLines","matchedLines"].map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ");if(o&&process.stderr.write(`${o}
|
|
85
423
|
`),Array.isArray(e.notes))for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
|
|
86
|
-
`)}(
|
|
87
|
-
`),0}if(e===
|
|
88
|
-
`),0;let
|
|
89
|
-
`),0}(e,s,r,n);return 0!==a&&process.exit(a),!0}}function t6(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function t9(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=ea(e);return t?{selector:t.selectorExpression}:{x:Number(e[0]),y:Number(e[1])}}function t7(e,t){if("start"===e||"stop"===e)return e;throw new _("INVALID_ARGS",`${t} requires start|stop`)}function se(e,t){if(void 0===e||""===e)throw new _("INVALID_ARGS",t);return e}function st(e){return void 0===e?void 0:Number(e)}let ss={...{session:tp,[eo.devices]:td,[eo.apps]:th,"ensure-simulator":tf,metro:tg,install:tb,reinstall:tI,"install-from-source":tD,connect:tx,disconnect:tL,connection:tN,auth:tz,open:tS,close:t$,[eo.snapshot]:tW,[eo.screenshot]:tY,[eo.diff]:tZ},...tX,...t5};async function sr(e){let t=ss[e.command];return!!t&&await t(e)}async function so(e,t){let{flags:s}=e,r=function(e){if(!e?.metroProxyBaseUrl||"android"!==e.platform&&"android-instance"!==e.leaseBackend)return null;let t=e?.metroProxyBaseUrl,s=e?.metroBearerToken,r=e?.tenant,o=e?.runId,n=e?.leaseId,a=[];if(t||a.push("metroProxyBaseUrl"),s||a.push("metroBearerToken"),r||a.push("tenant"),o||a.push("runId"),n||a.push("leaseId"),a.length>0)throw new _("INVALID_ARGS",`react-devtools remote Android bridge requires ${a.join(", ")}.`,{missing:a});if(!t||!s||!r||!o||!n)throw new _("INVALID_ARGS","react-devtools remote Android bridge is incomplete.");return{serverBaseUrl:t,bearerToken:s,tenantId:r,runId:o,leaseId:n}}(s);if(!r)return t();let o=e.stateDir??process.cwd(),n=e.session??s?.session??"default",a=s?.remoteConfig??`${r.tenantId}:${r.runId}:${r.leaseId}`;await eJ({projectRoot:e.cwd??process.cwd(),stateDir:o,serverBaseUrl:r.serverBaseUrl,bearerToken:r.bearerToken,bridgeScope:{tenantId:r.tenantId,runId:r.runId,leaseId:r.leaseId},session:n,profileKey:a,consumerKey:n,env:e.env??process.env});try{return await t()}finally{await ez({projectRoot:e.cwd??process.cwd(),stateDir:o,profileKey:a,consumerKey:n})}}async function sn(e,t={}){let s=t.cwd??process.cwd(),r=t.env??process.env;return await so(t,async()=>(await X("npm",["exec","--yes","--package","agent-react-devtools@0.4.0","--","agent-react-devtools",...e],{cwd:s,env:r,allowFailure:!0,onStdoutChunk:e=>{process.stdout.write(e)},onStderrChunk:e=>{process.stderr.write(e)}})).exitCode)}function sa(e,t={}){let s=si(t),r={...e};return s.defaultPlatform&&void 0===r.platform&&(r.platform=s.defaultPlatform),r}function si(e){var t,s,r,o;let n,a=e.env??process.env,i=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new _("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(a.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??a.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:i,lockPolicy:(s=e.policyOverrides,r=a,o=l,(n=s?.sessionLock??s?.sessionLockConflicts??sl(r.AGENT_DEVICE_SESSION_LOCK)??sl(r.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(s?.sessionLocked===!0||w(r.AGENT_DEVICE_SESSION_LOCKED)||o?"reject":void 0))}}function sl(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new _("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let sc=$.map(e=>e.key),su={sendToDaemon:en},sp=new Set(["launchUrl","metroBearerToken","metroKind","metroListenHost","metroNoInstallDeps","metroNoReuseExisting","metroPreparePort","metroProbeTimeoutMs","metroProjectRoot","metroProxyBaseUrl","metroPublicBaseUrl","metroRuntimeFile","metroStartupTimeoutMs","metroStatusHost"]),sd=new Set(["connect","connection","close","devices","disconnect","ensure-simulator","metro","session"]);async function sm(e,t=su){let s=P(),r=F(),o=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),n=e.includes("--json"),a=function(e){for(let t=0;t<e.length;t+=1){let s=e[t];if(s.startsWith("--session=")){let e=s.slice(10).trim();return e.length>0?e:null}if("--session"===s){let s=e[t+1]?.trim();if(s&&!s.startsWith("-"))return s;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await K({session:a,requestId:s,command:e[0],debug:o},async()=>{var a,l,c,p,d,m,f,g,y,w,v,b,I,D,A,$,L;let R,E,O,P,T,U,M;try{let t,s,r,o,n,h,b,I;a={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},s=null,r=[],o=[],n=!0;for(let l=0;l<e.length;l+=1){var a,i;let c=e[l];if(n&&"--"===c){n=!1;continue}if(!n){s?r.push(c):s=eE(c);continue}let u=c.startsWith("--"),p=c.startsWith("-")&&c.length>1;if(!u&&!p){s?r.push(c):s=eE(c);continue}let[d,m]=u?eC(c):[c,void 0],f=ef.get(d);if(a=s,i=f,"react-devtools"===a&&(!i||!eL(i.key,a))){r.push(c);continue}if(!f){if(function(e,t,s){var r;if(r=s,!/^-\d+(\.\d+)?$/.test(r)||!e)return!1;let o=eh(e);return!o||!!o.allowsExtraPositionals||0!==o.positionalArgs.length&&(t.length<o.positionalArgs.length||o.positionalArgs.some(e=>e.includes("?")))}(s,r,c)){s?r.push(c):s=c;continue}throw new _("INVALID_ARGS",`Unknown flag: ${d}`)}let g=function(e,t,s,r){if(void 0!==e.setValue){if(void 0!==s)throw new _("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==s)throw new _("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==s){if(0===s.trim().length)throw new _("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===r||eR(r)||!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("\\"))}(r)?{value:!0,consumeNext:!1}:{value:r,consumeNext:!0}}let o=s??r;if(void 0===o||void 0===s&&eR(o))throw new _("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:o,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(o))throw new _("INVALID_ARGS",`Invalid ${e_(t)}: ${o}`);return{value:o,consumeNext:void 0===s}}let n=Number(o);if(!Number.isFinite(n)||"number"==typeof e.min&&n<e.min||"number"==typeof e.max&&n>e.max)throw new _("INVALID_ARGS",`Invalid ${e_(t)}: ${o}`);return{value:Math.floor(n),consumeNext:void 0===s}}(f,d,m,e[l+1]);g.consumeNext&&(l+=1);let h=t[f.key];if(f.multiple){let e=Array.isArray(h)?[...h,g.value]:void 0===h?[g.value]:[h,g.value];t[f.key]=e}else t[f.key]=g.value;o.push({key:f.key,token:d})}return{command:s,positionals:r,flags:t,warnings:[],providedFlags:o}}(e),s=a?.env??process.env,r=a?.cwd??process.cwd(),p=t.command,o=null!==p&&(l={remoteConfig:t.flags.remoteConfig,cwd:r,env:s}).remoteConfig?{...function(e){let t={};for(let s of sc){let r=e[s];void 0!==r&&(t[s]=r)}return t}(k({configPath:l.remoteConfig,cwd:l.cwd,env:l.env}).profile),remoteConfig:l.remoteConfig}:{},b=el((n=(c={command:t.command,cwd:r,cliFlags:t.flags,env:s}).env??process.env,h=el({},function(e){let t={};for(let s of e)el(t,function(e,t){let s,r;if(!u.existsSync(e)){if(t)throw new _("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{s=u.readFileSync(e,"utf8")}catch(t){throw new _("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{r=JSON.parse(s)}catch(t){throw new _("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new _("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let s={};for(let[r,o]of Object.entries(e)){if("installSource"===r){s.installSource=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new _("INVALID_ARGS",`${t} installSource must be an object.`);if("github-actions-artifact"!==tv(e.type,`${t} installSource.type`))throw new _("INVALID_ARGS",`${t} installSource.type must be "github-actions-artifact".`);let{owner:s,repo:r}=tw(tv(e.repo,`${t} installSource.repo`),`${t} installSource.repo`);return ty(s,r,e.artifact,`${t} installSource.artifact`)}(o,t);continue}let e=ex.get(r);if(!e)throw new _("INVALID_ARGS",`Unknown config key "${r}" in ${t}.`);if(!e.config.enabled)throw new _("INVALID_ARGS",`Unsupported config key "${r}" in ${t}.`);s[r]=x(eN(e),o,t,r)}return s}(r,`config file ${e}`)}(s.path,s.required));return t}((d=c.cwd,m=c.cliFlags.config,f=n,(I=m??f.AGENT_DEVICE_CONFIG)?[{path:(g=I,y=d,w=f,ee(g,{cwd:y,env:w})),required:!0}]:[{path:(v=f,i.join(et("~",{env:v}),".agent-device","config.json")),required:!1},{path:i.resolve(d,"agent-device.json"),required:!1}]))),el(h,function(e,t){var s,r,o;let n={};for(let a of e$.filter(e=>e.config.enabled&&e.supportsCommand(t))){if("installSource"===a.key)continue;let t=a.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(n[a.key]=(s=t.value,r=`environment variable ${t.name}`,o=t.name,x(eN(a),s,r,o)))}return n}(n,c.command))),o),R={...function(e,t){let s=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),r=[...e.warnings],o=el({json:!1,help:!1,version:!1},t?.defaultFlags??{});el(o,e.flags);let n=eh(e.command),a=e.providedFlags.filter(t=>!eL(t.key,e.command));if(a.length>0){var i,l;let t=a.map(e=>e.token),n=(i=e.command,l=t,i?1===l.length?`Flag ${l[0]} is not supported for command ${i}.`:`Flags ${l.join(", ")} are not supported for command ${i}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(s)throw new _("INVALID_ARGS",n);for(let e of(r.push(`${n} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),a))delete o[e.key]}for(let t of Object.keys(o))void 0!==o[t]&&(eL(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 _("INVALID_ARGS","back accepts only one explicit mode flag: use either --in-app or --system.")}(e),n?.defaults)for(let[e,t]of Object.entries(n.defaults))void 0===o[e]&&(o[e]=t);if("batch"===e.command&&1!=+!!o.steps+ +!!o.stepsFile)throw new _("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,...s}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:s,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:o,warnings:r})}(t,{strictFlags:a?.strictFlags,defaultFlags:b}),providedFlags:t.providedFlags}}catch(t){V({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=C(t,{diagnosticId:B().diagnosticId,logPath:J({force:!0})??void 0});n?eO({success:!1,error:e}):eP(e,{showDetails:o}),process.exit(1);return}for(let e of R.warnings)process.stderr.write(`Warning: ${e}
|
|
90
|
-
`);
|
|
91
|
-
`),process.exit(0));let F="help"===
|
|
92
|
-
`),process.exit(0));let t=function(e){var t,s;let r=
|
|
424
|
+
`)}(o),0;if(e===ea.click||e===ea.press){let e=o.ref??"",t=o.x,s=o.y;if(e&&"number"==typeof t&&"number"==typeof s)return process.stdout.write(`Tapped @${e} (${t}, ${s})
|
|
425
|
+
`),0}if(e===ea.perf)return process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
426
|
+
`),0;let r=H(o);return r&&process.stdout.write(`${r}
|
|
427
|
+
`),0}(e,s,o,a);return 0!==n&&process.exit(n),!0}}function st(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function ss(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ")||void 0};let t=ei(e);return t?{selector:t.selectorExpression}:{x:Number(e[0]),y:Number(e[1])}}function so(e,t){if("start"===e||"stop"===e)return e;throw new _("INVALID_ARGS",`${t} requires start|stop`)}function sr(e,t){if(void 0===e||""===e)throw new _("INVALID_ARGS",t);return e}function sa(e){return void 0===e?void 0:Number(e)}let sn={...{session:tf,[ea.devices]:tg,[ea.apps]:tw,"ensure-simulator":tv,metro:ty,install:tA,reinstall:tD,"install-from-source":tS,connect:tR,disconnect:tC,connection:t_,auth:tX,open:tL,close:tN,[ea.snapshot]:tQ,[ea.screenshot]:t0,[ea.diff]:t1},...t2,...t9};async function si(e){let t=sn[e.command];return!!t&&await t(e)}async function sl(e,t){let{flags:s}=e,o=function(e){if(!e?.metroProxyBaseUrl||"android"!==e.platform&&"android-instance"!==e.leaseBackend)return null;let t=e?.metroProxyBaseUrl,s=e?.metroBearerToken,o=e?.tenant,r=e?.runId,a=e?.leaseId,n=[];if(t||n.push("metroProxyBaseUrl"),s||n.push("metroBearerToken"),o||n.push("tenant"),r||n.push("runId"),a||n.push("leaseId"),n.length>0)throw new _("INVALID_ARGS",`react-devtools remote Android bridge requires ${n.join(", ")}.`,{missing:n});if(!t||!s||!o||!r||!a)throw new _("INVALID_ARGS","react-devtools remote Android bridge is incomplete.");return{serverBaseUrl:t,bearerToken:s,tenantId:o,runId:r,leaseId:a}}(s);if(!o)return t();let r=e.stateDir??process.cwd(),a=e.session??s?.session??"default",n=s?.remoteConfig??`${o.tenantId}:${o.runId}:${o.leaseId}`;await eY({projectRoot:e.cwd??process.cwd(),stateDir:r,serverBaseUrl:o.serverBaseUrl,bearerToken:o.bearerToken,bridgeScope:{tenantId:o.tenantId,runId:o.runId,leaseId:o.leaseId},session:a,profileKey:n,consumerKey:a,env:e.env??process.env});try{return await t()}finally{await eZ({projectRoot:e.cwd??process.cwd(),stateDir:r,profileKey:n,consumerKey:a})}}async function sc(e,t={}){let s=t.cwd??process.cwd(),o=t.env??process.env;return await sl(t,async()=>(await Q("npm",["exec","--yes","--package","agent-react-devtools@0.4.0","--","agent-react-devtools",...e],{cwd:s,env:o,allowFailure:!0,onStdoutChunk:e=>{process.stdout.write(e)},onStderrChunk:e=>{process.stderr.write(e)}})).exitCode)}function sp(e,t={}){let s=sd(t),o={...e};return s.defaultPlatform&&void 0===o.platform&&(o.platform=s.defaultPlatform),o}function sd(e){var t,s,o,r;let a,n=e.env??process.env,i=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new _("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(n.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??n.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:i,lockPolicy:(s=e.policyOverrides,o=n,r=l,(a=s?.sessionLock??s?.sessionLockConflicts??su(o.AGENT_DEVICE_SESSION_LOCK)??su(o.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(s?.sessionLocked===!0||w(o.AGENT_DEVICE_SESSION_LOCKED)||r?"reject":void 0))}}function su(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new _("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let sm=$.map(e=>e.key),sf={sendToDaemon:en},sg=new Set(["launchUrl","metroBearerToken","metroKind","metroListenHost","metroNoInstallDeps","metroNoReuseExisting","metroPreparePort","metroProbeTimeoutMs","metroProjectRoot","metroProxyBaseUrl","metroPublicBaseUrl","metroRuntimeFile","metroStartupTimeoutMs","metroStatusHost"]),sh=new Set(["connect","connection","close","disconnect","ensure-simulator","metro","session"]);async function sv(e,t=sf){let s=P(),o=B(),r=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),a=e.includes("--json"),n=function(e){for(let t=0;t<e.length;t+=1){let s=e[t];if(s.startsWith("--session=")){let e=s.slice(10).trim();return e.length>0?e:null}if("--session"===s){let s=e[t+1]?.trim();if(s&&!s.startsWith("-"))return s;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await J({session:n,requestId:s,command:e[0],debug:r},async()=>{var n,i,c,p,u,m,f,g,h,y,w,b,k,I,A,D,$;let N,E,O,U,P,T,M;try{let t,s,o,r,a,v,b,k;n={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},s=null,o=[],r=[],a=!0;for(let l=0;l<e.length;l+=1){var n,i;let c=e[l];if(a&&"--"===c){a=!1;continue}if(!a){s?o.push(c):s=eU(c);continue}let p=c.startsWith("--"),d=c.startsWith("-")&&c.length>1;if(!p&&!d){s?o.push(c):s=eU(c);continue}let[u,m]=p?e_(c):[c,void 0],f=eh.get(u);if(n=s,i=f,"react-devtools"===n&&(!i||!eR(i.key,n))){o.push(c);continue}if(!f){if(function(e,t,s){var o;if(o=s,!/^-\d+(\.\d+)?$/.test(o)||!e)return!1;let r=ey(e);return!r||!!r.allowsExtraPositionals||0!==r.positionalArgs.length&&(t.length<r.positionalArgs.length||r.positionalArgs.some(e=>e.includes("?")))}(s,o,c)){s?o.push(c):s=c;continue}throw new _("INVALID_ARGS",`Unknown flag: ${u}`)}let g=function(e,t,s,o){if(void 0!==e.setValue){if(void 0!==s)throw new _("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==s)throw new _("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==s){if(0===s.trim().length)throw new _("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===o||eO(o)||!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("\\"))}(o)?{value:!0,consumeNext:!1}:{value:o,consumeNext:!0}}let r=s??o;if(void 0===r||void 0===s&&eO(r))throw new _("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:r,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(r))throw new _("INVALID_ARGS",`Invalid ${eE(t)}: ${r}`);return{value:r,consumeNext:void 0===s}}let a=Number(r);if(!Number.isFinite(a)||"number"==typeof e.min&&a<e.min||"number"==typeof e.max&&a>e.max)throw new _("INVALID_ARGS",`Invalid ${eE(t)}: ${r}`);return{value:Math.floor(a),consumeNext:void 0===s}}(f,u,m,e[l+1]);g.consumeNext&&(l+=1);let h=t[f.key];if(f.multiple){let e=Array.isArray(h)?[...h,g.value]:void 0===h?[g.value]:[h,g.value];t[f.key]=e}else t[f.key]=g.value;r.push({key:f.key,token:u})}return{command:s,positionals:o,flags:t,warnings:[],providedFlags:r}}(e),s=n?.env??process.env,o=n?.cwd??process.cwd(),p=t.command,r=null!==p&&(i={remoteConfig:t.flags.remoteConfig,cwd:o,env:s}).remoteConfig?{...function(e){let t={};for(let s of sm){let o=e[s];void 0!==o&&(t[s]=o)}return t}(S({configPath:i.remoteConfig,cwd:i.cwd,env:i.env}).profile),remoteConfig:i.remoteConfig}:{},b=ec((a=(c={command:t.command,cwd:o,cliFlags:t.flags,env:s}).env??process.env,v=ec({},function(e){let t={};for(let s of e)ec(t,function(e,t){let s,o;if(!d.existsSync(e)){if(t)throw new _("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{s=d.readFileSync(e,"utf8")}catch(t){throw new _("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{o=JSON.parse(s)}catch(t){throw new _("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!o||"object"!=typeof o||Array.isArray(o))throw new _("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let s={};for(let[o,r]of Object.entries(e)){if("installSource"===o){s.installSource=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new _("INVALID_ARGS",`${t} installSource must be an object.`);if("github-actions-artifact"!==tI(e.type,`${t} installSource.type`))throw new _("INVALID_ARGS",`${t} installSource.type must be "github-actions-artifact".`);let{owner:s,repo:o}=tk(tI(e.repo,`${t} installSource.repo`),`${t} installSource.repo`);return tb(s,o,e.artifact,`${t} installSource.artifact`)}(r,t);continue}let e=eN.get(o);if(!e)throw new _("INVALID_ARGS",`Unknown config key "${o}" in ${t}.`);if(!e.config.enabled)throw new _("INVALID_ARGS",`Unsupported config key "${o}" in ${t}.`);s[o]=L(eC(e),r,t,o)}return s}(o,`config file ${e}`)}(s.path,s.required));return t}((u=c.cwd,m=c.cliFlags.config,f=a,(k=m??f.AGENT_DEVICE_CONFIG)?[{path:(g=k,h=u,y=f,et(g,{cwd:h,env:y})),required:!0}]:[{path:(w=f,l.join(es("~",{env:w}),".agent-device","config.json")),required:!1},{path:l.resolve(u,"agent-device.json"),required:!1}]))),ec(v,function(e,t){var s,o,r;let a={};for(let n of eL.filter(e=>e.config.enabled&&e.supportsCommand(t))){if("installSource"===n.key)continue;let t=n.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(a[n.key]=(s=t.value,o=`environment variable ${t.name}`,r=t.name,L(eC(n),s,o,r)))}return a}(a,c.command))),r),N={...function(e,t){let s=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),o=[...e.warnings],r=ec({json:!1,help:!1,version:!1},t?.defaultFlags??{});ec(r,e.flags);let a=ey(e.command),n=e.providedFlags.filter(t=>!eR(t.key,e.command));if(n.length>0){var i,l;let t=n.map(e=>e.token),a=(i=e.command,l=t,i?1===l.length?`Flag ${l[0]} is not supported for command ${i}.`:`Flags ${l.join(", ")} are not supported for command ${i}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(s)throw new _("INVALID_ARGS",a);for(let e of(o.push(`${a} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),n))delete r[e.key]}for(let t of Object.keys(r))void 0!==r[t]&&(eR(t,e.command)||delete r[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 _("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===r[e]&&(r[e]=t);if("batch"===e.command&&1!=+!!r.steps+ +!!r.stepsFile)throw new _("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,...s}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:s,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:r,warnings:o})}(t,{strictFlags:n?.strictFlags,defaultFlags:b}),providedFlags:t.providedFlags}}catch(t){V({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=C(t,{diagnosticId:j().diagnosticId,logPath:z({force:!0})??void 0});a?eP({success:!1,error:e}):eT(e,{showDetails:r}),process.exit(1);return}for(let e of N.warnings)process.stderr.write(`Warning: ${e}
|
|
428
|
+
`);N.flags.version&&(process.stdout.write(`${o}
|
|
429
|
+
`),process.exit(0));let F="help"===N.command,B=N.flags.help;if(F||B){F&&N.positionals.length>1&&(eT(new _("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=F?N.positionals[0]:N.command;e||(process.stdout.write(`${ek}
|
|
430
|
+
`),process.exit(0));let t=function(e){var t,s;let o,r=(o=eu[e])?`${o.body}
|
|
431
|
+
|
|
432
|
+
Related:
|
|
433
|
+
agent-device help command list and global flags
|
|
434
|
+
agent-device help <command> command-specific flags
|
|
435
|
+
agent-device help workflow normal app automation loop
|
|
436
|
+
`:null;if(r)return r;let a=ey(e);if(!a)return null;let n=(t=e,(s=a).usageOverride?s.usageOverride:[t,...s.positionalArgs.map(eb),...s.allowedFlags.flatMap(e=>(ev.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),i=eI(new Set(a.allowedFlags)),l=eI(ef),c=[];return i.length>0&&c.push(eA("Command flags:",i)),c.push(eA("Global flags:",l)),`agent-device ${n}
|
|
93
437
|
|
|
94
|
-
${
|
|
438
|
+
${a.helpDescription}
|
|
95
439
|
|
|
96
440
|
Usage:
|
|
97
|
-
agent-device ${
|
|
441
|
+
agent-device ${n}
|
|
98
442
|
|
|
99
|
-
${
|
|
100
|
-
`}(
|
|
101
|
-
`),process.exit(1)}
|
|
102
|
-
`),process.exit(1));let{command:G,positionals:
|
|
443
|
+
${c.join("\n\n")}
|
|
444
|
+
`}(eU(e));t&&(process.stdout.write(t),process.exit(0)),eT(new _("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${ek}
|
|
445
|
+
`),process.exit(1)}N.command||(process.stdout.write(`${ek}
|
|
446
|
+
`),process.exit(1));let{command:G,positionals:q}=N,H=new Set(N.providedFlags.map(e=>e.key));try{O=(E=sd({policyOverrides:N.flags,configuredPlatform:N.flags.platform,configuredSession:N.flags.session})).lockPolicy?{...N.flags}:sp(N.flags,{policyOverrides:N.flags,configuredPlatform:N.flags.platform,configuredSession:N.flags.session}),U=K(O.stateDir),P=O.session??"default",b={command:G,explicitFlagKeys:H,stateDir:U.baseDir,session:P,remoteConfig:O.remoteConfig},M=(T="connect"===b.command||"connection"===b.command?null:function(e){let t=e.validateRemoteConfigHash??!0,s=e.remoteConfig?x({configPath:e.remoteConfig,cwd:e.cwd,env:e.env}):void 0,o=eX(e)??(e.allowActiveFallback?e8({stateDir:e.stateDir}):null);if(!o||s&&o.remoteConfigPath!==s)return null;if(t&&e2(o.remoteConfigPath)!==o.remoteConfigHash)throw new _("INVALID_ARGS","Active remote connection config changed. Run agent-device connect --force to refresh it.",{remoteConfig:o.remoteConfigPath});let r=function(e,t){try{return S({configPath:e.remoteConfigPath,cwd:t.cwd,env:t.env}).profile}catch(e){if(!1===t.validateRemoteConfigHash)return{};throw e}}(o,e);return{runtime:o.runtime,flags:{...r,remoteConfig:o.remoteConfigPath,daemonBaseUrl:o.daemon?.baseUrl??r.daemonBaseUrl,daemonTransport:o.daemon?.transport??r.daemonTransport,daemonServerMode:o.daemon?.serverMode??r.daemonServerMode,tenant:o.tenant,sessionIsolation:"tenant",runId:o.runId,leaseId:o.leaseId,leaseBackend:o.leaseBackend,session:o.session,platform:o.platform??r.platform,target:o.target??r.target}}}({stateDir:b.stateDir,session:b.session,remoteConfig:b.remoteConfig,cwd:process.cwd(),env:process.env,allowActiveFallback:!b.explicitFlagKeys.has("session")&&(!b.remoteConfig||"disconnect"===b.command),validateRemoteConfigHash:"disconnect"!==b.command}))?function(e,t,s){let o={...e};for(let[e,r]of Object.entries(t))void 0!==r&&(s.has(e)||(o[e]=r));return o}(O,T.flags,H):O}catch(t){let e=C(R(t),{diagnosticId:j().diagnosticId,logPath:z({force:!0})??void 0});N.flags.json?eP({success:!1,error:e}):eT(e,{showDetails:N.flags.verbose}),process.exit(1);return}let J=null;try{let e;if("react-devtools"===G){let e=await sc(q,{flags:M,stateDir:U.baseDir,session:M.session??P,cwd:process.cwd(),env:process.env});process.exit(e);return}el({command:G,currentVersion:o,stateDir:U.baseDir,flags:M});let r=T?.runtime,a=(e,t)=>({session:e.session??P,requestId:s,stateDir:e.stateDir,daemonBaseUrl:e.daemonBaseUrl,daemonAuthToken:e.daemonAuthToken,daemonTransport:e.daemonTransport,daemonServerMode:e.daemonServerMode,tenant:e.tenant,sessionIsolation:e.sessionIsolation,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,runtime:t,lockPolicy:E.lockPolicy,lockPlatform:E.defaultPlatform,cwd:process.cwd(),debug:!!e.verbose});if("batch"===G){if(q.length>0)throw new _("INVALID_ARGS","batch does not accept positional arguments.");e=function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=d.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new _("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return v(t)}(O)}if(k=G,"auth"!==k&&"connection"!==k&&(M=(await tT({command:G,flags:M,stateDir:U.baseDir,env:process.env})).flags),M.remoteConfig&&(I=G,!sh.has(I))){let s=er(a(M,r),{transport:t.sendToDaemon}),o=await tt({command:G,flags:M,client:s,runtime:r,batchSteps:e,forceRuntimePrepare:function(e){for(let t of sg)if(e.has(t))return!0;return!1}(H)});M=o.flags,r=o.runtime}A={command:G,flags:M,runtime:r,explicitFlagKeys:H,hadConnectionDefaults:!!T},!("open"===A.command&&!A.runtime&&!A.flags.bundleUrl&&!A.flags.metroHost&&!A.flags.metroPort&&!A.flags.remoteConfig&&!A.hadConnectionDefaults&&((D=A.explicitFlagKeys).has("daemonBaseUrl")||D.has("daemonTransport")||D.has("tenant")||D.has("sessionIsolation")||D.has("runId")||D.has("leaseId")||D.has("leaseBackend")))||process.stderr.write("Warning: open is using explicit remote daemon or tenant flags without saved Metro runtime hints. React Native apps may launch without bundle/runtime hints; prefer connect --remote-config <path> first or pass --remote-config <path> on this command.\n");let n=M.daemonBaseUrl;J=!M.verbose||M.json||n?null:function(e){try{let t=0,s=!1,o=setInterval(()=>{if(!s&&d.existsSync(e))try{let s=d.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let o=d.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);d.readSync(o,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{d.closeSync(o)}}catch{}},200);return()=>{s=!0,clearInterval(o)}}catch{return null}}(U.logPath);let i=er(a(M,r),{transport:t.sendToDaemon});if("batch"===G){if(!e)throw new _("INVALID_ARGS","batch requires --steps or --steps-file.");let t=e.map((e,t)=>({...e,flags:E.lockPolicy&&void 0===O.platform?{...e.flags??{}}:sp(e.flags??{},{policyOverrides:M,configuredPlatform:M.platform,configuredSession:M.session,inheritedPlatform:M.platform})}));if(await si({command:G,positionals:q,flags:{...M,batchSteps:t},client:i}))return}else if("runtime"===G)throw new _("INVALID_ARGS","runtime command was removed. Use connect --remote-config <path> for remote runs, or metro prepare --remote-config <path> for inspection.");else if(await si({command:G,positionals:q,flags:M,client:i}))return;throw new _("INVALID_ARGS",`Unknown command: ${G}`)}catch(s){let e=R(s),t=C(e,{diagnosticId:j().diagnosticId,logPath:z({force:!0})??void 0});if("close"===G&&"COMMAND_FAILED"===($=e).code&&($.details?.kind==="daemon_startup_failed"||$.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof $.details?.infoPath||"string"==typeof $.details?.lockPath))){M.json&&eP({success:!0,data:{closed:"session",source:"no-daemon"}});return}if(M.json)eP({success:!1,error:t});else if(eT(t,{showDetails:M.verbose}),M.verbose)try{let e=U.logPath;if(d.existsSync(e)){let t=d.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
|
|
103
447
|
[daemon log]
|
|
104
448
|
${s}
|
|
105
|
-
`)}}catch{}
|
|
449
|
+
`)}}catch{}J&&J(),process.exit(1)}finally{J&&J()}})}p(process.argv[1]??"").href===import.meta.url&&sv(process.argv.slice(2)).catch(e=>{eT(C(R(e)),{showDetails:!0}),process.exit(1)}),sv(process.argv.slice(2));
|