agent-device 0.17.10 → 0.18.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.
Files changed (160) hide show
  1. package/README.md +3 -2
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.10.apk → agent-device-android-multitouch-helper-0.18.1.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.1.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.10.manifest.json → agent-device-android-multitouch-helper-0.18.1.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.10.apk → agent-device-android-snapshot-helper-0.18.1.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.1.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.10.manifest.json → agent-device-android-snapshot-helper-0.18.1.manifest.json} +6 -6
  8. package/apple-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +156 -0
  9. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +10 -16
  10. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -0
  11. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +3 -1
  12. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +2 -0
  13. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +2 -4
  14. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +9 -36
  15. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +2 -0
  16. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +2 -0
  17. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +2 -0
  18. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +2 -0
  19. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +0 -1
  20. package/dist/src/1986.js +1 -0
  21. package/dist/src/2748.js +1 -1
  22. package/dist/src/2948.js +21 -21
  23. package/dist/src/314.js +1 -1
  24. package/dist/src/3340.js +8 -7
  25. package/dist/src/432.js +4 -4
  26. package/dist/src/4418.js +1 -1
  27. package/dist/src/4428.js +3 -3
  28. package/dist/src/485.js +1 -0
  29. package/dist/src/495.js +5 -0
  30. package/dist/src/5484.js +1 -1
  31. package/dist/src/5643.js +1 -0
  32. package/dist/src/587.js +1 -1
  33. package/dist/src/5913.js +4 -0
  34. package/dist/src/6849.js +1 -0
  35. package/dist/src/6918.js +1 -1
  36. package/dist/src/6967.js +1 -0
  37. package/dist/src/760.js +1 -0
  38. package/dist/src/7871.js +1 -0
  39. package/dist/src/8225.js +1 -1
  40. package/dist/src/8391.js +1 -0
  41. package/dist/src/8404.js +2 -0
  42. package/dist/src/8414.js +2 -0
  43. package/dist/src/8875.js +1 -1
  44. package/dist/src/8936.js +1 -0
  45. package/dist/src/9414.js +1 -0
  46. package/dist/src/9581.js +5 -5
  47. package/dist/src/9624.js +1 -1
  48. package/dist/src/9722.js +37 -37
  49. package/dist/src/android-adb.d.ts +19 -54
  50. package/dist/src/android-adb.js +1 -1
  51. package/dist/src/android.js +5 -5
  52. package/dist/src/apps.js +9 -11
  53. package/dist/src/audio-probe.js +1 -0
  54. package/dist/src/batch.d.ts +50 -25
  55. package/dist/src/batch.js +1 -1
  56. package/dist/src/cli-help.js +104 -37
  57. package/dist/src/cli.js +36 -27
  58. package/dist/src/contracts.d.ts +46 -122
  59. package/dist/src/contracts.js +1 -1
  60. package/dist/src/debug-symbols.js +3 -0
  61. package/dist/src/devices.js +1 -1
  62. package/dist/src/devices~1.js +1 -1
  63. package/dist/src/devices~2.js +1 -1
  64. package/dist/src/find.js +1 -1
  65. package/dist/src/finders.d.ts +2 -6
  66. package/dist/src/finders.js +1 -1
  67. package/dist/src/generic.js +1 -9
  68. package/dist/src/handler-utils.js +1 -0
  69. package/dist/src/index.d.ts +500 -182
  70. package/dist/src/index.js +1 -1
  71. package/dist/src/input-actions.js +1 -1
  72. package/dist/src/input-actions~1.js +1 -1
  73. package/dist/src/install-source.d.ts +0 -26
  74. package/dist/src/install-source.js +1 -1
  75. package/dist/src/interaction.js +1 -1
  76. package/dist/src/interactor.js +1 -0
  77. package/dist/src/internal/bin.js +1 -1
  78. package/dist/src/internal/companion-tunnel.js +1 -1
  79. package/dist/src/internal/png-worker.js +1 -1
  80. package/dist/src/lease.js +1 -1
  81. package/dist/src/linux.js +1 -1
  82. package/dist/src/metro.d.ts +10 -134
  83. package/dist/src/metro.js +1 -1
  84. package/dist/src/notifications.js +1 -1
  85. package/dist/src/react-native.js +1 -1
  86. package/dist/src/record-trace-recording.js +3 -3
  87. package/dist/src/record-trace.js +1 -1
  88. package/dist/src/remote-config.d.ts +28 -24
  89. package/dist/src/remote-config.js +1 -1
  90. package/dist/src/runner-sequence.js +1 -0
  91. package/dist/src/selector-runtime.js +1 -1
  92. package/dist/src/selectors.d.ts +7 -3
  93. package/dist/src/selectors.js +1 -1
  94. package/dist/src/server.js +2 -2
  95. package/dist/src/session.js +11 -8
  96. package/dist/src/simulator.js +2 -0
  97. package/dist/src/snapshot.js +2 -2
  98. package/dist/src/web.js +1 -1
  99. package/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +297 -0
  100. package/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +30 -0
  101. package/package.json +15 -11
  102. package/server.json +2 -2
  103. package/android-multitouch-helper/README.md +0 -41
  104. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.10.apk.sha256 +0 -1
  105. package/android-snapshot-helper/README.md +0 -88
  106. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.10.apk.sha256 +0 -1
  107. package/dist/src/2133.js +0 -1
  108. package/dist/src/2577.js +0 -1
  109. package/dist/src/2954.js +0 -2
  110. package/dist/src/4291.js +0 -1
  111. package/dist/src/4723.js +0 -1
  112. package/dist/src/5628.js +0 -1
  113. package/dist/src/5910.js +0 -2
  114. package/dist/src/6024.js +0 -1
  115. package/dist/src/733.js +0 -1
  116. package/dist/src/7394.js +0 -6
  117. package/dist/src/8275.js +0 -2
  118. package/dist/src/8358.js +0 -4
  119. package/dist/src/9919.js +0 -6
  120. package/dist/src/android-snapshot-helper.d.ts +0 -359
  121. package/dist/src/android-snapshot-helper.js +0 -1
  122. package/dist/src/apple.js +0 -1
  123. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.swift +0 -17
  124. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AccentColor.colorset/Contents.json +0 -11
  125. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/Contents.json +0 -36
  126. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/logo.jpg +0 -0
  127. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Contents.json +0 -6
  128. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/Contents.json +0 -21
  129. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/logo.jpg +0 -0
  130. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/Contents.json +0 -21
  131. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/powered-by.png +0 -0
  132. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/ContentView.swift +0 -34
  133. package/ios-runner/README.md +0 -53
  134. package/ios-runner/RUNNER_PROTOCOL.md +0 -76
  135. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -0
  136. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +0 -0
  137. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +0 -0
  138. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests.entitlements +0 -0
  139. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +0 -0
  140. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +0 -0
  141. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.h +0 -0
  142. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.m +0 -0
  143. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +0 -0
  144. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +0 -0
  145. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +0 -0
  146. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -0
  147. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +0 -0
  148. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +0 -0
  149. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +0 -0
  150. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +0 -0
  151. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +0 -0
  152. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +0 -0
  153. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -0
  154. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +0 -0
  155. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan +0 -0
  156. /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +0 -0
  157. /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -0
  158. /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -0
  159. /package/dist/src/{4069.js → 4917.js} +0 -0
  160. /package/dist/src/{9836.js → 893.js} +0 -0
@@ -1,4 +1,7 @@
1
- import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{asAppError as i,normalizeError as o,AppError as s}from"./733.js";import{startAndroidSimpleperfProfile as l,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as u,dispatchCommand as p,sessionMatchesScope as d,selectorTargetsSessionDevice as c,appendAppLogMarker as f,resolveCommandDevice as m,hasRuntimeTransportHints as h,sampleAppleFramePerf as g,captureAppleMemorySnapshot as w,getSessionCommandKind as y,inferFillText as v,startAndroidPerfettoTrace as A,stopIosRunnerSession as S,captureAndroidHeapSnapshot as I,stopAppleXctracePerfCapture as b,resolvePublicSessionName as _,writeAppleXctracePerfReport as k,requireSessionOrExplicitSelector as N,cleanupUploadedArtifact as D,resolveSessionRequestLogPath as x,ANDROID_FRAME_SAMPLE_METHOD as R,refreshSessionDeviceIfNeeded as M,buildAppleFrameSamplingMetadata as P,createRequestCanceledError as L,registerRequestAbort as O,errorResponse as E,settleIosSimulator as C,readReplayTestActionProgress as $,buildSessionRecoveryHint as V,applyRuntimeHintsToApp as U,withKeyedLock as F,resolveTargetDevice as q,getAppLogPathMetadata as G,uniqueStrings as T,setSessionSnapshot as B,sampleAndroidMemoryPerf as H,shutdownDeviceTarget as K,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as j,sampleAndroidCpuPerf as z,clearRuntimeHintsFromApp as W,ANDROID_HPROF_SNAPSHOT_METHOD as J,startAppleXctracePerfCapture as X,buildAppleSamplingMetadata as Y,getSnapshotReferenceFrame as Z,clearAppLogFiles as Q,handleCloseCommand as ee,prepareIosRunner as et,session_device_utils_hasExplicitSessionFlag as er,readSessionNetworkCapture as ea,cleanupRetainedMaterializedPaths as en,isImplicitSessionScopeConflict as ei,resolveSessionRunnerLogPath as eo,ANDROID_CPU_SAMPLE_DESCRIPTION as es,buildSnapshotState as el,resolveLogBackend as eu,stopAndroidSimpleperfProfile as ep,context_contextFromFlags as ed,listDeviceInventory as ec,SessionStore as ef,ANDROID_CPU_SAMPLE_METHOD as em,buildAppleMemorySnapshotSupport as eh,stopAndroidPerfettoTrace as eg,isRequestCanceled as ew,resolveRequestTrackingId as ey,retainMaterializedPaths as ev,runAppLogDoctor as eA,resolvePayloadInput as eS,prepareUploadedArtifact as eI,resetAndroidFramePerfStats as eb,ANDROID_FRAME_SAMPLE_DESCRIPTION as e_,withReplayTestActionProgress as ek,markRequestCanceled as eN,stopAppLog as eD,resolveImplicitSessionScope as ex,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eR,ensureDeviceReady as eM,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eP,prewarmIosRunnerSession as eL,clearRequestCanceled as eO,resolveAndroidEmulatorAvdName as eE,writeAndroidSimpleperfReport as eC,resolveFrontmostMacOsApp as e$,isCommandSupportedOnDevice as eV,sampleApplePerfMetrics as eU,sampleAndroidFramePerf as eF,ANDROID_MEMORY_SAMPLE_METHOD as eq,getRequestSignal as eG,markAndroidSnapshotFreshness as eT,startAppLog as eB,emitRequestProgress as eH}from"./9722.js";import{isPerfAction as eK,isPerfSubject as ej,pointFromPercent as ez,PERF_AREA_ERROR_MESSAGE as eW,buildSwipeGesturePlan as eJ,PERF_ACTION_ERROR_MESSAGE as eX,buildSnapshotDisplayLines as eY,isPerfKind as eZ,isPerfMemoryKind as eQ,pointInsideRect as e0,successText as e1,clampGesturePoint as e3,resolveDeployResultTarget as e2,PERF_MEMORY_KIND_ERROR_MESSAGE as e5,PERF_KIND_ERROR_MESSAGE as e4,isPerfArea as e6,LOG_ACTION_VALUES as e8,withSuccessText as e7,clampToRange as e9,parseSessionSurface as te,resolveInstallFromSourceResultTarget as tt,readReactNativeOverlayActionNodes as tr,detectReactNativeOverlay as ta,PERF_SUBJECT_ERROR_MESSAGE as tn}from"./2948.js";import{isApplePlatform as ti,resolveAppleSimulatorSetPathForSelector as to,normalizePlatformSelector as ts,matchesPlatformSelector as tl}from"./5910.js";import{resolveIosSimulatorDeviceSetPath as tu,classifyAndroidAppTarget as tp,resolveIosDeviceDeepLinkBundleId as td,isInfrastructureBootFailureReason as tc,isWebUrl as tf,resolveAndroidSerialAllowlist as tm,isDeepLinkTarget as th,formatAndroidInstalledPackageRequiredMessage as tg,listAndroidApps as tw}from"./3340.js";import{getDiagnosticsMeta as ty,emitDiagnostic as tv}from"./432.js";import{runBatch as tA,mergeParentFlags as tS}from"./6918.js";import{assertResolvedAppsFilter as tI}from"./2748.js";import{listIosApps as tb}from"./apps.js";import{resolveWebProvider as t_}from"./provider.js";import{NETWORK_INCLUDE_MODES as tk}from"./4291.js";import{unsupportedCommand as tN,readEnvMap as tD,parseReplayScriptDetailed as tx,readReplayShellEnvSource as tR,normalizeCommandList as tM,normalizePlatform as tP,readReplayCliEnvEntries as tL,parseMaestroYamlDocuments as tO,parseAbsolutePoint as tE,readReplayScriptMetadata as tC,parseReplayCliEnvEntries as t$,collectReplayShellEnv as tV,support_action as tU,isPlainRecord as tF,requireAppId as tq,assertOnlyKeys as tG,resolveMaestroString as tT,requireStringValue as tB,parseMaestroPoint as tH,unsupportedMaestroSyntax as tK,readTimeoutMs as tj,writeReplayScript as tz,buildReplayVarScope as tW,resolveReplayAction as tJ,mergeReplayVarScopeValues as tX}from"./4428.js";import{runCmdSync as tY}from"./8875.js";import{readSnapshotDiagnosticsSummary as tZ,summarizeSnapshotTimingSamples as tQ,mergeSnapshotDiagnostics as t0}from"./8358.js";import{resolveSelectorChain as t1,extractNodeText as t3,findSnapshotAncestor as t2,isDescendantOfSnapshotNode as t5,splitIsSelectorArgs as t4,buildSelectorChainForNode as t6,buildSnapshotNodeByIndex as t8,matchesSelector as t7,normalizeType as t9}from"./9836.js";import{formatScriptActionSummary as re,evaluateIsPredicate as rt,isTouchTargetCommand as rr}from"./2577.js";import{splitSelectorFromArgs as ra,normalizeText as rn,tryParseSelectorChain as ri,parseSelectorChain as ro}from"./587.js";import{sleep as rs}from"./5560.js";import{handleRecordCommand as rl}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as ru,PUBLIC_COMMANDS as rp}from"./2133.js";import{trimRuntimeValue as rd}from"./5628.js";var rc={};async function rf(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new s("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await eM(e.session.device),e.session.device}if(!r)throw new s("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await q(e.flags??{});return await eM(a),a}async function rm(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await ev({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rh(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rg(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new s("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new s("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new s("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new s("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new s("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:eI(i,t.meta?.tenantId)},cleanup:()=>{D(i)}}:{source:e,cleanup:()=>{}}),l=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new s("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rf({session:n,flags:t.flags});if(!eV("install",u))return E("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let p=eG(t.meta?.requestId),d=async(e,i)=>{let s;try{var u;s=await rm({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),p=e7(o,(u=o,`Installed: ${tt(u)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:a.flags??{},result:n})}({session:n,sessionStore:a,req:t,data:p}),{ok:!0,data:p}}catch(e){throw s&&await en(s.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===u.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:p});return await d(r,async t=>{if(await e(u,r.installablePath),!r.bundleId)throw new s("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...rh(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./3340.js"),m=await c(o.source,{signal:p});return await d(m,async e=>{let t=await f(u,m.installablePath,m.packageName);if(!t)throw new s("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./3340.js"),a=r(t);return{...rh(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rw(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new s("INVALID_ARGS","release_materialized_paths requires a materializationId");return await en(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}e.r(rc),e.d(rc,{handleSessionCommands:()=>oV});let ry=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function rv(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function rA(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return rd(e)}}function rS(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new s("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function rI(e){if("ios"===e||"android"===e)return e}async function rb(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!h(r)||h(a)||await W({device:n.device,appId:n.appBundleId})}async function r_(e){var t,r;let{req:a,sessionName:n,sessionStore:i}=e,o=(a.positionals?.[0]??"show").toLowerCase(),s=i.get(n),l=i.getRuntimeHints(n);if(!["set","show","clear"].includes(o))return E("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){h(l)&&s?.appBundleId&&await W({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(n);return{ok:!0,data:{session:n,cleared:e}}}if("show"===o)return{ok:!0,data:{session:n,configured:!!l,runtime:l}};let u=rI(ts(a.flags?.platform)??l?.platform??s?.device.platform);if(!u)return E("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return E("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${s.device.platform}.`);let p={platform:(t=a.flags,r={platform:u,metroHost:rd(t?.metroHost),metroPort:rS(t?.metroPort),bundleUrl:rd(t?.bundleUrl),launchUrl:rd(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===rv(p)?E("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,p),{ok:!0,data:{session:n,configured:!0,runtime:p}})}let rk="open-command-roundtrip",rN="Not implemented for this platform in this release.";function rD(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let rx=new Set(["app","desktop","frontmost-app"]);async function rR(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function rM(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return th(t)?"macos"===e.platform?void 0:"device"===e.kind?td(r,t):tf(t)?void 0:r??await rP(e,t):await rL(e,t)}async function rP(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rL(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rO(e,t){if(!("android"!==e.platform||!t||th(t)))try{let{resolveAndroidApp:r}=await import("./3340.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function rE(e,t,r){if(r||"android"!==e.platform||!t||!th(t))return r;try{let{getAndroidAppState:t}=await import("./3340.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function rC(e,t,r,a){return await rM(e,t,r)??await a(e,t)??("android"===e.platform&&t&&th(t)?r:void 0)}function r$(e){return E("INVALID_ARGS",e)}function rV(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=te(r);if(!rx.has(e))throw new s("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new s("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new s("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?te(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new s("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return E(e instanceof s?e.code:"INVALID_ARGS",String(e.message))}}function rU(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&th(r)?r$("open --relaunch does not support URL targets."):"app"!==a?r$("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tp(r)?r$(tg(r)):null:null}async function rF(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:o,openTarget:l,existingSession:u}=e;await eM(n,{deviceHub:t.flags?.deviceHub===!0});let{appBundleId:p,appName:d}=await rq({device:n,surface:o,openTarget:l,existingAppBundleId:u?.appBundleId}),c=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new s("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!ry.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${ry.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new s("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new s("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:rA(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new s("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return rS(e)}}(t.metroPort),bundleUrl:rA(t.bundleUrl,"bundleUrl"),launchUrl:rA(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:rI(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=rI(n);if(a.platform&&r&&!i)throw new s("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new s("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&rv(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!c.ok)return{type:"response",response:c};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=c.data;await rb({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:d,runtime:c.data.runtime}}}async function rq(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await rR(r);return{appBundleId:i.appBundleId??await rC(t,a,n,rO),appName:i.appName??a}}let rG=new Map;async function rT(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await S(t.id),await p(t,"close",[r],a,n),await C(t,300)}async function rB(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=n?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||th(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,a=ed(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function rH(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,S=g,I=Date.now(),b={};if(v&&c){let e=S??c,t=Date.now();await rT({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...ed(u,o.flags,S??y?.appBundleId,A)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let k=Date.now();await U({device:d,appId:S,runtime:w}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-k);let N="ios"===d.platform&&"app"===h&&f.length>0,D={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir},R=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(N&&S&&(b.runnerPrewarmKind="session",b.runnerPrewarmScheduled=!0,R)){i=eL(d,{...D,propagateError:!0});let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let M=Date.now(),P=await rK({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:S,appName:m,existingSession:y});if("response"===P.type)return P.response;let O=P.session??y;await p(d,"open",f,o.flags?.out,{...ed(u,o.flags,S)}),b.openDispatchDurationMs=Math.max(0,Date.now()-M);let $=Date.now();if(await rB({runtime:w,device:d,req:o,logPath:u,appBundleId:S,traceLogPath:A,openPositionals:f}),b.launchUrlDurationMs=Math.max(0,Date.now()-$),N&&S&&!i&&(i=eL(d,D)),v&&i&&!0!==b.runnerPrewarmWaited){let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==b.runnerPrewarmWaited&&(b.runnerPrewarmWaited=!1);S=await rE(d,c,S),"android"===d.platform&&S&&await eb(d,S);let V=c?(t=S,{durationMs:Math.max(0,Date.now()-M),measuredAt:new Date().toISOString(),method:rk,appTarget:c,appBundleId:t}):void 0,F=Date.now();if(await C(d,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-F),ew(o.meta?.requestId)){let e=L();return E(e.code,e.message,e.details)}y&&eT(y,"open",y.snapshot);let q=rD({existingSession:O,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??ex(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===rv(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let G=l.ensureSessionDir(s),T=x(G,o.meta?.requestId??ty().requestId);b.totalDurationMs=Math.max(0,Date.now()-I);let B=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:p,runtime:d,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),d&&c(d)>0&&(f.runtime=d),p&&(f.platform=p.platform,f.target=p.target??"mobile",f.device=p.name,f.id=p.id,f.kind=p.kind,"android"===p.platform&&(f.serial=p.id)),p?.platform==="ios"&&(f.device_udid=p.id,f.ios_simulator_device_set=p.simulatorSetPath??null),{...f,...e1(`Opened: ${i??o??t}`)}}({sessionName:q.name,sessionStateDir:G,runnerLogPath:eo(G),requestLogPath:T,appName:m,appBundleId:S,surface:h,startup:V,timing:b,device:d,runtime:w,runtimeHintCount:rv});return l.recordAction(q,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:B}),l.set(s,q),{ok:!0,data:B}}async function rK(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let p=rD({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??ex(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});a.set(r,p);let d=await u(p);return d&&!d.ok?{type:"response",response:d}:{type:"session",session:a.get(r)??p}}async function rj(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=rV(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?r$("open --relaunch requires an app name or an active session app."):r$("Session already active. Close it first or pass a new --session name.");let u=rU({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let p=await M(i.device),d=await rF({req:t,sessionName:r,sessionStore:n,device:p,surface:l,openTarget:s,existingSession:i});return"response"===d.type?d.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:p,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return r$("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&th(r)?r$("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tp(r)?r$(tg(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await q(t.flags??{}),p=rV(u,t.flags?.surface,s);if("string"!=typeof p)return p;let d=rU({shouldRelaunch:o,openTarget:s,surface:p,device:u});return d||await F(rG,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return ei(t,e)?E("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.name,hint:"Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target."}):E("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:V(e,"device-in-use")});let i=await rF({req:t,sessionName:r,sessionStore:n,device:u,surface:p,openTarget:s});return"response"===i.type?i.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:p})})}let rz={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await import("./apps.js");return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await import("./3340.js");return await a(e,t,r)}},rW={ios:async(e,t,r)=>{let{installIosApp:a}=await import("./apps.js"),n=await a(e,r,{appIdentifierHint:t});return{bundleId:n.bundleId,appName:n.appName,launchTarget:n.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await import("./3340.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function rJ(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=N(a,s,l);if(u)return u;let p=r.positionals?.[0]?.trim(),d=r.positionals?.[1]?.trim();if(!p||!d)return E("INVALID_ARGS",`${a} requires: ${a} <app> <path-to-app-binary>`);let c=r.meta?.uploadedArtifactId;try{var f;let e,n=c?eI(c,r.meta?.tenantId):ef.expandHome(d);if(!t.existsSync(n))return E("INVALID_ARGS",`App binary not found: ${n}`);let u=await m({session:s,flags:l,ensureReady:!1});if(!eV(a,u))return E("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,p,n),r=t.bundleId;e=r?{app:p,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,p,n),r=t.package;e=r?{app:p,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let h=e7(e,(f=e,`Installed: ${f.appName??e2(f)}`));return s&&i.recordAction(s,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:h??{}}),{ok:!0,data:h}}finally{c&&D(c)}}async function rX(e,t,r){return await tA(e,t,r)}async function rY(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=ex(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>d(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:eo(t),platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tm(t.flags?.androidDeviceAllowlist),r=ts(t.flags?.platform),a=to({simulatorSetPath:tu(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ec({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?ti(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=N(t.command,e,n);if(i)return i;let o=await m({session:e,flags:n,ensureReady:!0});if(!eV("apps",o))return E("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=tI(t.flags?.appsFilter);return ti(o.platform)?{ok:!0,data:{apps:(await tb(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tw(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function rZ(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let rQ='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',r0='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function r1(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=ts(i.platform);if(!n&&er(i))return E("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=N("appstate",n,i);if(s)return s;let l=ti(n?.device.platform)&&c(i,n);if("ios"===o&&!l)return E("SESSION_NOT_FOUND",rQ);if("macos"===o&&!l)return E("SESSION_NOT_FOUND",r0);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return E("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await m({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return E("SESSION_NOT_FOUND",rQ);if("macos"===u.platform)return E("SESSION_NOT_FOUND",r0);if("web"===u.platform)return E("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:p}=await import("./3340.js"),d=await p(u);return{ok:!0,data:{platform:"android",package:d.package,activity:d.activity}}}async function r3(e){let{req:t,sessionName:r,sessionStore:a}=e;if("boot"===t.command){let e,n=a.get(r),o=t.flags??{},s=N(t.command,n,o);if(s)return s;let l="android"===(ts(o.platform)??n?.device.platform),u=!0===o.headless;if(u&&!l)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=eE({flags:o,sessionDevice:n?.device}),d=l&&!!p,c=!1;try{e=await m({session:n,flags:o,ensureReady:!1})}catch(r){let t=i(r);if(l&&u&&!p&&"DEVICE_NOT_FOUND"===t.code)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!p)throw r;e=await rZ({avdName:p,serial:o.serial,headless:u}),c=!0}if(o.target&&(e.target??"mobile")!==o.target)return E("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${o.target}.`);if(l&&u){if("android"!==e.platform||"emulator"!==e.kind)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=eE({flags:o,sessionDevice:n?.device,resolvedDevice:e});if(!t)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await rZ({avdName:t,serial:o.serial,headless:!0})}await eM(e)}else("android"!==e.platform||!0!==e.booted)&&await eM(e);return eV("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:E("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var n;let e,i=a.get(r),o=t.flags??{},s=N(t.command,i,o);if(s)return s;let l=await m({ensureReady:!1,flags:o,session:i});if(!eV("shutdown",l))return E("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.id)return E("DEVICE_IN_USE","Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.",{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await K(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:E(u.error?.code??"COMMAND_FAILED",(n=u,(e=n.error?.message??n.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await r1({req:t,sessionName:r,sessionStore:a}):null}async function r2(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===rk&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:rk,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:rk,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:rk},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:r6(),memory:{available:!1,reason:rN},cpu:{available:!1,reason:rN}}},sampling:{startup:{method:rk,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:eq,description:eP,unit:"kB"},cpu:{method:em,description:es,unit:"percent"},fps:{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:Y(a.device)}});return at(e)&&(e.appBundleId?"android"===e.device.platform?await r8(u,e,e.appBundleId,t):await r7(u,e,e.appBundleId):(n=u,l=ar(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function r5(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:r6()},sampling:{fps:"android"===(a=r).device.platform?{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:P(a.device)}};return at(e)&&(e.appBundleId?await ae(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:ar(e)}),n}async function r4(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:eq,description:eP,unit:"kB",topConsumerLimit:5}:Y(a.device).memory,snapshot:"android"===r.device.platform?{method:J,description:j,defaultKind:"android-hprof",artifactOnly:!0}:{method:eR,description:u,defaultKind:"memgraph",artifactOnly:!0}}};if(!at(e)){if("snapshot"===t.action){let r=al(e,t.kind);return n.artifact=au(e,r),n.support=ad(n.artifact.support)??ap(e),n}return n.metrics={memory:{available:!1,reason:rN}},n}return"sample"===t.action?n.metrics={memory:await ai(e,t)}:(n.artifact=await as(e,t),n.support=ad(n.artifact.support)??ap(e)),n}function r6(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function r8(e,t,r,a){let n=await aa(t,r,a);r9(e,t,n)}async function r7(e,t,r){let a=await an(t,r);r9(e,t,a)}function r9(e,t,r){e.metrics.memory=af(r.memory),e.metrics.cpu=af(r.cpu),e.metrics.fps=am(af(r.fps),t)}async function ae(e,t,r,a){let n="android"===t.device.platform?await ac(eF(t.device,r,{adb:a.androidAdb})):await ac(g(t.device,r));e.metrics.fps=am(af(n),t)}function at(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function ar(e){return"android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first."}async function aa(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([H(e.device,t,a),z(e.device,t,a),eF(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function an(e,t){let r=await ac(g(e.device,t)),a=await ac(eU(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function ai(e,t){return e.appBundleId?af("android"===e.device.platform?await ac(H(e.device,e.appBundleId,{adb:t.androidAdb})):await ac(ao(e))):{available:!1,reason:ar(e)}}async function ao(e){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e));return(await eU(e.device,e.appBundleId)).memory}async function as(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=al(e,t.kind),n=function(e,t){if(e.out)return ef.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?au(e,a):await I(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?au(e,a):await w(e.device,e.appBundleId,n)}function al(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function au(e,t){var r,a;let n=ap(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:"ios"===r.device.platform||"macos"===r.device.platform?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function ap(e){return"android"===e.device.platform?{platform:e.device.platform,defaultKind:"android-hprof",androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:"Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice."}:"ios"!==e.device.platform&&"macos"!==e.device.platform?{platform:e.device.platform,defaultKind:"memgraph",androidHprof:!1,memgraph:!1,heapprofd:!1,reason:"Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.",hint:"Use perf memory sample where supported, or switch to a platform with memory artifact support.",heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}:{...eh(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function ad(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function ac(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function af(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function am(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=ah((a=e).windowStartedAt),i=ah(a.windowEndedAt)??ah(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function ah(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function ag(e){var t,r,a,n,i,s,l,u,p,d;let c,f,m,h,g,w,y=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,s=c,f=aw(i,1),m=aw(i,2),h=aw(i,3),ej(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?E("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?E("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:s}:E("INVALID_ARGS",tn)):(u=t,p=c,g=aw(u,1),w=aw(u,2),"start"!==(d=g)&&"stop"!==d?E("INVALID_ARGS","perf trace action must be start or stop"):eZ(w)?"perfetto"!==w?E("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:p}:E("INVALID_ARGS",e4)));if(!y.ok)return y;let{session:v}=e;if("android"!==v.device.platform)return E("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!v.appBundleId)return E("COMMAND_FAILED","No Android app package is associated with this session.",{hint:"Run open <app> first so perf can resolve the package and process identity."});try{let t="cpu"===y.area?await aA(e,v,v.appBundleId,y):await aS(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function aw(e,t){return(e.positionals?.[t]??"").toLowerCase()}function ay(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function av(e,t,a){var n,i,o;let s;return t?ef.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function aA(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"cpu.perf.data"),i=await l(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new s("COMMAND_FAILED","Stop the Android Simpleperf CPU profile before generating a report.",{hint:"Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf."})}(n);let r=av(e,a.outPath,"cpu-report.json");return await eC(t.device,n,r,{adb:e.androidAdbExecutor})}let i=ab(e,a.outPath,n),o=await ep(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}async function aS(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"app.perfetto-trace"),i=await A(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"trace",a.kind),i=ab(e,a.outPath,n),o=await eg(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}function aI(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new s("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.":"Run perf trace stop --kind perfetto before starting another Android native perf capture."})}function ab(e,t,r){return t?av(e,t,r.outPath):r.outPath}function a_(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new s("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.":"Run perf trace start --kind perfetto first, then stop in the same session."})}async function ak(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return E("INVALID_ARGS","perf cpu requires profile");let t=aN(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=aD(e[3]);return r.ok?{ok:!0,area:"cpu",mode:"cpu-profile",action:t.value,kind:"xctrace",template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:r}(r):"trace"===a?function(e){let t=aN(e[1],"perf trace",!1);if(!t.ok)return t;let r=aD(e[2]);return r.ok?{ok:!0,area:"trace",mode:"trace",action:t.value,kind:"xctrace",template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:r}(r):E("INVALID_ARGS",eW));if(!n.ok)return n;if("android"===t.device.platform)return E("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if("ios"!==t.device.platform&&"macos"!==t.device.platform)return E("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return E("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await ax(e,t,n);if("stop"===n.action)return await aR(e,t,n);return await aM(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function aN(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:E("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function aD(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:E("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function ax(e,t,r){if(t.applePerf?.active)return E("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=aL(e,r),i=await X({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=aO("started",i);return aP(e,t,o),{ok:!0,data:o}}async function aR(e,t,r){var a,n,o,s,l,u,p;let d,c=t.applePerf?.active;if(!c)return E("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ef.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{d=await b(c,f)}catch(r){throw a=r,i(a).details?.captureCleanedUp===!0&&(n=e,(o=t).applePerf={...o.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,o)),r}s=e,l=t,u=d,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(p=u).mode?{lastProfileTracePath:p.outPath,lastProfileTemplate:p.template}:{lastTracePath:p.outPath}},s.sessionStore.set(s.sessionName,l);let m=aO("stopped",d);return aP(e,t,m),{ok:!0,data:m}}async function aM(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return E("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=aL(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await k({tracePath:ef.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return aP(e,t,s),{ok:!0,data:s}}function aP(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function aL(e,t){if(t.outPath)return ef.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function aO(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}let aE=`logs requires ${e8.slice(0,-1).join(", ")}, or ${e8.at(-1)}`,aC=["dump","log"],a$=`network requires ${aC.join(" or ")}`,aV=`network include mode must be one of: ${tk.join(", ")}`,aU={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=G(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eu(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>aH(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",f(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>aK(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>aj(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>az(e,t,r)};async function aF(e){let{req:t}=e;return"perf"===t.command?aq(e):"logs"===t.command?aB(e):"network"===t.command?aW(e):null}async function aq(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,l=n.get(a);if(!l)return E("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===l.device.platform?await ag({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await ak(e,l);let p=function(e){var t,r,a,n,i,l,u,p,d,c;let f,m,h=e6(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return E("INVALID_ARGS",eW);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=eK(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return E("INVALID_ARGS",eX);let w=function(e){if(void 0!==e)return"string"==typeof e&&eZ(e)?e:new s("INVALID_ARGS",e4)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?aT(r)?void 0:E("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?E("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,l=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return E("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=l,p=n,d=i,u?"memory"!==p||"snapshot"!==d?E("INVALID_ARGS","--kind is only supported with perf memory snapshot"):eQ(u)?void 0:E("INVALID_ARGS",e5):void 0)));return y||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!p.ok)return p;if(p.native)return await ak(e,l);try{return{ok:!0,data:await aG(e,l,p)}}catch(e){return{ok:!1,error:o(e)}}}async function aG(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await r4(t,{action:function(e){if(aT(e))return e;throw new s("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await r5(t,{androidAdb:i}):await r2(t,{androidAdb:i})}function aT(e){return"sample"===e||"snapshot"===e}async function aB(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return E("SESSION_NOT_FOUND","logs requires an active session");if(!eV("logs",s.device))return E("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,e8.includes(r)?a&&"clear"!==r?E("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:E("INVALID_ARGS",aE));return l.ok?await aU[l.action]({...e,session:s,restart:l.restart}):l}async function aH(e,t,r){let a=r.resolveAppLogPath(t),n=await eA(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function aK(e,t,r,a){if(e.appLog&&!a)return E("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:Q(n)};let i=e.appBundleId;if(!i)return E("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eD(e.appLog);let s=Q(n),l=r.resolveAppLogPidPath(t);try{let a=await eB(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...s,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:o(a)}}}async function aj(e,t,r){if(e.appLog)return E("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return E("INVALID_ARGS","logs start requires an app session; run open <app> first");let a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await eB(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:o(e)}}}async function az(e,t,r){if(!e.appLog)return E("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eD(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function aW(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return E("SESSION_NOT_FOUND","network requires an active session");if(!eV("network",n.device))return E("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!aC.includes(i))return E("INVALID_ARGS",a$);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return E("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return E("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return tk.includes(a)?{ok:!0,include:a}:E("INVALID_ARGS",aV)}(t);return s.ok?{ok:!0,session:n,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await aJ({include:r,maxEntries:a});let i=await ea({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function aJ(e){let t=t_();if(!t.dumpNetwork)return E("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:o(e)}}}function aX(e,t,r){var a,n;if(null==e)return tU("open",[tT(tq(t,"launchApp"),r)]);if("string"==typeof e)return tU("open",[tT(e,r)]);if(!tF(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tG(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),a0(e,"permissions"),a0(e,"clearKeychain");let i=tT("string"==typeof e.appId?e.appId:tq(t,"launchApp"),r),o=(a=e,n=r,[...aZ(a.arguments,"launchApp.arguments",n),...aZ(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return tU("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function aY(e,t,r){if(null==e)return tU("close",[tT(tq(t,"stopApp"),r)]);if("string"==typeof e)return tU("close",[tT(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function aZ(e,t,r){if(null==e)return[];if("string"==typeof e)return[tT(e,r)];if(Array.isArray(e))return e.map((e,a)=>aQ(e,`${t}[${a}]`,r));if(tF(e))return Object.entries(e).flatMap(([e,a])=>[tT(e,r),aQ(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function aQ(e,t,r){if("string"==typeof e)return tT(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new s("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function a0(e,t){if(void 0!==e[t])throw tK(`Maestro launchApp field "${t}" is not supported yet.`)}let a1="__maestroRunScript",a3="__maestroAssertVisible",a2="__maestroAssertNotVisible",a5="__maestroPressEnter",a4="__maestroWaitForAnimationToEnd",a6="__maestroScrollUntilVisible",a8="__maestroSwipeScreen",a7="__maestroSwipeOn",a9="__maestroTapOn",ne="__maestroTapPointPercent";function nt(e){if(null==e)return tU("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return tU("type",["\b".repeat(e)]);if(!tF(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tG(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return tU("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new s("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return tU("type",["\b".repeat(e.charactersToErase)])}function nr(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function na(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tK(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nn(e){return na(e,"swipe direction")}function ni(e,t,r=[],a){if("string"==typeof e)return no(tT(e,a));if(!tF(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tG(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(nl("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(nl("selected",String(e.selected))),"string"==typeof e.id&&n.push(nl("id",tT(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return no(tT(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(nl("label",tT(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new s("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function no(e,t=[]){return[[nl("label",e),...t].join(" "),[nl("text",e),...t].join(" "),[nl("id",e),...t].join(" ")].join(" || ")}function ns(e){let t=nr(e.duration);return t?[t]:[]}function nl(e,t){return`${e}=${JSON.stringify(t)}`}function nu(e){var t,r;if(!tF(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function np(e){let t=nu(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nd(e){let t={doubleTap:!0};return tF(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class nc{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new s("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new s("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new s("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new s("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function nf(e,t,r){return{...tU(e,t),replayControl:r}}function nm(e,t,r){let a="string"==typeof e?tT(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new s("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let nh=`
1
+ import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{access as i}from"node:fs/promises";import{asAppError as o,normalizeError as s,AppError as l}from"./485.js";import{runXcrun as u,installProviderDeviceInstallablePath as d,LOCAL_DEVICE_INVENTORY_PLATFORM_SELECTORS as p,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as c,dispatchCommand as f,sessionMatchesScope as m,appendAppLogMarker as h,countDeviceInventoryByGroup as g,startAndroidSimpleperfProfile as w,installProviderDeviceApp as v,sampleAppleFramePerf as y,captureAppleMemorySnapshot as A,isHostSystemAudioProbeDevice as b,getSessionCommandKind as S,inferFillText as _,startAndroidPerfettoTrace as I,stopIosRunnerSession as k,captureAndroidHeapSnapshot as N,stopAppleXctracePerfCapture as D,resolvePublicSessionName as x,writeAppleXctracePerfReport as R,registerBuiltinPlatformPlugins as M,stopSessionApplePerfCapture as P,cleanupUploadedArtifact as L,resolveSessionRequestLogPath as O,ANDROID_FRAME_SAMPLE_METHOD as $,buildAppleFrameSamplingMetadata as C,createRequestCanceledError as E,stopAppleRunnerForClose as V,isActiveProviderDevice as F,registerRequestAbort as q,errorResponse as T,runHostSystemAudioProbeCommand as U,readReplayTestActionProgress as G,configureProviderPortReverse as H,releaseSessionLease as K,removeProviderPortReverse as B,withKeyedLock as j,buildSessionRecoveryHint as z,resolveTargetDevice as W,getAppLogPathMetadata as J,sampleAndroidMemoryPerf as Y,requireCommandSupported as X,uniqueStrings as Q,setSessionSnapshot as Z,stopSessionAudioProbe as ee,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as et,sampleAndroidCpuPerf as er,ANDROID_HPROF_SNAPSHOT_METHOD as ea,buildDeviceInventoryRequestFromFlags as en,startAppleXctracePerfCapture as ei,buildAppleSamplingMetadata as eo,cleanupRetainedMaterializedPathsForSession as es,clearAppLogFiles as el,tryGetPlugin as eu,getSnapshotReferenceFrame as ed,prepareIosRunner as ep,hasExplicitDeviceSelector as ec,stopSessionAndroidNativePerfCapture as ef,readSessionNetworkCapture as em,cleanupRetainedMaterializedPaths as eh,isImplicitSessionScopeConflict as eg,resolveSessionRunnerLogPath as ew,ANDROID_CPU_SAMPLE_DESCRIPTION as ev,buildSnapshotState as ey,resolveLogBackend as eA,resolveSessionLeaseForRequest as eb,stopAndroidSimpleperfProfile as eS,context_contextFromFlags as e_,listDeviceInventory as eI,SessionStore as ek,ANDROID_CPU_SAMPLE_METHOD as eN,buildAppleMemorySnapshotSupport as eD,stopAndroidPerfettoTrace as ex,isRequestCanceled as eR,resolveRequestTrackingId as eM,retainMaterializedPaths as eP,runAppLogDoctor as eL,resolvePayloadInput as eO,prepareUploadedArtifact as e$,LeaseRegistry as eC,resetAndroidFramePerfStats as eE,listSessionSelectorConflicts as eV,stopSessionAppLog as eF,stopSessionAndroidSnapshotHelper as eq,withReplayTestActionProgress as eT,ANDROID_FRAME_SAMPLE_DESCRIPTION as eU,markRequestCanceled as eG,stopAppLog as eH,resolveImplicitSessionScope as eK,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eB,ANDROID_MEMORY_SAMPLE_DESCRIPTION as ej,writeAndroidSimpleperfReport as ez,prewarmIosRunnerSession as eW,clearRequestCanceled as eJ,buildSimctlArgsForDevice as eY,resolveFrontmostMacOsApp as eX,isCommandSupportedOnDevice as eQ,sampleApplePerfMetrics as eZ,sampleAndroidFramePerf as e0,ANDROID_MEMORY_SAMPLE_METHOD as e1,getRequestSignal as e3,markAndroidSnapshotFreshness as e2,startAppLog as e5,emitRequestProgress as e4}from"./9722.js";import{ensureDeviceReady as e8,buildAppleRunnerRequestOptions as e6,buildAppleRunnerSessionOptions as e7,createAppleRunnerCachePrewarmOnColdBoot as e9,createAppleRunnerCacheColdBootPrewarmForOpen as te}from"./8414.js";import{isPerfAction as tt,isPerfSubject as tr,pointFromPercent as ta,PERF_AREA_ERROR_MESSAGE as tn,buildSwipeGesturePlan as ti,PERF_ACTION_ERROR_MESSAGE as to,buildSnapshotDisplayLines as ts,formatDoctorCheckDetailLines as tl,isPerfKind as tu,isPerfMemoryKind as td,pointInsideRect as tp,successText as tc,clampGesturePoint as tf,resolveDeployResultTarget as tm,PERF_MEMORY_KIND_ERROR_MESSAGE as th,PERF_KIND_ERROR_MESSAGE as tg,isPerfArea as tw,formatDoctorCheckSummaryLine as tv,LOG_ACTION_VALUES as ty,withSuccessText as tA,clampToRange as tb,parseSessionSurface as tS,resolveInstallFromSourceResultTarget as t_,readReactNativeOverlayActionNodes as tI,detectReactNativeOverlay as tk,PERF_SUBJECT_ERROR_MESSAGE as tN}from"./2948.js";import{recordSessionAction as tD}from"./handler-utils.js";import{trimRuntimeValue as tx,resolveRuntimeTransportHints as tR}from"./8936.js";import{resolveAndroidAdbExecutor as tM,runAndroidAdb as tP,resolveIosSimulatorDeviceSetPath as tL,classifyAndroidAppTarget as tO,resolveIosDeviceDeepLinkBundleId as t$,isInfrastructureBootFailureReason as tC,Deadline as tE,isWebUrl as tV,resolveAndroidSerialAllowlist as tF,isDeepLinkTarget as tq,formatAndroidInstalledPackageRequiredMessage as tT,listAndroidApps as tU}from"./3340.js";import{isApplePlatform as tG,resolveAppleSimulatorSetPathForSelector as tH,matchesDeviceSelector as tK,NETWORK_INCLUDE_MODES as tB,isMobilePlatform as tj,matchesPlatformSelector as tz}from"./6849.js";import{getDiagnosticsMeta as tW,emitDiagnostic as tJ}from"./432.js";import{shutdownSimulator as tY,getSimulatorState as tX}from"./simulator.js";import{runBatch as tQ,mergeParentFlags as tZ}from"./6918.js";import{assertResolvedAppsFilter as t0}from"./2748.js";import{listIosApps as t1}from"./apps.js";import{resolveWebProvider as t3}from"./provider.js";import{unsupportedCommand as t2,readEnvMap as t5,parseReplayScriptDetailed as t4,readReplayShellEnvSource as t8,normalizeCommandList as t6,normalizePlatform as t7,readReplayCliEnvEntries as t9,parseMaestroYamlDocuments as re,parseAbsolutePoint as rt,readReplayScriptMetadata as rr,parseReplayCliEnvEntries as ra,collectReplayShellEnv as rn,support_action as ri,isPlainRecord as ro,requireAppId as rs,assertOnlyKeys as rl,resolveMaestroString as ru,requireStringValue as rd,parseMaestroPoint as rp,unsupportedMaestroSyntax as rc,readTimeoutMs as rf,writeReplayScript as rm,buildReplayVarScope as rh,resolveReplayAction as rg,mergeReplayVarScopeValues as rw}from"./4428.js";import{runCmdSync as rv,runCmd as ry}from"./8875.js";import{readSnapshotDiagnosticsSummary as rA,summarizeSnapshotTimingSamples as rb,mergeSnapshotDiagnostics as rS}from"./5913.js";import{resolveSelectorChain as r_,extractNodeText as rI,findSnapshotAncestor as rk,isDescendantOfSnapshotNode as rN,splitIsSelectorArgs as rD,buildSelectorChainForNode as rx,buildSnapshotNodeByIndex as rR,matchesSelector as rM,normalizeType as rP}from"./893.js";import{formatScriptActionSummary as rL,evaluateIsPredicate as rO,isTouchTargetCommand as r$}from"./7871.js";import{splitSelectorFromArgs as rC,normalizeText as rE,tryParseSelectorChain as rV,parseSelectorChain as rF}from"./587.js";import{sleep as rq}from"./5560.js";import{handleRecordCommand as rT}from"./record-trace-recording.js";import{recordingExtensionForPlatform as rU,defaultRecordingPath as rG}from"./5643.js";import{detectProjectRuntimeKind as rH}from"./760.js";import{INTERNAL_COMMANDS as rK,PUBLIC_COMMANDS as rB}from"./1986.js";import{readVersion as rj}from"./1404.js";var rz={};async function rW(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new l("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await e8(e.session.device),e.session.device}if(!r)throw new l("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await W(e.flags??{});return await e8(a),a}async function rJ(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await eP({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rY(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rX(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new l("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new l("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new l("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new l("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new l("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:e$(i,t.meta?.tenantId)},cleanup:()=>{L(i)}}:{source:e,cleanup:()=>{}}),s=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new l("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rW({session:n,flags:t.flags}),d=X("install",u,{message:"install_from_source is not supported on this device"});if(d)return d;let p=e3(t.meta?.requestId);if("ios"===u.platform){let{prepareIosInstallArtifact:e}=await import("./apps.js"),i=await e(o.source,{signal:p});return await rQ({prepared:i,retention:s,req:t,resolvedSourceCleanup:()=>o.cleanup(),session:n,sessionName:r,sessionStore:a,buildResult:async e=>await rZ(u,i,e)})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),f=await c(o.source,{signal:p});return await rQ({prepared:f,retention:s,req:t,resolvedSourceCleanup:()=>o.cleanup(),session:n,sessionName:r,sessionStore:a,buildResult:async e=>await r0(u,f,e)})}catch(e){return{ok:!1,error:s(e)}}}async function rQ(e){let t;try{var r;t=await rJ(e);let a=await e.buildResult(t),n=tA(a,(r=a,`Installed: ${t_(r)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;tD(r,t,a,"install_source",n,{positionals:[]})}({session:e.session,sessionStore:e.sessionStore,req:e.req,data:n}),{ok:!0,data:n}}catch(r){throw t&&await eh(t.materializationId,e.req.meta?.tenantId).catch(()=>{}),r}finally{await e.prepared.cleanup(),e.resolvedSourceCleanup()}}async function rZ(e,t,r){var a,n,i;let o,s,u=await d(e,t.installablePath,{appIdentifierHint:t.bundleId});if(!u){let{installIosInstallablePath:r}=await import("./apps.js");await r(e,t.installablePath)}return a=t,n=u,i=r,o=function(e,t){let r=t?.bundleId??e.bundleId;if(r)return r;throw new l("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact")}(a,n),s=n?.appName??a.appName,{...rY(i),bundleId:o,...r1(s),launchTarget:n?.launchTarget??o}}async function r0(e,t,r){let a=await d(e,t.installablePath,{packageNameHint:t.packageName}),n=await r3(e,t,a),{inferAndroidAppName:i}=await import("./3340.js"),o=i(n);return{...rY(r),packageName:n,...r1(a?.appName??o),launchTarget:a?.launchTarget??n}}function r1(e){return e?{appName:e}:{}}async function r3(e,t,r){let a=r?.packageName??r?.launchTarget;if(a)return a;let{installAndroidInstallablePathAndResolvePackageName:n}=await import("./3340.js"),i=await n(e,t.installablePath,t.packageName);if(!i)throw new l("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");return i}async function r2(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new l("INVALID_ARGS","release_materialized_paths requires a materializationId");return await eh(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:s(e)}}}function r5(e){return"ios"===e.platform&&"simulator"===e.kind}function r4(e,t,r){return t||ec(r)?null:T("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}async function r8(e,t){r5(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function r6(e){let t=ec(e.flags)||!e.session?await W(e.flags??{},{allowStoppedAndroidAvdPlaceholders:e.allowStoppedAndroidAvdPlaceholders}):await r7(e.session.device);return!1!==e.ensureReady&&await e8(t),t}async function r7(e){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await W(t)}catch(e){if(!(e instanceof l)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await W({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function r9(e){let t=e.flags?.device?.trim();return t||(e.resolvedDevice?.platform==="android"&&"emulator"===e.resolvedDevice.kind?e.resolvedDevice.name:e.sessionDevice?.platform==="android"&&"emulator"===e.sessionDevice.kind?e.sessionDevice.name:void 0)}e.r(rz),e.d(rz,{handleSessionCommands:()=>lS});let ae="shared_prefs/ReactNativeDevPrefs.xml",at="debug_http_host",ar="dev_server_https",aa="RCT_jsLocation",an="RCT_packager_scheme",ai="React Native runtime hints require adb run-as access to the app sandbox. Verify the app is debuggable and the selected package/device are correct.",ao='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function as(e){return void 0!==tR(e)}async function al(e){let{device:t,appId:r,runtime:a}=e;if(F(t)||!r)return;let n=tR(a);if(n){if("android"===t.platform)return void await ad(t,r,n);"ios"===t.platform&&"simulator"===t.kind&&await am(t,r,n)}}async function au(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await ap(t,r);"ios"===t.platform&&"simulator"===t.kind&&await ah(t,r)}}async function ad(e,t,r){var a,n,i,o,s,l;let u,d;ay(t);let p=(a=await ac(e,t),n=at,i=`${r.host}:${r.port}`,u=` <string name="${aA(n)}">${aA(i)}</string>`,aw(av(a,n),u));o=p,s=ar,l="https"===r.scheme,d=` <boolean name="${aA(s)}" value="${l?"true":"false"}" />`,p=aw(av(o,s),d),await af(e,t,p)}async function ap(e,t){ay(t);let r=await ac(e,t),a=av(r,at),n=av(a,ar);n!==r&&await af(e,t,n)}async function ac(e,t){let r=await tP(e,["shell","run-as",t,"cat",ae],{allowFailure:!0});return 0!==r.exitCode?ao:ag(r.stdout)}async function af(e,t,r){let a=["shell","run-as",t,"id"],n=await tP(e,a,{allowFailure:!0});if(0!==n.exitCode){let e=ab(n.stdout,n.stderr);throw new l("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:a,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:e?ai:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await tP(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await tP(e,["shell","run-as",t,"tee",ae],{stdin:r.trimEnd()})}catch(a){let e=o(a);if("TOOL_MISSING"===e.code)throw e;let r=ab("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new l("COMMAND_FAILED",r?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...e.details??{},package:t,cmd:"adb",phase:"write-runtime-hints",hint:r?ai:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function am(e,t,r){await u(eY(e,["spawn",e.id,"defaults","write",t,aa,"-string",`${r.host}:${r.port}`])),await u(eY(e,["spawn",e.id,"defaults","write",t,an,"-string",r.scheme]))}async function ah(e,t){await u(eY(e,["spawn",e.id,"defaults","delete",t,aa]),{allowFailure:!0}),await u(eY(e,["spawn",e.id,"defaults","delete",t,an]),{allowFailure:!0})}function ag(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
2
+ `:ao}function aw(e,t){return ag(e).replace("</map>",`${t}
3
+ </map>`)}function av(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return ag(e).replace(RegExp(`^\\s*<string name="${r}">[\\s\\S]*?<\\/string>\\n?`,"m"),"").replace(RegExp(`^\\s*<boolean name="${r}" value="(?:true|false)"\\s*\\/?>\\n?`,"m"),"")}function ay(e){if("binary"!==tO(e))return;let t=tT(e);throw new l("INVALID_ARGS",t,{package:e,hint:t})}function aA(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function ab(e,t){let r=`${e}
4
+ ${t}`.toLowerCase();return["run-as: package not debuggable","run-as: permission denied","run-as: package is unknown","run-as: unknown package","is unknown","is not an application","could not set capabilities"].some(e=>r.includes(e))}let aS=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function a_(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function aI(e,t){if(void 0!==e){if("string"!=typeof e)throw new l("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return tx(e)}}function ak(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new l("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function aN(e){if("ios"===e||"android"===e)return e}async function aD(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!as(r)||as(a)||await au({device:n.device,appId:n.appBundleId})}async function ax(e){var t,r,a;let{req:n,sessionName:i,sessionStore:o}=e,s=(n.positionals?.[0]??"show").toLowerCase();if("port-reverse"===(t=s)||"port-reverse-remove"===t)return await aM(n,s);if("set"!==(r=s)&&"show"!==r&&"clear"!==r)return T("INVALID_ARGS","runtime requires set, show, clear, port-reverse, or port-reverse-remove");let l=o.get(i),u=o.getRuntimeHints(i);return"clear"===s?await aR(i,o,l,u):"show"===s?{ok:!0,data:{session:i,configured:!!(a=u),runtime:a}}:function(e){var t,r;let{req:a,sessionName:n,sessionStore:i,session:o,current:s}=e,l=aN(a.flags?.platform??s?.platform??o?.device.platform);if(!l)return T("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(o&&o.device.platform!==l)return T("INVALID_ARGS",`runtime set targets ${l}, but session "${n}" is already bound to ${o.device.platform}.`);let u={platform:(t=a.flags,r={platform:l,metroHost:tx(t?.metroHost),metroPort:ak(t?.metroPort),bundleUrl:tx(t?.bundleUrl),launchUrl:tx(t?.launchUrl)}).platform??s?.platform,metroHost:r.metroHost??s?.metroHost,metroPort:r.metroPort??s?.metroPort,bundleUrl:r.bundleUrl??s?.bundleUrl,launchUrl:r.launchUrl??s?.launchUrl};return 0===a_(u)?T("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,u),{ok:!0,data:{session:n,configured:!0,runtime:u}})}({req:n,sessionName:i,sessionStore:o,session:l,current:u})}async function aR(e,t,r,a){as(a)&&r?.appBundleId&&await au({device:r.device,appId:r.appBundleId});let n=t.clearRuntimeHints(e);return{ok:!0,data:{session:e,cleared:n}}}async function aM(e,t){let r=function(e){var t,r;let a,n,i,o,s=(t=e,a=t.flags?.leaseId,n=t.flags?.leaseProvider,a?n?{ok:!0,leaseId:a,provider:n}:{ok:!1,response:T("INVALID_ARGS","runtime port-reverse requires a lease provider.")}:{ok:!1,response:T("INVALID_ARGS","runtime port-reverse requires a resolved remote lease.")});if(!s.ok)return s;let l=(r=e,i=aL(r.flags?.devicePort),o=aL(r.flags?.hostPort??r.flags?.devicePort),i&&o?{ok:!0,devicePort:i,hostPort:o}:{ok:!1,response:T("INVALID_ARGS","runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.")});if(!l.ok)return l;let u=e.flags?.portReverseName?.trim()||"runtime";return{ok:!0,options:{leaseId:s.leaseId,provider:s.provider,devicePort:l.devicePort,hostPort:l.hostPort,name:u}}}(e);if(!r.ok)return r.response;let a=await aP(t,r.options);return a?{ok:!0,data:{action:t,...a}}:T("UNSUPPORTED_OPERATION","No active provider device runtime supports port reverse for this lease.")}async function aP(e,t){return"port-reverse"===e?await H(t):await B(t)}function aL(e){if("number"==typeof e&&Number.isInteger(e)&&!(e<1)&&!(e>65535))return e}let aO="open-command-roundtrip",a$="Not implemented for this platform in this release.";function aC(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let aE=new Set(["app","desktop","frontmost-app"]);async function aV(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await eX();return{appBundleId:t.bundleId,appName:t.appName}}async function aF(e,t,r){if(tG(e.platform)&&t)return tq(t)?"macos"===e.platform?void 0:"device"===e.kind?t$(r,t):tV(t)?void 0:r??await aq(e,t):await aT(e,t)}async function aq(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aT(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aU(e,t){if(!("android"!==e.platform||!t||tq(t)))try{let{resolveAndroidApp:r}=await import("./3340.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function aG(e,t,r){if(r||"android"!==e.platform||!t||!tq(t))return r;try{let{getAndroidAppState:t}=await import("./3340.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function aH(e,t,r,a){return await aF(e,t,r)??await a(e,t)??("android"===e.platform&&t&&tq(t)?r:void 0)}function aK(e){return T("INVALID_ARGS",e)}function aB(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=tS(r);if(!aE.has(e))throw new l("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new l("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new l("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?tS(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new l("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return T(e instanceof l?e.code:"INVALID_ARGS",String(e.message))}}function aj(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&tq(r)?aK("open --relaunch does not support URL targets."):"app"!==a?aK("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tO(r)?aK(tT(r)):null:null}async function az(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,openTarget:s,existingSession:u,onIosSimulatorColdBootStart:d}=e;await e8(n,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:d});let{appBundleId:p,appName:c}=await aW({device:n,surface:i,openTarget:s,existingAppBundleId:u?.appBundleId}),f=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new l("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!aS.includes(e));if(n)throw new l("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${aS.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new l("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new l("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:aI(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new l("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return ak(e)}}(t.metroPort),bundleUrl:aI(t.bundleUrl,"bundleUrl"),launchUrl:aI(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:aN(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=aN(n);if(a.platform&&r&&!i)throw new l("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new l("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&a_(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=o(t);return T(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!f.ok)return{type:"response",response:f};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=f.data;await aD({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:c,runtime:f.data.runtime}}}async function aW(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await aV(r);return{appBundleId:i.appBundleId??await aH(t,a,n,aU),appName:i.appName??a}}let aJ=new Map;async function aY(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await k(t.id),await f(t,"close",[r],a,n),await r8(t,300)}async function aX(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,p=n?.launchUrl;if(!p||0===d.length||d.length>1)return;let c=d[0]?.trim();!c||tq(c)||await f(i,"open",[p],o.flags?.out,{...(t=s,r=o.flags,a=e_(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function aQ(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:p,openPositionals:c,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:v}=e,y=o.flags?.relaunch===!0,A=v?.trace?.outPath,b=g,S=Date.now(),_={};if(y&&p){let e=b??p,t=Date.now();await aY({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...e_(u,o.flags,b??v?.appBundleId,A)}}),_.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let I=Date.now();await al({device:d,appId:b,runtime:w}),_.runtimeHintsDurationMs=Math.max(0,Date.now()-I);let k="ios"===d.platform&&"app"===h&&c.length>0,N=e7({req:o,logPath:u,appBundleId:b,traceLogPath:A}),D=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(k&&b&&(_.runnerPrewarmKind="session",_.runnerPrewarmScheduled=!0,D)){i=eW(d,{...N,propagateError:!0});let e=Date.now();await i,_.runnerPrewarmWaited=!0,_.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let R=Date.now(),M=await aZ({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:b,appName:m,existingSession:v});if("response"===M.type)return M.response;let P=M.session??v;await f(d,"open",c,o.flags?.out,{...e_(u,o.flags,b)}),_.openDispatchDurationMs=Math.max(0,Date.now()-R);let L=Date.now();if(await aX({runtime:w,device:d,req:o,logPath:u,appBundleId:b,traceLogPath:A,openPositionals:c}),_.launchUrlDurationMs=Math.max(0,Date.now()-L),k&&b&&!i&&(i=eW(d,N)),y&&i&&!0!==_.runnerPrewarmWaited){let e=Date.now();await i,_.runnerPrewarmWaited=!0,_.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==_.runnerPrewarmWaited&&(_.runnerPrewarmWaited=!1);b=await aG(d,p,b),"android"===d.platform&&b&&await eE(d,b);let $=p?(t=b,{durationMs:Math.max(0,Date.now()-R),measuredAt:new Date().toISOString(),method:aO,appTarget:p,appBundleId:t}):void 0,C=Date.now();if(await r8(d,300),_.postOpenSettleDurationMs=Math.max(0,Date.now()-C),eR(o.meta?.requestId)){let e=E();return T(e.code,e.message,e.details)}v&&e2(v,"open",v.snapshot);let V=aC({existingSession:P,sessionName:v?.name??x(o),sessionScope:v?.sessionScope??eK(o),device:d,surface:h,appBundleId:b,appName:m,saveScript:!!o.flags?.saveScript});V.lease=eb({req:o,existingLease:v?.lease}),void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===a_(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let F=l.ensureSessionDir(s),q=O(F,o.meta?.requestId??tW().requestId);_.totalDurationMs=Math.max(0,Date.now()-S);let U=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:d,runtime:p,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),p&&c(p)>0&&(f.runtime=p),d&&(f.platform=d.platform,f.target=d.target??"mobile",f.device=d.name,f.id=d.id,f.kind=d.kind,"android"===d.platform&&(f.serial=d.id)),d?.platform==="ios"&&(f.device_udid=d.id,f.ios_simulator_device_set=d.simulatorSetPath??null),{...f,...tc(`Opened: ${i??o??t}`)}}({sessionName:V.name,sessionStateDir:F,runnerLogPath:ew(F),requestLogPath:q,appName:m,appBundleId:b,surface:h,startup:$,timing:_,device:d,runtime:w,runtimeHintCount:a_});return l.recordAction(V,{command:"open",positionals:c,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:U}),l.set(s,V),{ok:!0,data:U}}async function aZ(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let d=aC({existingSession:l,sessionName:l?.name??x(t),sessionScope:l?.sessionScope??eK(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});d.lease=eb({req:t,existingLease:l?.lease}),a.set(r,d);let p=await u(d);return p&&!p.ok?{type:"response",response:p}:{type:"session",session:a.get(r)??d}}async function a0(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=aB(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?aK("open --relaunch requires an app name or an active session app."):aK("Session already active. Close it first or pass a new --session name.");let u=aj({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let d=await r7(i.device),p=await az({req:t,sessionName:r,sessionStore:n,device:d,surface:l,openTarget:s,existingSession:i,onIosSimulatorColdBootStart:te({req:t,logPath:a,device:d,surface:l,openTarget:s,traceLogPath:i.trace?.outPath})});return"response"===p.type?p.response:await aQ({req:t,sessionName:r,sessionStore:n,logPath:a,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:p.details.appBundleId,appName:p.details.appName,runtime:p.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return aK("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&tq(r)?aK("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tO(r)?aK(tT(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await W(t.flags??{}),d=aB(u,t.flags?.surface,s);if("string"!=typeof d)return d;let p=aj({shouldRelaunch:o,openTarget:s,surface:d,device:u});return p||await j(aJ,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return eg(t,e)?T("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.name,hint:"Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target."}):T("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:z(e,"device-in-use")});let i=await az({req:t,sessionName:r,sessionStore:n,device:u,surface:d,openTarget:s,onIosSimulatorColdBootStart:te({req:t,logPath:a,device:u,surface:d,openTarget:s})});return"response"===i.type?i.response:await aQ({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:d})})}async function a1(e){if(!1===e.booted)return{success:!0,exitCode:0,stdout:"",stderr:""};try{return r5(e)?await a3(e):await a5(e)}catch(t){let e=s(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function a3(e){let t=await tY(e);return t.success?t:"Shutdown"===await a2(e)?{...t,success:!0,exitCode:0}:t}async function a2(e){try{return await tX(e)}catch{return null}}async function a5(e){let t=await tP(e,["emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function a4(e){let{device:t,shutdownRequested:r}=e;if(r&&(r5(t)||"android"===t.platform&&"emulator"===t.kind))return await a1(t)}async function a8(e){let t,{req:r,sessionName:a,logPath:n,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,l=i.get(a);if(!l)return await a6(r,n);try{var u,d,p;(await eF(l),await ee(l,"session-close"),await P(l),await ef(l),await eq(l),u=r,d=l,p=u,(p.positionals?.length??0)>0||"web"===d.device.platform)&&(tG(l.device.platform)&&!r5(l.device)&&await V(l),await f(l.device,"close",r.positionals??[],r.flags?.out,{...e_(n,r.flags,l.appBundleId,l.trace?.outPath)}),await r8(l.device,300));tG(l.device.platform)&&(!r5(l.device)||r.flags?.shutdown||l.recording)?await V(l):tG(l.device.platform)&&tJ({level:"debug",phase:"ios_runner_retained_after_close",data:{session:l.name,deviceId:l.device.id}});let e=i.getRuntimeHints(a);as(e)&&l.appBundleId&&await au({device:l.device,appId:l.appBundleId}).catch(()=>{}),tD(i,l,r,"close",{session:l.name,...tc(`Closed: ${l.name}`)}),r.flags?.saveScript&&(l.recordSession=!0),i.writeSessionLog(l),await es(a).catch(()=>{})}finally{try{t=await K({session:l,leaseRegistry:o,leaseLifecycleProvider:s})}finally{i.delete(a)}}let c=await a4({device:l.device,shutdownRequested:r.flags?.shutdown});return c?{ok:!0,data:tA({session:l.name,shutdown:c,...t?{provider:t}:{}},`Closed: ${l.name}`)}:{ok:!0,data:{session:l.name,...tc(`Closed: ${l.name}`),...t?{provider:t}:{}}}}async function a6(e,t){if(!e.positionals||0===e.positionals.length)return T("SESSION_NOT_FOUND","No active session");let r=await r6({session:void 0,flags:e.flags,ensureReady:!0});return await f(r,"close",e.positionals,e.flags?.out,{...e_(t,e.flags)}),await r8(r,300),{ok:!0,data:{app:e.positionals[0],...tc(`Closed: ${e.positionals[0]}`)}}}let a7={ios:async(e,t,r)=>{let a=await v(e,t,r,{relaunch:!0,appIdentifierHint:t});if(a)return{bundleId:a.bundleId??a.launchTarget??t};let{reinstallIosApp:n}=await import("./apps.js");return await n(e,t,r)},android:async(e,t,r)=>{let a=await v(e,t,r,{relaunch:!0,packageNameHint:t});if(a)return{package:a.packageName??a.launchTarget??t};let{reinstallAndroidApp:n}=await import("./3340.js");return await n(e,t,r)}},a9={ios:async(e,t,r)=>{let a=await v(e,t,r,{appIdentifierHint:t});if(a)return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget};let{installIosApp:n}=await import("./apps.js"),i=await n(e,r,{appIdentifierHint:t});return{bundleId:i.bundleId,appName:i.appName,launchTarget:i.launchTarget}},android:async(e,t,r)=>{let a=await v(e,t,r,{packageNameHint:t});if(a)return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget};let{installAndroidApp:n}=await import("./3340.js"),i=await n(e,r);return{package:i.packageName,appName:i.appName,launchTarget:i.launchTarget}}};async function ne(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=r4(a,s,l);if(u)return u;let d=function(e,t){let r=t[0]?.trim(),a=t[1]?.trim();if("install"===e){let e=a??r;return e?{ok:!0,app:a?r??"":"",appPathInput:e}:{ok:!1,response:T("INVALID_ARGS","install requires: install <path-to-app-binary>")}}return r&&a?{ok:!0,app:r,appPathInput:a}:{ok:!1,response:T("INVALID_ARGS","reinstall requires: reinstall <app> <path-to-app-binary>")}}(a,r.positionals??[]);if(!d.ok)return d.response;let{app:p,appPathInput:c}=d,f=r.meta?.uploadedArtifactId;try{var m,h,g,w,v,y,A;let e,n,u=f?e$(f,r.meta?.tenantId):ek.expandHome(c);if(!t.existsSync(u))return T("INVALID_ARGS",`App binary not found: ${u}`);let d=await r6({session:s,flags:l,ensureReady:!1}),b=X(a,d);if(b)return b;let S="ios"===d.platform?(m=p,h=u,e=(g=await o.ios(d,p,u)).bundleId,{app:m||e||g.launchTarget||h,appPath:h,platform:"ios",...e?{appId:e,bundleId:e}:{},appName:g.appName,launchTarget:g.launchTarget}):(w=p,v=u,n=(y=await o.android(d,p,u)).package,{app:w||n||y.launchTarget||v,appPath:v,platform:"android",...n?{appId:n,package:n,packageName:n}:{},appName:y.appName,launchTarget:y.launchTarget}),_=tA(S,(A=S,`Installed: ${A.appName??tm(A)}`));return tD(i,s,r,a,_),{ok:!0,data:_}}finally{f&&L(f)}}async function nt(e,t,r){return await tQ(e,t,r)}async function nr(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=eK(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>m(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:ew(t),platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tF(t.flags?.androidDeviceAllowlist),r=t.flags?.platform,a=tH({simulatorSetPath:tL(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await eI({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?tG(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,appleOs:t,...r})=>r);return{ok:!0,data:{devices:o}}}catch(t){let e=o(t);return T(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=r4(t.command,e,n);if(i)return i;let o=await r6({session:e,flags:n,ensureReady:!0}),s=X("apps",o);if(s)return s;let l=t0(t.flags?.appsFilter);return tG(o.platform)?{ok:!0,data:{apps:(await t1(o,l)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tU(o,l)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function na(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let nn='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',ni='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function no(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=i.platform;if(!n&&"string"==typeof i?.session&&i.session.trim().length>0)return T("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=r4("appstate",n,i);if(s)return s;let l=tG(n?.device.platform)&&!!n&&0===eV(n,i).length;if("ios"===o&&!l)return T("SESSION_NOT_FOUND",nn);if("macos"===o&&!l)return T("SESSION_NOT_FOUND",ni);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return T("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await r6({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return T("SESSION_NOT_FOUND",nn);if("macos"===u.platform)return T("SESSION_NOT_FOUND",ni);if("web"===u.platform)return T("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:d}=await import("./3340.js"),p=await d(u);return{ok:!0,data:{platform:"android",package:p.package,activity:p.activity}}}async function ns(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e;if("boot"===t.command){let e,i=n.get(r),s=t.flags??{},l=r4(t.command,i,s);if(l)return l;let u="android"===(s.platform??i?.device.platform),d=!0===s.headless;if(d&&!u)return T("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=r9({flags:s,sessionDevice:i?.device}),c=u&&!!p,f=!1;try{e=await r6({session:i,flags:s,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(r){let t=o(r);if(u&&d&&!p&&"DEVICE_NOT_FOUND"===t.code)return T("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!c||"DEVICE_NOT_FOUND"!==t.code||!p)throw r;e=await na({avdName:p,serial:s.serial,headless:d}),f=!0}if(s.target&&(e.target??"mobile")!==s.target)return T("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${s.target}.`);if(u&&d){if("android"!==e.platform||"emulator"!==e.kind)return T("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!f){let t=r9({flags:s,sessionDevice:i?.device,resolvedDevice:e});if(!t)return T("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await na({avdName:t,serial:s.serial,headless:!0})}await e8(e)}else"android"===e.platform&&"emulator"===e.kind&&!0!==e.booted?(e=await na({avdName:e.name,serial:s.serial,headless:!1}),await e8(e)):("android"!==e.platform||!0!==e.booted)&&await e8(e,{onIosSimulatorColdBootStart:e9({req:t,logPath:a,device:e,enabled:!0})});let m=X("boot",e);return m||{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}}if("shutdown"===t.command){var i;let e,a=n.get(r),o=t.flags??{},s=r4(t.command,a,o);if(s)return s;let l=await r6({ensureReady:!1,flags:o,session:a}),u=X("shutdown",l,{message:"shutdown is supported only for Apple simulators and Android emulators."});if(u)return u;if(a&&a.device.platform===l.platform&&a.device.id===l.id)return T("DEVICE_IN_USE","Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.",{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let d=await a1(l);return d.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:d}}:T(d.error?.code??"COMMAND_FAILED",(i=d,(e=i.error?.message??i.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:d})}return"appstate"===t.command?await no({req:t,sessionName:r,sessionStore:n}):null}async function nl(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===aO&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:aO,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:aO,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:aO},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:np(),memory:{available:!1,reason:a$},cpu:{available:!1,reason:a$}}},sampling:{startup:{method:aO,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:e1,description:ej,unit:"kB"},cpu:{method:eN,description:ev,unit:"percent"},fps:{method:$,description:eU,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:eo(a.device)}});return ng(e)&&(e.appBundleId?"android"===e.device.platform?await nc(u,e,e.appBundleId,t):await nf(u,e,e.appBundleId):(n=u,l=nw(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function nu(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:np()},sampling:{fps:"android"===(a=r).device.platform?{method:$,description:eU,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:C(a.device)}};return ng(e)&&(e.appBundleId?await nh(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:nw(e)}),n}async function nd(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:e1,description:ej,unit:"kB",topConsumerLimit:5}:eo(a.device).memory,snapshot:"android"===r.device.platform?{method:ea,description:et,defaultKind:"android-hprof",artifactOnly:!0}:{method:eB,description:c,defaultKind:"memgraph",artifactOnly:!0}}};if(!ng(e)){if("snapshot"===t.action){let r=n_(e,t.kind);return n.artifact=nI(e,r),n.support=nN(n.artifact.support)??nk(e),n}return n.metrics={memory:{available:!1,reason:a$}},n}return"sample"===t.action?n.metrics={memory:await nA(e,t)}:(n.artifact=await nS(e,t),n.support=nN(n.artifact.support)??nk(e)),n}function np(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function nc(e,t,r,a){let n=await nv(t,r,a);nm(e,t,n)}async function nf(e,t,r){let a=await ny(t,r);nm(e,t,a)}function nm(e,t,r){e.metrics.memory=nx(r.memory),e.metrics.cpu=nx(r.cpu),e.metrics.fps=nR(nx(r.fps),t)}async function nh(e,t,r,a){let n="android"===t.device.platform?await nD(e0(t.device,r,{adb:a.androidAdb})):await nD(y(t.device,r));e.metrics.fps=nR(nx(n),t)}function ng(e){return eu(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function nw(e){return"android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first."}async function nv(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([Y(e.device,t,a),er(e.device,t,a),e0(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function ny(e,t){let r=await nD(y(e.device,t)),a=await nD(eZ(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function nA(e,t){return e.appBundleId?nx("android"===e.device.platform?await nD(Y(e.device,e.appBundleId,{adb:t.androidAdb})):await nD(nb(e))):{available:!1,reason:nw(e)}}async function nb(e){if(!e.appBundleId)throw new l("INVALID_ARGS",nw(e));return(await eZ(e.device,e.appBundleId)).memory}async function nS(e,t){if(!e.appBundleId)throw new l("INVALID_ARGS",nw(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=n_(e,t.kind),n=function(e,t){if(e.out)return ek.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?nI(e,a):await N(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?nI(e,a):await A(e.device,e.appBundleId,n)}function n_(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function nI(e,t){var r,a;let n=nk(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:tG(r.device.platform)?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function nk(e){return"android"===e.device.platform?{platform:e.device.platform,defaultKind:"android-hprof",androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:"Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice."}:tG(e.device.platform)?{...eD(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}:{platform:e.device.platform,defaultKind:"memgraph",androidHprof:!1,memgraph:!1,heapprofd:!1,reason:"Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.",hint:"Use perf memory sample where supported, or switch to a platform with memory artifact support.",heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function nN(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function nD(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function nx(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=s(e.reason);return{available:!1,reason:t.message,error:t}}function nR(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=nM((a=e).windowStartedAt),i=nM(a.windowEndedAt)??nM(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function nM(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function nP(e){var t,r,a,n,i,o,l,u,d,p;let c,f,m,h,g,w,v=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,o=c,f=nL(i,1),m=nL(i,2),h=nL(i,3),tr(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?T("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?T("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:o}:T("INVALID_ARGS",tN)):(u=t,d=c,g=nL(u,1),w=nL(u,2),"start"!==(p=g)&&"stop"!==p?T("INVALID_ARGS","perf trace action must be start or stop"):tu(w)?"perfetto"!==w?T("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:d}:T("INVALID_ARGS",tg)));if(!v.ok)return v;let{session:y}=e;if("android"!==y.device.platform)return T("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!y.appBundleId)return T("COMMAND_FAILED","No Android app package is associated with this session.",{hint:"Run open <app> first so perf can resolve the package and process identity."});try{let t="cpu"===v.area?await nC(e,y,y.appBundleId,v):await nE(e,y,y.appBundleId,v);return{ok:!0,data:t}}catch(e){return{ok:!1,error:s(e)}}}function nL(e,t){return(e.positionals?.[t]??"").toLowerCase()}function nO(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function n$(e,t,a){var n,i,o;let s;return t?ek.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function nC(e,t,r,a){if("start"===a.action){nV(t);let n=n$(e,a.outPath,"cpu.perf.data"),i=await w(t.device,r,n,{adb:e.androidAdbExecutor});return nO(e,i)}let n=nq(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new l("COMMAND_FAILED","Stop the Android Simpleperf CPU profile before generating a report.",{hint:"Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf."})}(n);let r=n$(e,a.outPath,"cpu-report.json");return await ez(t.device,n,r,{adb:e.androidAdbExecutor})}let i=nF(e,a.outPath,n),o=await eS(t.device,n,i,{adb:e.androidAdbExecutor});return nO(e,o)}async function nE(e,t,r,a){if("start"===a.action){nV(t);let n=n$(e,a.outPath,"app.perfetto-trace"),i=await I(t.device,r,n,{adb:e.androidAdbExecutor});return nO(e,i)}let n=nq(t,"trace",a.kind),i=nF(e,a.outPath,n),o=await ex(t.device,n,i,{adb:e.androidAdbExecutor});return nO(e,o)}function nV(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new l("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.":"Run perf trace stop --kind perfetto before starting another Android native perf capture."})}function nF(e,t,r){return t?n$(e,t,r.outPath):r.outPath}function nq(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new l("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.":"Run perf trace start --kind perfetto first, then stop in the same session."})}async function nT(e){if(!b(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import("./audio-probe.js");return t}M();let nU=["probe"],nG=["start","status","stop"],nH=`audio probe requires ${nG.join(", ")}`;async function nK(e){let t=function(e){var t;let r,a=(r=(t=e).sessionStore.get(t.sessionName))?eQ("audio",r.device)?{ok:!0,session:r}:T("UNSUPPORTED_OPERATION","audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts"):T("SESSION_NOT_FOUND","audio requires an active session");if(!a.ok)return a;let n=function(e){let t,r;if(t=(e.positionals?.[0]??"probe").toLowerCase(),nU.includes(t)?!"probe":!void 0)return T("INVALID_ARGS","audio requires probe");let a=(r=(e.positionals?.[1]??"status").toLowerCase(),nG.includes(r)?r:void 0);return a?{ok:!0,probeAction:a}:T("INVALID_ARGS",nH)}(e.req);if(!n.ok)return n;let i=function(e,t){if("start"!==t&&e.positionals&&e.positionals.length>2)return T("INVALID_ARGS","audio probe duration and bucket are only supported with audio probe start");let r=nj(e.positionals?.[2],{defaultValue:1e4,min:100,max:12e4,message:"audio probe duration must be an integer in range 100..120000 ms"});if(r instanceof Error)return T("INVALID_ARGS",r.message);let a=nj(e.positionals?.[3],{defaultValue:1e3,min:100,max:1e4,message:"audio probe bucket must be an integer in range 100..10000 ms"});return a instanceof Error?T("INVALID_ARGS",a.message):{ok:!0,timing:{durationMs:r,bucketMs:a}}}(e.req,n.probeAction);return i.ok?{ok:!0,session:a.session,probeAction:n.probeAction,...i.timing}:i}(e);if(!t.ok)return t;let r=await nT(t.session.device);if(r)return await nB(e,t,r);let a=t3();if(!a.probeAudio)return T("UNSUPPORTED_OPERATION","audio is not supported by this web provider");try{return{ok:!0,data:await a.probeAudio({action:t.probeAction,durationMs:t.durationMs,bucketMs:t.bucketMs})}}catch(e){return{ok:!1,error:s(e)}}}async function nB(e,t,r){try{return{ok:!0,data:await U({session:t.session,sessionName:e.sessionName,sessionStore:e.sessionStore,backend:r,probeAction:t.probeAction,durationMs:t.durationMs,bucketMs:t.bucketMs})}}catch(e){return{ok:!1,error:s(e)}}}function nj(e,t){if(void 0===e)return t.defaultValue;let r=Number.parseInt(e,10);return!Number.isInteger(r)||String(r)!==e||r<t.min||r>t.max?Error(t.message):r}async function nz(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return T("INVALID_ARGS","perf cpu requires profile");let t=nW(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=nJ(e[3]);return r.ok?{ok:!0,area:"cpu",mode:"cpu-profile",action:t.value,kind:"xctrace",template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:r}(r):"trace"===a?function(e){let t=nW(e[1],"perf trace",!1);if(!t.ok)return t;let r=nJ(e[2]);return r.ok?{ok:!0,area:"trace",mode:"trace",action:t.value,kind:"xctrace",template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:r}(r):T("INVALID_ARGS",tn));if(!n.ok)return n;if("android"===t.device.platform)return T("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if(!tG(t.device.platform))return T("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return T("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await nY(e,t,n);if("stop"===n.action)return await nX(e,t,n);return await nQ(e,t,n)}catch(e){return{ok:!1,error:s(e)}}}function nW(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:T("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function nJ(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:T("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function nY(e,t,r){if(t.applePerf?.active)return T("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=n0(e,r),i=await ei({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=n1("started",i);return nZ(e,t,o),{ok:!0,data:o}}async function nX(e,t,r){var a,n,i,s,l,u,d;let p,c=t.applePerf?.active;if(!c)return T("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ek.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{p=await D(c,f)}catch(r){throw a=r,o(a).details?.captureCleanedUp===!0&&(n=e,(i=t).applePerf={...i.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,i)),r}s=e,l=t,u=p,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(d=u).mode?{lastProfileTracePath:d.outPath,lastProfileTemplate:d.template}:{lastTracePath:d.outPath}},s.sessionStore.set(s.sessionName,l);let m=n1("stopped",p);return nZ(e,t,m),{ok:!0,data:m}}async function nQ(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return T("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return T("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=n0(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:T("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await R({tracePath:ek.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return nZ(e,t,s),{ok:!0,data:s}}function nZ(e,t,r){tD(e.sessionStore,t,e.req,"perf",r)}function n0(e,t){if(t.outPath)return ek.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function n1(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}let n3=`logs requires ${ty.slice(0,-1).join(", ")}, or ${ty.at(-1)}`,n2=["dump","log"],n5=`network requires ${n2.join(" or ")}`,n4=`network include mode must be one of: ${tB.join(", ")}`,n8={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=J(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eA(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>ir(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",h(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>ia(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>ii(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>io(e,t,r)};async function n6(e){let{req:t}=e;return"perf"===t.command?n7(e):"logs"===t.command?it(e):"network"===t.command?is(e):"audio"===t.command?await nK(e):null}async function n7(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,o=n.get(a);if(!o)return T("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===o.device.platform?await nP({req:r,sessionName:a,sessionStore:n,session:o,androidAdbExecutor:i,area:u}):await nz(e,o);let d=function(e){var t,r,a,n,i,o,u,d,p,c;let f,m,h=tw(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return T("INVALID_ARGS",tn);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=tt(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return T("INVALID_ARGS",to);let w=function(e){if(void 0!==e)return"string"==typeof e&&tu(e)?e:new l("INVALID_ARGS",tg)}(e.flags?.kind);if(w instanceof l)return{ok:!1,error:s(w)};let v=(t=h,r=g,("memory"===t?ie(r)?void 0:T("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?T("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,o=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return T("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=o,d=n,p=i,u?"memory"!==d||"snapshot"!==p?T("INVALID_ARGS","--kind is only supported with perf memory snapshot"):td(u)?void 0:T("INVALID_ARGS",th):void 0)));return v||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!d.ok)return d;if(d.native)return await nz(e,o);try{return{ok:!0,data:await n9(e,o,d)}}catch(e){return{ok:!1,error:s(e)}}}async function n9(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await nd(t,{action:function(e){if(ie(e))return e;throw new l("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await nu(t,{androidAdb:i}):await nl(t,{androidAdb:i})}function ie(e){return"sample"===e||"snapshot"===e}async function it(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return T("SESSION_NOT_FOUND","logs requires an active session");let l=X("logs",s.device);if(l)return l;let u=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,ty.includes(r)?a&&"clear"!==r?T("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:T("INVALID_ARGS",n3));return u.ok?await n8[u.action]({...e,session:s,restart:u.restart}):u}async function ir(e,t,r){let a=r.resolveAppLogPath(t),n=await eL(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function ia(e,t,r,a){if(e.appLog&&!a)return T("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:el(n)};let i=e.appBundleId;if(!i)return T("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eH(e.appLog);let o=el(n),l=r.resolveAppLogPidPath(t);try{let a=await e5(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...o,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:s(a)}}}async function ii(e,t,r){if(e.appLog)return T("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return T("INVALID_ARGS","logs start requires an app session; run open <app> first");let a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await e5(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:s(e)}}}async function io(e,t,r){if(!e.appLog)return T("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eH(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function is(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return T("SESSION_NOT_FOUND","network requires an active session");let i=X("network",n.device);if(i)return i;let o=(t.positionals?.[0]??"dump").toLowerCase();if(!n2.includes(o))return T("INVALID_ARGS",n5);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return T("INVALID_ARGS","network dump limit must be an integer in range 1..200");let l=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return T("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return tB.includes(a)?{ok:!0,include:a}:T("INVALID_ARGS",n4)}(t);return l.ok?{ok:!0,session:n,maxEntries:s,include:l.include}:l}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await il({include:r,maxEntries:a});let i=await em({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function il(e){let t=t3();if(!t.dumpNetwork)return T("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:s(e)}}}function iu(e,t,r){var a,n;if(null==e)return ri("open",[ru(rs(t,"launchApp"),r)]);if("string"==typeof e)return ri("open",[ru(e,r)]);if(!ro(e))throw new l("INVALID_ARGS","launchApp expects a string or map.");rl(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),im(e,"permissions"),im(e,"clearKeychain");let i=ru("string"==typeof e.appId?e.appId:rs(t,"launchApp"),r),o=(a=e,n=r,[...ip(a.arguments,"launchApp.arguments",n),...ip(a.launchArguments,"launchApp.launchArguments",n)]),s=!0===e.clearState;return ri("open",[i],{...!s&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...s?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function id(e,t,r){if(null==e)return ri("close",[ru(rs(t,"stopApp"),r)]);if("string"==typeof e)return ri("close",[ru(e,r)]);throw new l("INVALID_ARGS","stopApp expects a string appId or no value.")}function ip(e,t,r){if(null==e)return[];if("string"==typeof e)return[ru(e,r)];if(Array.isArray(e))return e.map((e,a)=>ic(e,`${t}[${a}]`,r));if(ro(e))return Object.entries(e).flatMap(([e,a])=>[ru(e,r),ic(a,`${t}.${e}`,r)]);throw new l("INVALID_ARGS",`${t} expects a string, list, or map.`)}function ic(e,t,r){if("string"==typeof e)return ru(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new l("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function im(e,t){if(void 0!==e[t])throw rc(`Maestro launchApp field "${t}" is not supported yet.`)}let ih="__maestroRunScript",ig="__maestroAssertVisible",iw="__maestroAssertNotVisible",iv="__maestroPressEnter",iy="__maestroWaitForAnimationToEnd",iA="__maestroScrollUntilVisible",ib="__maestroSwipeScreen",iS="__maestroSwipeOn",i_="__maestroTapOn",iI="__maestroTapPointPercent";function ik(e){if(null==e)return ri("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return ri("type",["\b".repeat(e)]);if(!ro(e))throw new l("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(rl(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return ri("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new l("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return ri("type",["\b".repeat(e.charactersToErase)])}function iN(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function iD(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw rc(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function ix(e){return iD(e,"swipe direction")}function iR(e,t,r=[],a){if("string"==typeof e)return iM(ru(e,a));if(!ro(e))throw new l("INVALID_ARGS",`${t} expects a string or selector map.`);rl(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(iL("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(iL("selected",String(e.selected))),"string"==typeof e.id&&n.push(iL("id",ru(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return iM(ru(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(iL("label",ru(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new l("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function iM(e,t=[]){return[[iL("label",e),...t].join(" "),[iL("text",e),...t].join(" "),[iL("id",e),...t].join(" ")].join(" || ")}function iP(e){let t=iN(e.duration);return t?[t]:[]}function iL(e,t){return`${e}=${JSON.stringify(t)}`}function iO(e){var t,r;if(!ro(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function i$(e){let t=iO(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function iC(e){let t={doubleTap:!0};return ro(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class iE{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new l("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new l("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new l("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new l("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new l("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new l("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function iV(e,t,r){return{...ri(e,t),replayControl:r}}function iF(e,t,r){let a="string"==typeof e?ru(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new l("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let iq=`
2
5
  const fs = require('node:fs');
3
6
  const input = JSON.parse(fs.readFileSync(0, 'utf8'));
4
7
  if (typeof fetch !== 'function') {
@@ -19,10 +22,10 @@ fetch(input.url, {
19
22
  console.error(error && error.stack ? error.stack : String(error));
20
23
  process.exit(1);
21
24
  });
22
- `;function ng(e){if("string"!=typeof e)throw new s("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new s("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,nw)}catch(t){throw new s("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function nw(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let ny={launchApp:({value:e,config:t,context:r})=>[aX(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return tU(a9,[no(tT(e,t))],np(e));if(tF(e)&&"string"==typeof e.point){tG(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tH(e.point);return"percent"===t.kind?tU(ne,[String(t.x),String(t.y)],nu(e)):tU("click",[String(t.x),String(t.y)],nu(e))}tF(e)&&tG(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=np(e);return tU(a9,[ni(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tF(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new s("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=ni(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(tF(e)&&"string"==typeof e.point){tG(e,"doubleTapOn",["point","delay"]);let t=tE(e.point);return tU("click",[String(t.x),String(t.y)],nd(e))}return tF(e)&&tG(e,"doubleTapOn",["id","text","enabled","selected","delay"]),tU("click",[ni(e,"doubleTapOn",["delay"],t)],nd(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tF(e)&&"string"==typeof e.point){tG(e,"longPressOn",["point"]);let t=tE(e.point);return tU("longpress",[String(t.x),String(t.y),"3000"])}return tF(e)&&tG(e,"longPressOn",["id","text","enabled","selected"]),tU("click",[ni(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[tU("type",[tT(function(e){if("string"==typeof e)return e;if(!tF(e))throw new s("INVALID_ARGS","inputText expects a string or map.");if(tG(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new s("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[nt(e)],pasteText:({value:e,context:t,name:r})=>[tU("type",[tT(tB(r,e),t)])],openLink:({value:e,config:t,context:r,name:a})=>{var n,i,o,s,l,u;let p;return[(n=e,i=t,o=r,s=a,p=tT((l=n,u=s,"string"==typeof l?l:tF(l)?(tG(l,u,["link"]),tB(`${u}.link`,l.link)):tB(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?tU("open",[tT(tq(i,s),o),p],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):tU("open",[p]))]},assertVisible:({value:e,context:t,name:r})=>[tU(a3,[ni(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[tU(a2,[ni(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tF(e))throw new s("INVALID_ARGS","extendedWaitUntil expects a map.");tG(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw tK("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=ni(r,"extendedWaitUntil",[],t),n=String(tj(e,17e3));return void 0!==e.notVisible?[tU(a2,[a,n])]:[tU(a3,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[tU("screenshot",[tT(tB(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw tK("Maestro scroll options are not supported yet.");return tU("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[tU(a6,[no(tT(e,t)),"5000","down"])];if(!tF(e))throw new s("INVALID_ARGS","scrollUntilVisible expects a string or map.");tG(e,"scrollUntilVisible",["element","direction","timeout"]);let r=ni(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?na(e.direction,"scrollUntilVisible.direction"):"down";return[tU(a6,[r,String(tj(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!tF(e))throw new s("INVALID_ARGS","swipe expects a map.");tG(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,a=o,n=t,i=nn("string"==typeof r.direction?r.direction:"up"),tU(a7,[ni(a,"swipe.from",[],n),i,...ns(r)])):"string"==typeof e.direction?tU(a8,["direction",nn(e.direction),...ns(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tH(e.start),end:tH(e.end)};throw tK("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=nr(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return tU("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return tU(a8,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw tK("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[tU("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tB("pressKey",e).toLowerCase();if("back"===t)return tU("back");if("enter"===t||"return"===t)return tU(a5);if("home"===t)return tU("home");throw tK(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[tU("back")],waitForAnimationToEnd:({value:e})=>[tU(a4,[String(tj(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[aY(e,t,r)],runScript:({value:e,context:t})=>{let a;return[tU(a1,[function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runScript file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}((a=function(e,t){if("string"==typeof e)return{file:tT(e,t),env:{}};if(!tF(e))throw new s("INVALID_ARGS","runScript expects a file path string or map.");return tG(e,"runScript",["file","env"]),{file:tT(tB("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(tD(e.env,"runScript.env")).map(([e,r])=>[e,tT(r,t)]))}}(e,t)).file,t)],{...Object.keys(a.env).length>0?{maestro:{runScriptEnv:a.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){if("string"==typeof e)return a.parseRunFlowFile(tT(e,r),r).actions;if(!tF(e))throw new s("INVALID_ARGS","runFlow expects a file path string or map.");tG(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!tF(e))throw new s("INVALID_ARGS","runFlow.when expects a map.");return(tG(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new s("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new nc(function(e){let t=[],r=0;for(;r<e.length;){var a,n;let i=e.slice(r),o=(a=i,/^\s+/.exec(a)?.[0].length??0);if(o>0){r+=o;continue}let l=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(n=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(n)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(n)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(n)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(n);if(l){t.push(l.token),r+=l.length;continue}throw new s("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=tT(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new s("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,a=t,{...void 0!==r.visible?{visibleSelector:ni(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:ni(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...tD(e.env,"runFlow.env"),...r.envOverrides}};return function(e,t){let{visibleSelector:r,notVisibleSelector:a}=t;if(!r&&!a)return e;if(r&&a)throw tK("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[nf("runFlow.when",[n,i],{kind:"maestroRunFlowWhen",mode:n,selector:i,actions:e})]}(function(e,t,r,a,n){if("string"==typeof e.file)return a.parseRunFlowFile(tT(e.file,r),r).actions;if(Array.isArray(e.commands))return n(tM(e.commands),t,r,a);throw new s("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,a,n),i)})(e,t,r,a,nS),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!tF(e))throw new s("INVALID_ARGS","repeat expects a map.");if(tG(e,"repeat",["times","commands","while"]),void 0!==e.while)throw tK("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,nm(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new s("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new s("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let l=tM(e.commands);return Array.from({length:o}).flatMap(()=>n(l,t,r,a))})(e,t,r,a,nS),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!tF(e))throw new s("INVALID_ARGS","retry expects a map.");if(tG(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new s("INVALID_ARGS","retry requires a commands list.");let l=(i=e.maxRetries,o=r,void 0===i?1:nm(i,o,"retry.maxRetries")),u=n(tM(e.commands),t,r,a);return[nf("retry",[String(l)],{kind:"retry",maxRetries:l,actions:u})]})(e,t,r,a,nS)},nv={launchApp:(e,t)=>[aX(void 0,e,t)],scroll:()=>[tU("scroll",["down"])],hideKeyboard:()=>[tU("keyboard",["dismiss"])],eraseText:()=>[nt(void 0)],back:()=>[tU("back")],waitForAnimationToEnd:()=>[tU(a4,["15000"])],stopApp:(e,t)=>[aY(void 0,e,t)]};function nA(e,t,r,a,n){try{return function(e,t,r,a){if("string"==typeof e){var n,i,o;let a;return n=e,i=t,o=r,(a=nv[n])?a(i,o):tN(n)}let l=Object.entries(e);if(1!==l.length)throw new s("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[u,p]=l[0],d=ny[u];return d?d({value:p,config:t,context:r,deps:a,name:u}):tN(u)}(e,t,a,n)}catch(e){if(e instanceof s&&!/\bline \d+\b/.test(e.message))throw new s(e.code,`${e.message} (line ${r})`,e.details);throw e}}function nS(e,t,r,a){return e.flatMap((e,n)=>nA(e,t,n+1,r,a))}function nI(e,t){let{config:r,commands:a}=nb(tO(e)),n={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:a,context:n}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...a,...Array.from({length:t.onFlowComplete?.length??0},()=>a.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let a=o[e]??e+1,i=nA(r,t,a,n,{parseRunFlowFile:n_});s.push(...i),i.forEach(()=>l.push(a))}return function(e,t){let r=[],a=[];for(let n=0;n<e.length;n+=1){let i=e[n],o=function(e,t,r){var a;let n=function(e,t,r){let a=e[r],n=e[r+1],i=e[r+2];if(i?.command!==a5||a.flags?.maestro?.optional===!0)return null;let o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(n),s=function(e){if(e?.command!==a9)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);return n&&null!==o&&null!==s?{action:a,nextAction:n,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!n)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:p}=n;return(a=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(a.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[p,p,t[r+2]??p],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[p],consumed:1}}(e,t,n);if(o){r.push(...o.actions),a.push(...o.actionLines),n+=o.consumed-1;continue}r.push(i),a.push(t[n]??1)}return{actions:r,actionLines:a}}(s,l)}({config:r,commands:a,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),a=-1===r?0:r+1,n=[];for(let e=a;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&n.push(e+1);return n}(e),context:n});return{actions:i,actionLines:o,metadata:{env:r.env}}}function nb(e){if(0===e.length)throw new s("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:tM(e[0])};let t=function(e){if(!tF(e))throw new s("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.name&&e.name.length>0?{name:e.name}:{},..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...tF(e.env)?{env:tD(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:tM(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:tM(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new s("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:tM(r)}}function n_(e,a){let n=function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}(e,a);if(a.visitedPaths.has(n))throw new s("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(a.visitedPaths);return o.add(n),nI(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let nk=/[*?[\]{}]/;function nN(e,t,a,n,i=0){let o=r.basename(a,r.extname(a)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${o?`-${o}`:""}:attempt-${i+1}`}function nD(e,t){return"number"==typeof e?e:t}function nx(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function nR(e,a,n){var i,o;let l=ef.expandHome(e,a);if(t.existsSync(l)){let a=t.statSync(l);if(a.isDirectory())return{paths:[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:l}).map(e=>r.join(l,e))),source:"directory"};if(a.isFile()){if(!n.has(r.extname(l)))throw new s("INVALID_ARGS",`test does not support this file type: ${e}`);return{paths:[l],source:"file"}}return{paths:[],source:"file"}}if(i=e,!nk.test(i)&&(o=l,!nk.test(o)))throw new s("INVALID_ARGS",`test input not found: ${e}`);let u=r.isAbsolute(l)?l:e;return{paths:t.globSync(u,{cwd:r.isAbsolute(l)?void 0:a}).map(e=>r.isAbsolute(e)?e:r.resolve(a,e)).filter(e=>n.has(r.extname(e))&&function(e){try{return t.statSync(e).isFile()}catch{return!1}}(e)),source:"glob"}}function nM(e,t){let r=nP(e),a=nP(t);return r!==a?r-a:e.localeCompare(t)}function nP(e){return+(".ad"===r.extname(e))}function nL(e){return[...new Set(e.map(e=>r.normalize(e)))]}function nO(e){return"maestro"===e}let nE=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function nC(e){var t,r,a,n;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&tc(i)||(a=s.code,n=s.message,o=`${a}
23
- ${n}`.toLowerCase(),nE.some(e=>o.includes(e))))}async function n$(e){let a,n,{filePath:i,sessionName:s,requestId:l,parentRequestId:u,timeoutMs:p,platform:d,target:c,artifactsDir:f,shard:m,progress:h,runReplay:g,cleanupSession:w,finalizeAttempt:y}=e;O(l);let v=function(e,t){if(!t||t===e)return()=>{};let r=eG(t);if(!r)return()=>{};let a=()=>{eN(e)};return r.aborted?(a(),()=>{}):(r.addEventListener("abort",a,{once:!0}),()=>{r.removeEventListener("abort",a)})}(l,u),A=new Set,S=!1,I=Date.now(),b=function(e){let{artifactsDir:a,artifactPaths:n,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:u,target:p}=e;if(!a)return;let d=r.join(a,"replay-timing.ndjson");return t.mkdirSync(r.dirname(d),{recursive:!0}),t.writeFileSync(d,""),n.add(d),nq(d,{type:"replay_test_attempt_start",ts:new Date().toISOString(),replayPath:i,session:o,requestId:s,timeoutMs:l,platform:u,target:p}),d}({artifactsDir:f,artifactPaths:A,filePath:i,sessionName:s,requestId:l,timeoutMs:p,platform:d,target:c}),_=ek(h,async()=>await g({filePath:i,sessionName:s,platform:d,target:c,requestId:l,artifactsDir:f,artifactPaths:A,tracePath:b,shard:m})).catch(e=>({ok:!1,error:o(e)})).finally(()=>{v(),eO(l)});try{n="number"==typeof p?await Promise.race([_,new Promise(e=>{a=setTimeout(()=>{S=!0,eN(l),e(function(e,t=[]){return{ok:!1,error:{code:"COMMAND_FAILED",message:`TIMEOUT after ${e}ms`,hint:"Replay test timeouts are cooperative; the active command may take a short grace period to stop.",details:{reason:"timeout",timeoutMs:e,timeoutMode:"cooperative",artifactPaths:t}}}}(p,[...A]))},p)})]):await _,nq(b,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:s,ok:n.ok,timedOut:S,durationMs:Date.now()-I,errorCode:n.ok?void 0:n.error.code})}finally{var k,N,D;let e,t;a&&clearTimeout(a),S&&(await nV(_)||((k=n)&&!k.ok&&(k.error.details={...k.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),tv({level:"warn",phase:"test_timeout_cleanup_race",data:{session:s,requestId:l,graceMs:2e3}}),nU({replayPromise:_,cleanupSession:w,sessionName:s,requestId:l})));let r=await nF({finalizeAttempt:y,sessionName:s,artifactPaths:A,artifactsDir:f,tracePath:b});n?.ok&&r&&!r.ok&&(N=n,D=`Replay test finalization failed: ${r.error.message}`,t=Array.isArray((e=N.data??={}).warnings)?e.warnings.filter(e=>"string"==typeof e):[],e.warnings=[...t,D]);let i=Date.now();try{nq(b,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:s}),await w(s),nq(b,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!0,durationMs:Date.now()-i})}catch(t){let e=o(t);nq(b,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),tv({level:"warn",phase:"test_cleanup_failed",data:{session:s,error:e.message}})}}return n??{ok:!1,error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"}}}async function nV(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function nU(e){let{replayPromise:t,cleanupSession:r,sessionName:a,requestId:n}=e;try{await t}finally{try{await r(a)}catch(e){tv({level:"warn",phase:"test_late_cleanup_failed",data:{session:a,requestId:n,error:o(e).message}})}}}async function nF(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let s=Date.now();nq(i,{type:"replay_test_finalize_start",ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i});return nq(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-s,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let e=o(t);return nq(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:e.code}),tv({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function nq(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
24
- `)}async function nG(e){var t,a,n;let i,o=function(e){var t;let a,{entry:n,cwd:i,retries:o,suiteArtifactsDir:s,shard:l}=e;return{testStartedAt:Date.now(),testArtifactsDir:r.join(s,...l?[`shard-${l.shardIndex+1}`]:[],(t=n.path,(0===(a=i?r.relative(i,t):r.basename(t)).length||a.startsWith("..")?r.basename(t):a).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),maxAttempts:o+1}}(e),s=await nT(e,o);return t=e,a=o,n=s,i=Date.now()-a.testStartedAt,n.finalResponse?.ok?function(e,t,r,a){var n;let{entry:i,suiteIndex:o,suiteTotal:s,shard:l}=e,u=r.finalResponse;if(!u?.ok)throw Error("Expected passing replay test response.");return eH({type:"replay-test",file:i.path,title:i.title,status:"pass",index:o,total:s,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,...nK(l)}),{file:i.path,title:i.title,session:r.finalSessionName,status:"passed",durationMs:a,finalAttemptDurationMs:r.finalAttemptDurationMs,attempts:r.attempts,artifactsDir:t.testArtifactsDir,...(n=u,{replayed:"number"==typeof n.data?.replayed?n.data.replayed:0,healed:"number"==typeof n.data?.healed?n.data.healed:0}),...function(e){if(!Array.isArray(e))return{};let t=e.filter(e=>"string"==typeof e);return t.length>0?{warnings:t}:{}}(u.data?.warnings),...nH(u.data?.snapshotDiagnostics),...function(e){return nK(e)}(l),...r.attemptFailures.length>0?{attemptFailures:r.attemptFailures}:{}}}(t,a,n,i):function(e,t,r,a){var n,i;let{entry:o,suiteIndex:s,suiteTotal:l,shard:u}=e,p=(n=r.finalResponse)&&!n.ok?n.error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return eH({type:"replay-test",file:o.path,title:o.title,status:"fail",index:s,total:l,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,message:p.message,...nK(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:p,...nH((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return nK(e)}(u)}}(t,a,n,i)}async function nT(e,t){!function(e,t){let{entry:r,sessionName:a,suiteInvocationId:n,caseIndex:i,suiteIndex:o,suiteTotal:s,shard:l}=e;eH({type:"replay-test",file:r.path,title:r.title,status:"start",index:o,total:s,maxAttempts:t.maxAttempts,session:nN(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...nK(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let d=0;d<=e.retries&&!ew(e.requestId);d+=1){var a,n,i,o,s,l,u,p;let c=await nB(e,t,d);if((a=r).finalResponse=(n=c).response,a.finalSessionName=n.sessionName,a.attempts=n.attempt,a.finalAttemptDurationMs=n.durationMs,n.response.ok||a.attemptFailures.push({attempt:n.attempt,message:n.response.error.message,durationMs:n.durationMs}),i=e,o=c.response,s=d,o.ok||ew(i.requestId)||nC(o)||s>=i.retries)break;l=e,u=t,(p=c).response.ok||eH({type:"replay-test",file:l.entry.path,title:l.entry.title,status:"fail",index:l.suiteIndex,total:l.suiteTotal,attempt:p.attempt,maxAttempts:u.maxAttempts,durationMs:p.durationMs,retrying:!0,message:p.response.error.message,session:p.sessionName,artifactsDir:u.testArtifactsDir,...nK(l.shard)})}return r}async function nB(e,a,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,suiteIndex:p,suiteTotal:d,requestId:c,timeoutMs:f,shard:m}=e,h=n+1,g=Date.now(),w=nN(s,l,o.path,u,n),y=r.join(a.testArtifactsDir,`attempt-${h}`);i=o.path,t.mkdirSync(y,{recursive:!0}),function(e,a){var n;let i,o=r.join(a,"replay.ad");if(t.copyFileSync(e,o),n=e,".yml"!==(i=r.extname(n).toLowerCase())&&".yaml"!==i)return;let s=r.join(a,r.basename(e));r.resolve(s)!==r.resolve(o)&&t.copyFileSync(e,s)}(i,y);let v=function(e){let{requestId:t,suiteInvocationId:a,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return ey(`${t??a}${l}:test:${i+1}:${r.basename(n)}:attempt:${o+1}`,a)}({requestId:c,suiteInvocationId:l,filePath:o.path,caseIndex:u,attemptIndex:n,shardIndex:m?.shardIndex}),A=await n$({filePath:o.path,sessionName:w,requestId:v,parentRequestId:c,timeoutMs:f,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:y,shard:m,progress:{file:o.path,title:o.title,index:p,total:d,attempt:h,maxAttempts:a.maxAttempts,session:w,artifactsDir:a.testArtifactsDir,...nK(m)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),S=Date.now()-g;return!function(e){var a;let n,{response:i,filePath:o,sessionName:s,attempts:l,maxAttempts:u,attemptArtifactsDir:p}=e,d=[...Array.isArray(n=(a=i).ok?a.data?.artifactPaths:a.error.details?.artifactPaths)?[...new Set(n.filter(e=>"string"==typeof e))]:[]];i.ok||"string"!=typeof i.error.logPath||d.push(i.error.logPath);let c=function(e,a){let n=[],i=new Map;for(let o of e){if(!function(e){try{return t.statSync(e).isFile()}catch{return!1}}(o))continue;let e=function(e,t){let a=r.extname(e),n=a?e.slice(0,-a.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${a}`}(r.basename(o),i),s=r.join(a,e);r.resolve(o)!==r.resolve(s)&&t.copyFileSync(o,s),n.push(s)}return n}(d,p),f=[`file: ${o}`,`session: ${s}`,`attempt: ${l}/${u}`,`status: ${i.ok?"passed":"failed"}`];if(i.ok){let e="number"==typeof i.data?.replayed?i.data.replayed:0,t="number"==typeof i.data?.healed?i.data.healed:0;f.push(`replayed: ${e}`,`healed: ${t}`)}else f.push(`code: ${i.error.code}`,`message: ${i.error.message}`),i.error.hint&&f.push(`hint: ${i.error.hint}`),i.error.diagnosticId&&f.push(`diagnosticId: ${i.error.diagnosticId}`),i.error.logPath&&f.push(`logPath: ${i.error.logPath}`),i.error.details?.reason==="timeout"&&f.push("timeoutMode: cooperative");c.length>0&&f.push(`copiedArtifacts: ${c.map(e=>r.basename(e)).join(", ")}`);let m=r.join(p,"result.txt"),h=`${f.join("\n")}
25
- `;t.writeFileSync(m,h),i.ok||t.writeFileSync(r.join(p,"failure.txt"),h)}({response:A,filePath:o.path,sessionName:w,attempts:h,maxAttempts:a.maxAttempts,attemptArtifactsDir:y}),{response:A,sessionName:w,attempt:h,durationMs:S}}function nH(e){let t=tZ(e);return t?{snapshotDiagnostics:t}:{}}function nK(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function nj(e,t,r){let a=function(e){let t=nz(e?.shardAll,"--shard-all"),r=nz(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new s("INVALID_ARGS","--shard-all and --shard-split are mutually exclusive");return void 0!==t?{kind:"all",count:t}:void 0!==r?{kind:"split",count:r}:void 0}(e);if(!a||0===t.length)return;let n=await nW(e,a.count);return{mode:a.kind,shardCount:a.count,total:r+("all"===a.kind?t.length*a.count:t.length),shards:n.map((e,r)=>({shardIndex:r,shardCount:a.count,device:e,entries:"all"===a.kind?t:t.filter((e,t)=>t%a.count===r)}))}}function nz(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new s("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function nW(e,t){var r,a,n,i,o,l,u,p,d;let c,f,m=(r=e,"string"!=typeof(c=r?.device)||0===c.trim().length?[]:c.split(",").map(e=>e.trim()).filter(Boolean)),h=(n=await ec((a=e,f=tm(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:to({simulatorSetPath:tu(a?.iosSimulatorDeviceSet),platform:a?.platform,target:a?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(l=n,u=i,p=o,u.map(e=>{let t=nX(e),r=l.find(r=>nJ(r,p)&&(r.id===e||nX(r.name)===t));if(!r)throw new s("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!nJ(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(nY));if(h.length<t){throw new s("DEVICE_NOT_FOUND",`test sharding requires ${(d=t,`${d} device${1===d?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function nJ(e,t){return!(!tl(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function nX(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function nY(e,t){return e.id.localeCompare(t.id)}async function nZ(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return E("INVALID_ARGS","test requires at least one path or glob");try{var s,l,u,p;let e,i,d,c,f,m,h=Date.now(),g=await nQ(t);s=g,eH({type:"replay-test-suite",status:"start",total:s.total,runnable:s.runnable.length,skipped:s.entries.length-s.runnable.length,artifactsDir:s.suiteArtifactsDir,shardMode:s.shardPlan?.mode,shardCount:s.shardPlan?.shardCount});let w=g.shardPlan?function(e){let{entries:t,total:r}=e,a=[];for(let[e,n]of t.entries())"skip"===n.kind&&(eH({type:"replay-test",file:n.path,status:"skip",index:e+1,total:r,message:n.message}),a.push({file:n.path,status:"skipped",durationMs:0,reason:n.reason,message:n.message}));return a}({entries:g.entries,total:g.total}):[];g.shardPlan?w.push(...await n0({shards:g.shardPlan.shards,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o})):w.push(...await n2({discoveryEntries:g.entries,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o}));let y=(l=g.total,u=w,p=Date.now()-h,e=u.filter(e=>"passed"===e.status).length,d=(i=u.filter(e=>"failed"===e.status)).length,c=u.filter(e=>"skipped"===e.status).length,f=e+d,m=t0(u.map(e=>"skipped"===e.status?void 0:e.snapshotDiagnostics)),{total:l,executed:f,passed:e,failed:d,skipped:c,notRun:Math.max(0,l-f-c),durationMs:p,failures:i,tests:u,...m?{snapshotDiagnostics:m}:{}});return{ok:!0,data:y}}catch(t){let e=i(t);return E(e.code,e.message)}}async function nQ(e){var a,n,i,o;let l=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,l=new Set(nO(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!nO(i))return[...new Set(e.flatMap(e=>nR(e,a,n).paths))].map(e=>r.normalize(e)).sort((e,t)=>e.localeCompare(t));let o=[],s=[];for(let i of e){let e=function(e,a,n){let i=ef.expandHome(e,a);return t.existsSync(i)&&t.statSync(i).isDirectory()?{paths:function e(a,n){let i=[],o=t.opendirSync(a);try{let t;for(;null!==(t=o.readSync());){let o=r.join(a,t.name);t.isDirectory()?i.push(...e(o,n)):t.isFile()&&n.has(r.extname(t.name))&&i.push(o)}}finally{o.closeSync()}return i}(i,n),source:"directory"}:nR(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?nL(e.paths):e.paths.map(e=>r.normalize(e)).sort(nM))}return nL([...o,...s.flat()])}(a,n??process.cwd(),l,o),p=[];for(let e of u){var d,c,f,m;let a=t.readFileSync(e,"utf8"),n=tC(a),s=(d=a,c=e,nO(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=nb(tO(e));return t.name}(d):void 0);if(!i){p.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){nO(o)?p.push({kind:"run",path:e,title:s,metadata:n}):p.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${i}`});continue}f=i,m=n.platform,("apple"===f?"apple"===m||"ios"===m||"macos"===m:m===f)&&p.push({kind:"run",path:e,title:s,metadata:n})}if(0===p.filter(e=>"run"===e.kind).length){let e=i?` for --platform ${i}`:"";throw new s("INVALID_ARGS",`No replay tests matched${e}.`)}return p}({inputs:(n=e).positionals??[],cwd:n.meta?.cwd,platformFilter:n.flags?.platform,replayBackend:n.flags?.replayBackend}),u=l.flatMap((e,t)=>"run"===e.kind?[{entry:e,suiteIndex:t+1}]:[]),p=l.length-u.length,d=(a=e.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),c=await nj(e.flags,u,p);return{entries:l,runnable:u,shardPlan:c,suiteInvocationId:d,suiteArtifactsDir:(i=e,o=d,function(e){let{artifactsDir:t,cwd:a,suiteInvocationId:n}=e,i=ef.expandHome(t??".agent-device/test-artifacts",a);return r.join(i,n)}({artifactsDir:"string"==typeof i.flags?.artifactsDir?i.flags.artifactsDir:void 0,cwd:i.meta?.cwd,suiteInvocationId:o})),total:c?.total??l.length}}async function n0(e){return(await Promise.allSettled(e.shards.map(async t=>await n1({...e,shard:t})))).flatMap((t,r)=>{var a,n;let i;if("fulfilled"===t.status)return t.value;let s=e.shards[r];return s?[(a=s,n=e.sessionName,i=o(t.reason),{file:a.entries[0]?.entry.path??`shard-${a.shardIndex+1}`,session:n3(n,a),status:"failed",durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:a.shardIndex,shardCount:a.shardCount,deviceId:a.device.id})]:[]})}async function n1(e){let{shard:t,sessionName:r}=e;return await n5({...e,entries:t.entries,sessionName:n3(r,t),shard:t})}function n3(e,t){return`${e}:shard-${t.shardIndex+1}`}async function n2(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d}=e,c=[],f=0;for(let[e,m]of t.entries()){if(ew(i))break;if("skip"===m.kind){eH({type:"replay-test",file:m.path,status:"skip",index:e+1,total:l,message:m.message}),c.push({file:m.path,status:"skipped",durationMs:0,reason:m.reason,message:m.message});continue}f+=1;let t=await nG({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:nx(o?.retries,m.metadata.retries),timeoutMs:nD(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d});if(c.push(t),n4(t,o,i))break}return c}async function n5(e){let{entries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c}=e,f=[];for(let[e,m]of t.entries()){if(ew(i))break;let{entry:t,suiteIndex:h}=m,g=await nG({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:nx(o?.retries,t.metadata.retries),timeoutMs:nD(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c});if(f.push(g),n4(g,o,i))break}return f}function n4(e,t,r){return ew(r)||t?.failFast===!0||nC(e)}let n6={maestro:{parse:function(e,t={}){var a;let n;return nI(e,(n=(a=t).visitedPaths??new Set,a.sourcePath&&n.add(r.resolve(a.sourcePath)),{baseDir:a.sourcePath?r.dirname(a.sourcePath):void 0,platform:tP(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function n8(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,a=ra(null!==r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r}}async function n7(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(rr(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=n.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),rr(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&n9(r)?t.slice(0,-1):t}(e),a=r[0]??"";a&&!a.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=t4(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=n8(e.positionals??[]);r&&t.push(r)}return T(t).filter(e=>e.trim().length>0)})(t).map(e=>ri(e)).filter(e=>null!==e);if(0===o.length)return null;let s=rr(t.command)||"fill"===t.command,l=rr(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await ie(i,t,a,s,n);for(let e of o){let r=t1(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=t6(r.node,i.device.platform,{action:"fill"===t.command?"fill":rr(t.command)?"click":"get"}).join(" || ");if(rr(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&n9(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=v(t);if(!e)continue;return{...t,positionals:[a,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,a]}}if("is"===t.command){let{predicate:e,split:r}=t4(t.positionals);if(!e)continue;let n=r?.rest.join(" ").trim()??"",i=[e,a];return"text"===e&&n.length>0&&i.push(n),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=n8(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function n9(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function ie(e,t,r,a,n){let i=el(await p(e.device,"snapshot",[],t.flags?.out,{...ed(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return B(e,i),n.set(e.name,e),i}let it=.35,ir=120,ia=360,ii=8;function io(e,t){return Math.round(Math.min(ia,Math.max(ir,"number"==typeof e?e*it:0,1.5*t)))}let is=new WeakMap,il=new WeakMap,iu=new WeakMap;function ip(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function id(e){var t;let r,a=!0===e.raw||"1"===process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...a?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&(t=e.scope,(r=Z(ic(n.data)))&&is.set(t,r)),n}function ic(e){return Array.isArray(e?.nodes)?e:void 0}function im(e,t){e&&il.set(e,{selector:t})}function ih(e){e&&iu.delete(e)}let ig=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function iw(e,t,r,a,n,i={}){let o=iI(e,t,a);if(r.childOf){let t=iI(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=t8(e.nodes);o=o.filter(r=>t.some(t=>t5(e.nodes,r,t,n)))}let s=iv({nodes:e.nodes,matches:o,platform:a}),l=ik(e.nodes,s.matches,r.index,iS(t),n,!0===i.requireOnScreen,i.promoteTapTarget,i.preferredContext);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&0===s.matches.length?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}function iy(e,t,r,a){let n=iI(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=iv({nodes:e.nodes,matches:n,platform:r}),o=ik(e.nodes,i.matches,void 0,iS(t),a,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:i.matches.length}:{ok:!1,message:i.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:n.length>0?`Maestro selector matched ${n.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function iv(e){let t=e.matches.filter(t=>rt({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=ta(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tr(a),i=n.filter(t=>rt({predicate:"visible",node:t,nodes:e,platform:r}).pass);if(0===i.length)return 0===n.length?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(i.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&0===s.length}}(e.nodes,t,e.platform);return{matches:r.matches,blockedByReactNativeOverlay:r.blockedByReactNativeOverlay}}function iA(e){return e?.platform==="android"?"android":"ios"}function iS(e){let t=ro(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),a=r[0];return a&&r.every(e=>e===a)?a:null}function iI(e,t,r,a={}){for(let n of ro(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!t7(e,t,r)||t.terms.every(t=>(function(e,t,r,a){var n,i,o;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?t7(e,{raw:t.key,terms:[t]},r):ib((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:t3(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function ib(e,t,r={}){var a;let n=e??"",i=rn(n),o=rn(t);if(i===o||!1!==r.allowLeadingCompositeLabelMatch&&function(e,t){if(!e||!t||!e.startsWith(t))return!1;let r=e.at(t.length);return","===r||":"===r||";"===r}(i,o))return!0;if(a=t,!/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(a))return!1;try{return new RegExp(t).test(n)}catch{return!1}}function i_(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let a=function(e,t,r){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);)if(a.rect)return a.rect.width>0&&a.rect.height>0?a.rect:null;return null}(e,t,r);return a?{rect:a,inherited:!0}:null}function ik(e,t,r,a,n,i=!1,o=!1,s){var l,u,p,d,c,f,m,h,g,w,y,v,A,S,I,b,_,k,N;let D,x,R,M,P=t8(e),L=(l=e,u=t,p=P,d=a,c=r,f=n,m=i,R=(x=(D=u.map(e=>{var t;let r;return(r=i_(l,t=e,p))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?x:D,d&&void 0===c?(h=R,g=f,w=m,M=h.filter(e=>{var t,r;let a,n;return t=e.rect,r=g,a=r?.referenceWidth??1/0,n=r?.referenceHeight??1/0,t.x<a&&t.y<n&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:h):D),O=function(e,t,r,a,n,i){var o,s,l,u,p,d,c;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=a,u=n,p=i,u&&l?function(e,t,r,a){let n=t.filter(e=>0===iC(e.node,r));if(n.length>=2){let t=iD(e,n,r,a);if(t)return t}let i=t.filter(e=>1===iC(e.node,r));return n.length>0||i.length<2?null:iD(e,i,r,a)}(o,s,l,p)??iN(o,s,l,p):iN(o,s,l,p));return(d=f,c=a,n&&c&&d)?function(e,t,r){var a,n,i,o,s,l,u,p,d,c,f,m,h,g,w,y,v,A;let S,I,b,_,k,N,D,x;if(a=t,n=r,!(("cell"===(S=t9(a.node.type??""))||"other"===S||"scrollview"===S||"scroll-area"===S)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=iC(a.node,n)))return null;let R=(i=e,o=t,s=r,l=t8(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&t5(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=t9(t.type??""))&&"cell"!==n&&"other"!==n||1>=iC(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!iO(r,t.rect)&&iP(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(b=Math.floor((I=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),I[b]??0),P=function(e,t){let r=[],a=e.x,n=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(n,i.x+i.width);t>a&&r.push({x:a,width:t-a}),a=Math.max(a,o)}return n>a&&r.push({x:a,width:n-a}),r}(t.rect,R.map(e=>e.rect)),L=(u=t,p=r,d=P,c=M,N=d.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),D=(f=u,m=p,_=d.find(e=>1>Math.abs(e.x-f.rect.x)),k=Math.max(48,Math.min(220,8*m.length+24)),(h=f,g=m,w=_,y=k,w&&"scrollview"===t9(h.node.type??"")&&1>=iC(h.node,g)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&w.width<=.55*h.rect.width&&w.width>=.6*y)?{x:f.rect.x,width:Math.min(k,_.width)}:null),x=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!x?D:1===N.length?N[0]??null:D);return L?(v=t,A=L,{...v,rect:{x:A.x,y:v.rect.y,width:A.width,height:v.rect.height}}):null}(e,f,a)??f:f}(e,L,r,a,o,s);return y=e,v=O,A=P,S=o,I=n,v?S?(b=y,_=v,k=A,N=I,(iL(_.node)?null:t2(b,_.node,k,e=>{if(!iL(e))return null;let t=i_(b,e,k);return t&&function(e,t,r){var a,n;if(!iO(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>iP(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=iR(t),o=iR(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(_.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:v.node,rect:v.rect}):{node:v.node,rect:v.rect}:null}function iN(e,t,r,a){return(function(e,t,r,a){var n;let i,o,s;if(!r||t.length<2)return t;let l=t.filter(e=>0===iC(e.node,r));if(l.length<2)return t;let u=t8(e),p=l.map(t=>({candidate:t,container:ix(e,t.node,u)})).filter(e=>!!e.container);if(p.length<2||p.length!==l.length)return t;let d=p.filter(e=>{var t;return t=e,p.some(e=>e!==t&&t.container.index!==e.container.index&&iE(t.container.rect,e.container.rect)>=.6)});if(d.length<2)return t;let c=(o=Math.max(...i=(n=d).map(e=>iR(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>iR(e.container.rect)===o).map(e=>e.candidate));if(c.length>0)return c;let f=function(e,t,r,a){if(!r)return[];let n=ix(e,r.node,a),i=n&&iO(n.rect,r.rect)?n:null,o=t.map(e=>({entry:e,score:function(e,t,r){if(r)return e.index===r.index?0:.6>iE(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(iE(e.rect,t.rect)>=.6)return 0;let a=e.index-t.node.index;return a>=0?a:1e5+Math.abs(a)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,d,a,u);if(f.length>0)return f;let m=Math.max(...d.map(e=>e.container.index)),h=d.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,a).sort((e,t)=>(function(e,t,r){var a,n;let i=function(e,t,r){if(r){let a=iC(e.node,r)-iC(t.node,r);if(0!==a)return a}let a=iM(e.node)-iM(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&iM(e.node)===iM(t.node)?iR(t.rect)-iR(e.rect):iR(e.rect)-iR(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(a=e.rect,n=t.rect,Math.round(a.x)!==Math.round(n.x)||Math.round(a.y)!==Math.round(n.y)||Math.round(a.width)!==Math.round(n.width)||Math.round(a.height)!==Math.round(n.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function iD(e,t,r,a){let n=t8(e),i=t.filter(r=>{var a;return(a=r).rect.width>=16&&a.rect.width<=260&&a.rect.height>=24&&a.rect.height<=80&&t.some(t=>{var a,i,o,s;return a=e,i=t,o=r,s=n,!(i.node.index===o.node.index||!iO(i.rect,o.rect)||iR(i.rect)<2*iR(o.rect))&&t5(a,o.node,i.node,s)})});return iN(e,i,r,a)}function ix(e,t,r){return t2(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=t9(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function iR(e){return e.width*e.height}function iM(e){return ig.get(t9(e.type??""))??3}function iP(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}function iL(e){let t=t9(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function iO(e,t){return t.x>=e.x-1&&t.y>=e.y-1&&t.x+t.width<=e.x+e.width+1&&t.y+t.height<=e.y+e.height+1}function iE(e,t){let r=Math.max(e.x,t.x),a=Math.min(e.x+e.width,t.x+t.width),n=Math.max(e.y,t.y);return Math.max(0,a-r)*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-n)/Math.max(1,Math.min(iR(e),iR(t)))}function iC(e,t){let r=[e.label,t3(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rn(e)===rn(t))?1:r.some(e=>ib(e,t))?2:3}async function i$(e){let t=iJ(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=iW(e.baseReq,t.selector);return r?await iV(e,t,r):await iF(e,t)}async function iV(e,t,r){let a=Date.now(),n=await iU(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await iX(e,t.selector,"assertVisible");if(!r.visible){let n=iz(e.baseReq,t,r,a);return"return"===n.kind?n.response:await iF(e,t)}}return im(e.scope,t.selector),iQ({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await iq(e,t,n,a)}async function iU(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function iF(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await iX(e,t.selector,"assertVisible");if(l.visible)return iQ(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=iz(e.baseReq,t,l,n);if("return"===u.kind)return u.response;let p=function(e){var t,r,a,n;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,a=e.startedAt,n=e.deadlineMs,!t&&r-a<n)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:i});if("capture-again"===p){o=!0;continue}if("finish"===p)break;await rs(250)}let s=r??ip("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await iG(e,t,a);return l||i0(s,a,e.baseReq)}async function iq(e,t,r,a){let n=await iX(e,t.selector,"assertVisible");if(n.visible)return iQ(n.response,t.selector,a);let i=iz(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await iG(e,t,n.snapshot);return o||i0(r,n.snapshot,e.baseReq)}async function iG(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=iu.get(e);return iu.delete(e),t}(e.scope);return a?"tap"===a.kind?await iT(e,t,r,a):await iB(e,t,a):null}async function iT(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=iA(e.baseReq.flags),o=Z(t),s=iw(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:e0(s.rect)}};let l=iS(r.selector);return l&&(a=t,(n=l.trim().toLowerCase())&&a.nodes.some(e=>[e.label,e.value,e.identifier].some(e=>e?.trim().toLowerCase().includes(n))))?{ok:!0,target:{kind:"text",query:l}}:{ok:!1}}(e,r,a);return n.ok&&(tv({level:"info",phase:"maestro_assert_visible_retry_tap",data:{selector:t.selector,tapSelector:a.selector,originalPoint:a.point,retryTarget:n.target,timeoutMs:5e3}}),(await iK(e,n.target)).ok)?await iH(e,t,"retryTap"):null}async function iB(e,t,r){return(tv({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await ij(e,r)).ok)?await iH(e,t,"retrySwipe"):null}async function iH(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=iW(e.baseReq,a.selector);if(!n)return await iF(e,a);let i=Date.now(),o=await iU(e,a,n);return o.ok?(im(e.scope,a.selector),iQ({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await iq(e,a,o,i)}async function iK(e,t){return"text"===t.kind?await e.invoke({...e.baseReq,command:"find",positionals:[t.query,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}}):await e.invoke({...e.baseReq,command:"click",positionals:[String(t.point.x),String(t.point.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}async function ij(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function iz(e,t,r,a){var n,i,o,s,l,u,p;return!(n=r.response).ok&&"COMMAND_FAILED"===n.error.code&&n.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=iY(iS(e));if(!iZ(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>iY(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!iZ(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,p=a,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-p,timeoutMs:u}})}:{kind:"continue"}}function iW(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:iS(t)}function iJ(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:ip("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:ip("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function iX(e,t,r){let a=await id(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=ic(s.data);if(!l)return{visible:!1,response:ip("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=iy(l,i,iA(n.baseReq.flags),Z(l));return u.ok?(im(n.scope,i),{visible:!0,response:{ok:!0,data:{selector:i,matches:u.matches,nodeIndex:u.node.index,nodeType:u.node.type,nodeLabel:u.node.label,nodeIdentifier:u.node.identifier,rect:u.rect}}}):{visible:!1,response:ip("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function iY(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function iZ(e){return"loading"===e||"loading..."===e}function iQ(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function i0(e,a,n){var i;if(e.ok||!a)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,a){try{t.mkdirSync(a,{recursive:!0});let n=r.join(a,"failure-snapshot.json"),i=r.join(a,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
26
- `);let o=eY(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return t.writeFileSync(i,`${o.join("\n")}
27
- `),[n,i]}catch{return[]}}(a,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function i1(e){let t,r=iJ(e.positionals,{command:"assertNotVisible",defaultTimeoutMs:3e3});if(!r.ok)return r.response;let a=Date.now(),n=0;for(;Date.now()-a<=r.timeoutMs;){let i=await iX(e,r.selector,"assertNotVisible");if(!i.visible&&i.infrastructureFailure)return i.response;if(i.visible)n=0,t=i.response;else{n+=1;let e=Date.now()-a;if(n>=2||e>=r.timeoutMs)return{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:e,timeoutMs:r.timeoutMs}}}await rs(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:ip("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function i3(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return ip("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await id(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=ic(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?a?t===a?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:a}:{done:!0,response:e}:{done:!1}}(n,t,a);if(i.done)return i.response;t=i.signature??t,r=n,await rs(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function i2(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return ip("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return ip("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=iS(n),u=Math.max(1,Math.ceil(s/500)),p=null;for(let t=0;t<u;t+=1){let r=await on(e,n,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(p=r,t===u-1)break;let a=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!a.ok)return a}return t=p,r=n,a=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${a}ms for selector: ${r}. Last wait: ${t.error.message}`}}:ip("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function i5(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return ip("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await id(e);if(!i.ok)return i;let o=ic(i.data);if(!o)return ip("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=Z(o);if(!s)return ip("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=ez(s,a,n),u=await e.invoke({...e.baseReq,command:"click",positionals:[String(l.x),String(l.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});return u.ok&&ih(e.scope),u}async function i4(e){let t=await i6(e);if(t)return t;let r=await oe(e);return r.ok?await i9(e,r,r.durationMs):r.response}async function i6(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==iA(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function i8(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return ip("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:ip("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),p=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<p;){let t=await oi(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rs(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??ip("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function i7(e){let[t,r="up",a]=e.positionals;if(!t)return ip("INVALID_ARGS","swipe.label requires a label selector.");let n=await ou(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=e0(e.rect),a=e.frame,n=io(a?.referenceWidth,e.rect.width),i=io(a?.referenceHeight,e.rect.height),o=ii,s=a?a.referenceWidth-o:r.x+n,l=a?a.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:e9(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:e9(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:e9(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:e9(r.x+n,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(n.target,r);return i.ok?await i9(e,i,a):ip("INVALID_ARGS",i.message)}async function i9(e,t,r){var a,n;let i=[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]],o=await e.invoke({...e.baseReq,command:"swipe",positionals:i});return o.ok&&(a=e.scope,n={kind:"swipe",positionals:i},a&&iu.set(a,n)),o}async function oe(e){var t;let r=((t=e.scope)?is.get(t):void 0)??await ot(e);if(!r)return{ok:!1,response:ip("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[a,...n]=e.positionals;return"direction"===a?function(e,t,r){let[a,n]=e;if(!a)return{ok:!1,response:ip("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(a){case"up":case"down":var i,o,s;let l;return i=a,o=t,s=n,{ok:!0,start:e3({x:(l=eJ({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:e3({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=oa(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=or(r,t,i,50,o,50);return{ok:!0,start:ez(t,i,n.startY,{marginPx:s}),end:ez(t,o,n.endY,{marginPx:s}),durationMs:a}}(a,t,r,n);default:return{ok:!1,response:ip("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,iA(e.baseReq.flags)):"percent"===a?function(e,t,r){let[a,n,i,o,s]=e,l=[a,n,i,o].map(Number);if(l.some(e=>!Number.isFinite(e)))return{ok:!1,response:ip("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,p,d,c]=l,f=oa(r,u,p,d,c),m=or(r,t,u,p,d,c);return{ok:!0,start:ez(t,u,f.startY,{marginPx:m}),end:ez(t,d,f.endY,{marginPx:m}),durationMs:s}}(n,r,iA(e.baseReq.flags)):{ok:!1,response:ip("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function ot(e){let t=await id(e);if(t.ok)return Z(ic(t.data))}function or(e,t,r,a,n,i){return"ios"!==e||a!==i||30>Math.abs(n-r)?1:Math.max(1,Math.round(.15*t.referenceWidth))}function oa(e,t,r,a,n){return"android"!==e||r!==n||50!==r||30>Math.abs(a-t)?{startY:r,endY:n}:{startY:65,endY:65}}async function on(e,t,r,a){let n=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(a)]});return n.ok||!r?n:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(a)]})}async function oi(e,t,r){let a=iS(t),n=await oo(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await ol(e,a):{retry:!0,response:n.response}}async function oo(e,t,r){let a=await ou(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await os(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function os(e,t,r,a){let n=e0(r.rect);tv({level:"debug",phase:"maestro_tap_target",data:{selector:t,node:{index:r.node.index,type:r.node.type,label:r.node.label,value:r.node.value,identifier:r.node.identifier,visibleToUser:r.node.visibleToUser},rect:r.rect,point:n}});let i=await e.invoke({...e.baseReq,command:"click",positionals:[String(n.x),String(n.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});if(i.ok){var o,s,l;(o=e.scope)&&il.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&iu.set(s,l)}return{response:i,targetResolved:!0}}async function ol(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(tv({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?(ih(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function ou(e,t,r,a,n){let i=await id({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=ic(i.data);if(!o)return{ok:!1,response:ip("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=Z(o),l=iA(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?il.get(n):void 0;if(!i)return;let o=iy(t,i.selector,r,a);if(o.ok)return tv({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),p=iw(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!p.ok){let e=iS(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rn(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,t3(t),t.identifier,t.value].filter(e=>!!e).map(e=>rn(e));e.some(e=>e===r)?a.push(t):e.some(e=>e.includes(r))&&n.push(t)}return a.length>0?a:n}(e,t),o=iv({nodes:e.nodes,matches:i,platform:r}),s=ik(e.nodes,o.matches,void 0,t,a,!0===n.requireOnScreen,n.promoteTapTarget,n.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return p.ok?{ok:!0,target:{node:p.node,rect:p.rect,frame:s}}:{ok:!1,response:ip("ELEMENT_NOT_FOUND",p.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function op(e){switch(e.command){case a3:return await i$(e);case a2:return await i1(e);case a5:return await od(e);case a4:return await i3(e);case a6:return await i2(e);case a8:return await i4(e);case a7:return await i7(e);case a9:return await i8(e);case ne:return await i5(e);case a1:return function(e){let[r]=e.positionals;if(!r)return ip("INVALID_ARGS","runScript requires a file path.");try{let n=function(e){let{scriptPath:r,env:n}=e,i=t.readFileSync(r,"utf8"),o=Object.create(null);try{var l,u;a.runInNewContext(i,(l=n,u=o,{...l,output:u,json:ng,http:{post:(e,t)=>(function(e,t,r){let a=tY(process.execPath,["-e",nh],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==a.exitCode){let r;throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=a.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:a.exitCode,stderr:a.stderr})}try{return JSON.parse(a.stdout)}catch(r){throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,1e3),stderr:a.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:r,timeout:3e4})}catch(e){throw new s("COMMAND_FAILED",`Maestro runScript failed for ${r}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:r},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new s("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:r,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:n}}}catch(t){let e=i(t);return ip(e.code,e.message,e.details)}}(e);default:return}}async function od(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function oc(e){for(let[t,r]of e.actions.entries()){let a=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!a.ok)return a}return{ok:!0,data:{ran:e.actions.length}}}async function of(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await oc({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(a.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=a}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function om(e){let t=await oh(e,e.control);return t.ok?t.matched?await oy(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function oh(e,t){if("visible"===t.mode)return await og(e,t);let r=await ow(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function og(e,t){let r=Date.now();for(;;){let a=await ow(e,t.selector);if(!a.ok)return{ok:!1,response:a.response};if(a.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await rs(250)}}async function ow(e,t){var r,a;let n,i=await id(e);return i.ok?(r=e,a=t,(n=ic(i.data))?{ok:!0,matched:iy(n,a,iA(r.baseReq.flags),Z(n)).ok}:{ok:!1,response:ip("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function oy(e){let t=await oc({actions:e.control.actions,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return t.ok?{ok:!0,data:{ran:t.data?.ran,condition:e.control.mode,selector:e.control.selector}}:t}async function ov(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,p=tJ(a,n,{file:i,line:o}),d=Date.now();oI(l,{type:"replay_action_start",ts:new Date(d).toISOString(),replayPath:i,line:o,step:s,command:p.command,positionals:p.positionals??[]});let c=await oA({req:t,sessionName:r,resolved:p,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>ov({req:t,sessionName:r,action:e.action,scope:n,filePath:i,line:e.line,step:e.step,tracePath:l,invoke:u})}),f=Date.now();return oI(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:p.command,ok:c.ok,durationMs:f-d,resultTiming:c.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(c.data):void 0,errorCode:c.ok?void 0:c.error.code}),c}async function oA(e){var t;let{req:r,sessionName:a,resolved:n,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,p=(t=r.flags,tS(t,{...n.flags??{}})),d={token:r.token,session:a,flags:p,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await oS({control:n.replayControl,baseReq:d,line:o,step:s,invoke:l,invokeReplayAction:u})??await op({command:n.command,baseReq:d,positionals:n.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...d,command:n.command,positionals:n.positionals??[]});if(c.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(c.data);e&&tX(i,e)}return c}async function oS(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await of({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await om({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function oI(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
28
- `)}async function ob(e){let{req:a,sessionName:n,logPath:o,sessionStore:l,tracePath:u,invoke:p}=e,d=a.positionals?.[0];if(!d)return E("INVALID_ARGS","replay requires a path");let c="",f=new Set;try{var m,h,g,w,y,v,A,S,I,b,_,k,N,D,x,R,M,P,L,O;c=ef.expandHome(d,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),i=e.trimStart()[0];if("{"===i||"["===i)return E("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let C=function(e,t,r={}){var a;let n=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=n6[t];if(!r)throw new s("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return n?{...n.parse(e,{...r,platform:t?.platform,env:(a=t,{...tV(tR(a?.replayShellEnv)),...t$(tL(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...tx(e),metadata:tC(e)}}(e,a.flags,{sourcePath:c}),V=C.metadata,U=V.platform||V.target?{...a,flags:(m=a.flags,h=V,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,F=C.actions,q=C.actionLines;if(a.flags?.replayUpdate===!0&&C.updateUnsupportedMessage)return E("INVALID_ARGS",C.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&V.env&&Object.keys(V.env).length>0)return E("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(a.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(oR(t.flags)||oR(t.runtime))return!0}return!1}(F))return E("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let G=tW({builtins:function(e){let{req:t,sessionName:a,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:a,AD_FILENAME:r.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let p=o.target??n.target;p&&(l.AD_TARGET=p);let d=o.device;"string"==typeof d&&d.length>0&&(l.AD_DEVICE=d);let c="string"==typeof o.serial?o.serial:o.udid;"string"==typeof c&&c.length>0&&(l.AD_DEVICE_ID=c),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:U,sessionName:n,metadata:V,resolvedPath:c}),fileEnv:V.env,shellEnv:tV(tR(a.flags?.replayShellEnv)),cliEnv:t$(tL(a.flags?.replayEnv))}),T=a.flags?.replayUpdate===!0,B=u??l.get(n)?.trace?.outPath,H=[],K=0;for(let e=0;e<F.length;e+=1){let t=F[e];if(!t||"replay"===t.command)continue;!function(e,t,r){let a=$();a&&eH({type:"replay-test",...a,file:a.file||e,status:"progress",stepIndex:t+1,stepTotal:r})}(c,e,F.length);let r=oN(l,n),a=await ov({req:U,sessionName:n,action:t,scope:G,filePath:c,line:q[e]??0,step:e+1,tracePath:B,invoke:p});if(H.push(...oD(l,n,r)),a.ok){ok(a).forEach(e=>f.add(e));continue}if(ok(a).forEach(e=>f.add(e)),!T){return g=a,w=t,y=e,v=c,A=[...f],S=H,o_(g,w,y,v,A,tQ(S))}let i=await n7({action:t,sessionName:n,logPath:o,sessionStore:l});if(!i){return I=a,b=t,_=e,k=c,N=[...f],D=H,o_(I,b,_,k,N,tQ(D))}F[e]=i;let s=oN(l,n);if(a=await ov({req:U,sessionName:n,action:i,scope:G,filePath:c,line:q[e]??0,step:e+1,tracePath:B,invoke:p}),H.push(...oD(l,n,s)),!a.ok){return ok(a).forEach(e=>f.add(e)),x=a,R=i,M=e,P=c,L=[...f],O=H,o_(x,R,M,P,L,tQ(O))}ok(a).forEach(e=>f.add(e)),K+=1}T&&K>0&&tz(c,F,l.get(n));let j=tQ(H);return{ok:!0,data:{replayed:F.length,healed:K,session:n,artifactPaths:[...f],...j?{snapshotDiagnostics:j}:{}}}}catch(t){let e=i(t);return E(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function o_(e,t,r,a,n=[],i){if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${re(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:a,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:n,...i?{snapshotDiagnostics:i}:{}}}}}function ok(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&ox(e)))]:[]}if(!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,a="string"==typeof r.path?r.path:void 0;e?t.push(e):a&&t.push(a)}return[...new Set(t.filter(e=>ox(e)))]}function oN(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function oD(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function ox(e){try{return t.statSync(e).isFile()}catch{return!1}}function oR(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(oR):!!e&&"object"==typeof e&&Object.values(e).some(oR)}async function oM(e){let{req:t,sessionName:a,logPath:n,sessionStore:i,artifactsDir:o,tracePath:s}=e;if(t.flags?.recordVideo!==!0)return;let l=i.get(a);if(!l||l.recording)return;let u=o?r.join(o,"recording.mp4"):`./recording-${Date.now()}.mp4`;oL(s,{type:"video_recording_start",session:a,videoPath:u}),tv({phase:"replay_test_video_recording_start",data:{session:a,videoPath:u}});let p=await rl({req:{token:t.token,session:a,command:"record",positionals:["start",u],flags:{},meta:t.meta},sessionName:a,sessionStore:i,logPath:n});if(!p.ok)return oL(s,{type:"video_recording_start_failed",session:a,videoPath:u,errorCode:p.error.code}),p;let d=Date.now();return await rs(1e3),oL(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-d,requestedDurationMs:1e3}),tv({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-d,data:{session:a,requestedDurationMs:1e3}}),p}async function oP(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,tracePath:i,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!n.get(r)?.recording)return;oL(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rs(3e3);let l=Date.now(),u=await rl({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return ok(u).forEach(e=>o.add(e)),oL(i,{type:"video_recording_stop",session:r,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-s,errorCode:u.ok?void 0:u.error.code}),tv({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function oL(e,t){nq(e,{...t,ts:new Date().toISOString()})}async function oO(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}=e;return"replay"===t.command?await ob({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}):"test"===t.command?await nZ({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:o,target:s,requestId:l,artifactsDir:u,artifactPaths:p,tracePath:d,shard:c})=>{let f=function(e){let{platform:t,target:r,artifactsDir:a,shard:n}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===a&&void 0===n)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==a?{artifactsDir:a}:{}};if(!n)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:n.device.platform,target:n.device.target,shardAll:void 0,shardSplit:void 0,shardCount:n.shardCount,shardIndex:n.shardIndex};return"android"===n.device.platform?{...s,serial:n.device.id}:{...s,udid:n.device.id}}({parentFlags:t.flags,platform:o,target:s,artifactsDir:u,shard:c}),m={req:t,sessionName:r,logPath:a,sessionStore:n,artifactsDir:u,tracePath:d},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await oM(e)}}(m);return await ob({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:a,sessionStore:n,tracePath:d,invoke:async e=>{var t;let r=await oM(m);return r&&!r.ok?r:(t=await i(e),p&&ok(t).forEach(e=>p.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await oP({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await ee({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n})}}):null}async function oE(e){var t,r,a,n,i,o,s,l;let u,p,{req:d,sessionName:c,logPath:f,sessionStore:h}=e,g=d.positionals?.[0]??"";if("ios-runner"!==g)return E("INVALID_ARGS","prepare requires a subcommand: ios-runner");let w=h.get(c),y=d.flags??{},v=N(rp.prepare,w,y);if(v)return v;let A=await m({session:w,flags:y,ensureReady:!0});if(!ti(A.platform))return E("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let S=Date.now(),I=await et(A,(t=d,r=w,a=f,p=(n=t,"number"==typeof(u=n.flags?.timeoutMs)&&Number.isFinite(u)&&u>0?u:3e5),{verbose:t.flags?.verbose,logPath:a,traceLogPath:r?.trace?.outPath,cleanStaleBundles:!0,startupTimeoutMs:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return Math.max(45e3,Math.floor(e))}(t.flags?.timeoutMs),requestId:t.meta?.requestId,buildTimeoutMs:p,healthTimeoutMs:Math.min(p,9e4),iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir}));return{ok:!0,data:(i=g,o=A,s=Math.max(0,Date.now()-S),l=I,{action:i,platform:o.platform,deviceId:o.id,deviceName:o.name,kind:o.kind,durationMs:s,...l,message:`Prepared Apple runner: ${o.name}`})}}async function oC(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=n.get(r),d=t.flags??{},c=N(i,u,d);if(c)return c;let f=await m({session:u,flags:d,ensureReady:!0});if(!eV(i,f))return E("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let h=await p(f,i,o,t.flags?.out,{...ed(a,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,h,f):u;n.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:h??{}}),e!==u&&n.set(r,e)}return{ok:!0,data:h??{}}}async function o$(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=N(rp.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return E("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await m({session:i,flags:o,ensureReady:!0});if(!eV(rp.clipboard,u))return E("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,rp.clipboard,t.positionals??[],t.flags?.out,{...ed(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&n.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function oV(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i,invokeReplayAction:o,androidAdbExecutor:s}=e;if("inventory"===y(t.command))return await rY({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await r_({req:t,sessionName:r,sessionStore:n});if("state"===y(t.command))return await r3({req:t,sessionName:r,sessionStore:n});if(t.command===rp.clipboard)return await o$({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rp.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==ts((t.flags??{}).platform)?await oC({req:t,sessionName:r,logPath:a,sessionStore:n,command:rp.keyboard,positionals:t.positionals??[]}):E("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===y(t.command))return await aF({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:s});if(t.command===rp.prepare)return await oE({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rp.install||t.command===rp.reinstall)return await rJ({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===rp.install?rW:rz});if(t.command===ru.installSource)return await rg({req:t,sessionName:r,sessionStore:n});if(t.command===ru.releaseMaterializedPaths)return await rw({req:t});if(t.command===rp.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await oC({req:t,sessionName:r,logPath:a,sessionStore:n,command:rp.push,positionals:[i,"file"===(e=eS(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>ef.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):E("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===rp.triggerAppEvent?await oC({req:t,sessionName:r,logPath:a,sessionStore:n,command:rp.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await rC(e.device,r,e.appBundleId,rO)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===rp.open?await rj({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===y(t.command)?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o??i}):t.command===rp.batch?await rX(t,r,i):t.command===rp.close?await ee({req:t,sessionName:r,logPath:a,sessionStore:n}):null}export{rc as session_namespaceObject};
25
+ `;function iT(e){if("string"!=typeof e)throw new l("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new l("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,iU)}catch(t){throw new l("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function iU(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let iG={launchApp:({value:e,config:t,context:r})=>[iu(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return ri(i_,[iM(ru(e,t))],i$(e));if(ro(e)&&"string"==typeof e.point){rl(e,"tapOn",["point","repeat","delay","optional","label"]);let t=rp(e.point);return"percent"===t.kind?ri(iI,[String(t.x),String(t.y)],iO(e)):ri("click",[String(t.x),String(t.y)],iO(e))}ro(e)&&rl(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=i$(e);return ri(i_,[iR(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!ro(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new l("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=iR(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(ro(e)&&"string"==typeof e.point){rl(e,"doubleTapOn",["point","delay"]);let t=rt(e.point);return ri("click",[String(t.x),String(t.y)],iC(e))}return ro(e)&&rl(e,"doubleTapOn",["id","text","enabled","selected","delay"]),ri("click",[iR(e,"doubleTapOn",["delay"],t)],iC(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(ro(e)&&"string"==typeof e.point){rl(e,"longPressOn",["point"]);let t=rt(e.point);return ri("longpress",[String(t.x),String(t.y),"3000"])}return ro(e)&&rl(e,"longPressOn",["id","text","enabled","selected"]),ri("click",[iR(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[ri("type",[ru(function(e){if("string"==typeof e)return e;if(!ro(e))throw new l("INVALID_ARGS","inputText expects a string or map.");if(rl(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new l("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[ik(e)],pasteText:({value:e,context:t,name:r})=>[ri("type",[ru(rd(r,e),t)])],openLink:({value:e,config:t,context:r,name:a})=>{var n,i,o,s,l,u;let d;return[(n=e,i=t,o=r,s=a,d=ru((l=n,u=s,"string"==typeof l?l:ro(l)?(rl(l,u,["link"]),rd(`${u}.link`,l.link)):rd(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?ri("open",[ru(rs(i,s),o),d],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):ri("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[ri(ig,[iR(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[ri(iw,[iR(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!ro(e))throw new l("INVALID_ARGS","extendedWaitUntil expects a map.");rl(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw rc("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=iR(r,"extendedWaitUntil",[],t),n=String(rf(e,17e3));return void 0!==e.notVisible?[ri(iw,[a,n])]:[ri(ig,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[ri("screenshot",[ru(rd(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw rc("Maestro scroll options are not supported yet.");return ri("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[ri(iA,[iM(ru(e,t)),"5000","down"])];if(!ro(e))throw new l("INVALID_ARGS","scrollUntilVisible expects a string or map.");rl(e,"scrollUntilVisible",["element","direction","timeout"]);let r=iR(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?iD(e.direction,"scrollUntilVisible.direction"):"down";return[ri(iA,[r,String(rf(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!ro(e))throw new l("INVALID_ARGS","swipe expects a map.");rl(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,a=o,n=t,i=ix("string"==typeof r.direction?r.direction:"up"),ri(iS,[iR(a,"swipe.from",[],n),i,...iP(r)])):"string"==typeof e.direction?ri(ib,["direction",ix(e.direction),...iP(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:rp(e.start),end:rp(e.end)};throw rc("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=iN(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return ri("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return ri(ib,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw rc("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[ri("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=rd("pressKey",e).toLowerCase();if("back"===t)return ri("back");if("enter"===t||"return"===t)return ri(iv);if("home"===t)return ri("home");throw rc(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[ri("back")],waitForAnimationToEnd:({value:e})=>[ri(iy,[String(rf(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[id(e,t,r)],runScript:({value:e,context:t})=>{let a;return[ri(ih,[function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new l("INVALID_ARGS","runScript file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}((a=function(e,t){if("string"==typeof e)return{file:ru(e,t),env:{}};if(!ro(e))throw new l("INVALID_ARGS","runScript expects a file path string or map.");return rl(e,"runScript",["file","env"]),{file:ru(rd("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(t5(e.env,"runScript.env")).map(([e,r])=>[e,ru(r,t)]))}}(e,t)).file,t)],{...Object.keys(a.env).length>0?{maestro:{runScriptEnv:a.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){if("string"==typeof e)return a.parseRunFlowFile(ru(e,r),r).actions;if(!ro(e))throw new l("INVALID_ARGS","runFlow expects a file path string or map.");rl(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!ro(e))throw new l("INVALID_ARGS","runFlow.when expects a map.");return(rl(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new l("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new iE(function(e){let t=[],r=0;for(;r<e.length;){var a,n;let i=e.slice(r),o=(a=i,/^\s+/.exec(a)?.[0].length??0);if(o>0){r+=o;continue}let s=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(n=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(n)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(n)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(n)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(n);if(s){t.push(s.token),r+=s.length;continue}throw new l("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=ru(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new l("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new l("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new l("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,a=t,{...void 0!==r.visible?{visibleSelector:iR(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:iR(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...t5(e.env,"runFlow.env"),...r.envOverrides}};return function(e,t){let{visibleSelector:r,notVisibleSelector:a}=t;if(!r&&!a)return e;if(r&&a)throw rc("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[iV("runFlow.when",[n,i],{kind:"maestroRunFlowWhen",mode:n,selector:i,actions:e})]}(function(e,t,r,a,n){if("string"==typeof e.file)return a.parseRunFlowFile(ru(e.file,r),r).actions;if(Array.isArray(e.commands))return n(t6(e.commands),t,r,a);throw new l("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,a,n),i)})(e,t,r,a,iB),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!ro(e))throw new l("INVALID_ARGS","repeat expects a map.");if(rl(e,"repeat",["times","commands","while"]),void 0!==e.while)throw rc("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,iF(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new l("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new l("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let s=t6(e.commands);return Array.from({length:o}).flatMap(()=>n(s,t,r,a))})(e,t,r,a,iB),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!ro(e))throw new l("INVALID_ARGS","retry expects a map.");if(rl(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new l("INVALID_ARGS","retry requires a commands list.");let s=(i=e.maxRetries,o=r,void 0===i?1:iF(i,o,"retry.maxRetries")),u=n(t6(e.commands),t,r,a);return[iV("retry",[String(s)],{kind:"retry",maxRetries:s,actions:u})]})(e,t,r,a,iB)},iH={launchApp:(e,t)=>[iu(void 0,e,t)],scroll:()=>[ri("scroll",["down"])],hideKeyboard:()=>[ri("keyboard",["dismiss"])],eraseText:()=>[ik(void 0)],back:()=>[ri("back")],waitForAnimationToEnd:()=>[ri(iy,["15000"])],stopApp:(e,t)=>[id(void 0,e,t)]};function iK(e,t,r,a,n){try{return function(e,t,r,a){if("string"==typeof e){var n,i,o;let a;return n=e,i=t,o=r,(a=iH[n])?a(i,o):t2(n)}let s=Object.entries(e);if(1!==s.length)throw new l("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[u,d]=s[0],p=iG[u];return p?p({value:d,config:t,context:r,deps:a,name:u}):t2(u)}(e,t,a,n)}catch(e){if(e instanceof l&&!/\bline \d+\b/.test(e.message))throw new l(e.code,`${e.message} (line ${r})`,e.details);throw e}}function iB(e,t,r,a){return e.flatMap((e,n)=>iK(e,t,n+1,r,a))}function ij(e,t){let{config:r,commands:a}=iz(re(e)),n={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:a,context:n}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...a,...Array.from({length:t.onFlowComplete?.length??0},()=>a.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let a=o[e]??e+1,i=iK(r,t,a,n,{parseRunFlowFile:iW});s.push(...i),i.forEach(()=>l.push(a))}return function(e,t){let r=[],a=[];for(let n=0;n<e.length;n+=1){let i=e[n],o=function(e,t,r){var a;let n=function(e,t,r){let a=e[r],n=e[r+1],i=e[r+2];if(i?.command!==iv||a.flags?.maestro?.optional===!0)return null;let o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(n),s=function(e){if(e?.command!==i_)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);return n&&null!==o&&null!==s?{action:a,nextAction:n,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!n)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:d}=n;return(a=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(a.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[d,d,t[r+2]??d],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[d],consumed:1}}(e,t,n);if(o){r.push(...o.actions),a.push(...o.actionLines),n+=o.consumed-1;continue}r.push(i),a.push(t[n]??1)}return{actions:r,actionLines:a}}(s,l)}({config:r,commands:a,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),a=-1===r?0:r+1,n=[];for(let e=a;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&n.push(e+1);return n}(e),context:n});return{actions:i,actionLines:o,metadata:{env:r.env}}}function iz(e){if(0===e.length)throw new l("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:t6(e[0])};let t=function(e){if(!ro(e))throw new l("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.name&&e.name.length>0?{name:e.name}:{},..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...ro(e.env)?{env:t5(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:t6(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:t6(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new l("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:t6(r)}}function iW(e,a){let n=function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new l("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}(e,a);if(a.visitedPaths.has(n))throw new l("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(a.visitedPaths);return o.add(n),ij(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let iJ=/[*?[\]{}]/;function iY(e,t,a,n,i=0){let o=r.basename(a,r.extname(a)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${o?`-${o}`:""}:attempt-${i+1}`}function iX(e,t){return"number"==typeof e?e:t}function iQ(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function iZ(e,a,n){var i,o;let s=ek.expandHome(e,a);if(t.existsSync(s)){let a=t.statSync(s);if(a.isDirectory())return{paths:[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:s}).map(e=>r.join(s,e))),source:"directory"};if(a.isFile()){if(!n.has(r.extname(s)))throw new l("INVALID_ARGS",`test does not support this file type: ${e}`);return{paths:[s],source:"file"}}return{paths:[],source:"file"}}if(i=e,!iJ.test(i)&&(o=s,!iJ.test(o)))throw new l("INVALID_ARGS",`test input not found: ${e}`);let u=r.isAbsolute(s)?s:e;return{paths:t.globSync(u,{cwd:r.isAbsolute(s)?void 0:a}).map(e=>r.isAbsolute(e)?e:r.resolve(a,e)).filter(e=>n.has(r.extname(e))&&function(e){try{return t.statSync(e).isFile()}catch{return!1}}(e)),source:"glob"}}function i0(e,t){let r=i1(e),a=i1(t);return r!==a?r-a:e.localeCompare(t)}function i1(e){return+(".ad"===r.extname(e))}function i3(e){return[...new Set(e.map(e=>r.normalize(e)))]}function i2(e){return"maestro"===e}let i5=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function i4(e){var t,r,a,n;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&tC(i)||(a=s.code,n=s.message,o=`${a}
26
+ ${n}`.toLowerCase(),i5.some(e=>o.includes(e))))}async function i8(e){let a,n,{filePath:i,sessionName:o,requestId:l,parentRequestId:u,timeoutMs:d,platform:p,target:c,artifactsDir:f,shard:m,progress:h,runReplay:g,cleanupSession:w,finalizeAttempt:v}=e;q(l);let y=function(e,t){if(!t||t===e)return()=>{};let r=e3(t);if(!r)return()=>{};let a=()=>{eG(e)};return r.aborted?(a(),()=>{}):(r.addEventListener("abort",a,{once:!0}),()=>{r.removeEventListener("abort",a)})}(l,u),A=new Set,b=!1,S=Date.now(),_=function(e){let{artifactsDir:a,artifactPaths:n,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:u,target:d}=e;if(!a)return;let p=r.join(a,"replay-timing.ndjson");return t.mkdirSync(r.dirname(p),{recursive:!0}),t.writeFileSync(p,""),n.add(p),oe(p,{type:"replay_test_attempt_start",ts:new Date().toISOString(),replayPath:i,session:o,requestId:s,timeoutMs:l,platform:u,target:d}),p}({artifactsDir:f,artifactPaths:A,filePath:i,sessionName:o,requestId:l,timeoutMs:d,platform:p,target:c}),I=eT(h,async()=>await g({filePath:i,sessionName:o,platform:p,target:c,requestId:l,artifactsDir:f,artifactPaths:A,tracePath:_,shard:m})).catch(e=>({ok:!1,error:s(e)})).finally(()=>{y(),eJ(l)});try{n="number"==typeof d?await Promise.race([I,new Promise(e=>{a=setTimeout(()=>{b=!0,eG(l),e(function(e,t=[]){return{ok:!1,error:{code:"COMMAND_FAILED",message:`TIMEOUT after ${e}ms`,hint:"Replay test timeouts are cooperative; the active command may take a short grace period to stop.",details:{reason:"timeout",timeoutMs:e,timeoutMode:"cooperative",artifactPaths:t}}}}(d,[...A]))},d)})]):await I,oe(_,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:o,ok:n.ok,timedOut:b,durationMs:Date.now()-S,errorCode:n.ok?void 0:n.error.code})}finally{var k,N,D;let e,t;a&&clearTimeout(a),b&&(await i6(I)||((k=n)&&!k.ok&&(k.error.details={...k.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),tJ({level:"warn",phase:"test_timeout_cleanup_race",data:{session:o,requestId:l,graceMs:2e3}}),i7({replayPromise:I,cleanupSession:w,sessionName:o,requestId:l})));let r=await i9({finalizeAttempt:v,sessionName:o,artifactPaths:A,artifactsDir:f,tracePath:_});n?.ok&&r&&!r.ok&&(N=n,D=`Replay test finalization failed: ${r.error.message}`,t=Array.isArray((e=N.data??={}).warnings)?e.warnings.filter(e=>"string"==typeof e):[],e.warnings=[...t,D]);let i=Date.now();try{oe(_,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:o}),await w(o),oe(_,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!0,durationMs:Date.now()-i})}catch(t){let e=s(t);oe(_,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),tJ({level:"warn",phase:"test_cleanup_failed",data:{session:o,error:e.message}})}}return n??{ok:!1,error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"}}}async function i6(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function i7(e){let{replayPromise:t,cleanupSession:r,sessionName:a,requestId:n}=e;try{await t}finally{try{await r(a)}catch(e){tJ({level:"warn",phase:"test_late_cleanup_failed",data:{session:a,requestId:n,error:s(e).message}})}}}async function i9(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let o=Date.now();oe(i,{type:"replay_test_finalize_start",ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i});return oe(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-o,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let e=s(t);return oe(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-o,errorCode:e.code}),tJ({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function oe(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
27
+ `)}async function ot(e){var t,a,n;let i,o=function(e){var t;let a,{entry:n,cwd:i,retries:o,suiteArtifactsDir:s,shard:l}=e;return{testStartedAt:Date.now(),testArtifactsDir:r.join(s,...l?[`shard-${l.shardIndex+1}`]:[],(t=n.path,(0===(a=i?r.relative(i,t):r.basename(t)).length||a.startsWith("..")?r.basename(t):a).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),maxAttempts:o+1}}(e),s=await or(e,o);return t=e,a=o,n=s,i=Date.now()-a.testStartedAt,n.finalResponse?.ok?function(e,t,r,a){var n;let{entry:i,suiteIndex:o,suiteTotal:s,shard:l}=e,u=r.finalResponse;if(!u?.ok)throw Error("Expected passing replay test response.");return e4({type:"replay-test",file:i.path,title:i.title,status:"pass",index:o,total:s,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,...oi(l)}),{file:i.path,title:i.title,session:r.finalSessionName,status:"passed",durationMs:a,finalAttemptDurationMs:r.finalAttemptDurationMs,attempts:r.attempts,artifactsDir:t.testArtifactsDir,...(n=u,{replayed:"number"==typeof n.data?.replayed?n.data.replayed:0,healed:"number"==typeof n.data?.healed?n.data.healed:0}),...function(e){if(!Array.isArray(e))return{};let t=e.filter(e=>"string"==typeof e);return t.length>0?{warnings:t}:{}}(u.data?.warnings),...on(u.data?.snapshotDiagnostics),...function(e){return oi(e)}(l),...r.attemptFailures.length>0?{attemptFailures:r.attemptFailures}:{}}}(t,a,n,i):function(e,t,r,a){var n,i;let{entry:o,suiteIndex:s,suiteTotal:l,shard:u}=e,d=(n=r.finalResponse)&&!n.ok?n.error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return e4({type:"replay-test",file:o.path,title:o.title,status:"fail",index:s,total:l,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,message:d.message,hint:d.hint,...oi(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:d,...on((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return oi(e)}(u)}}(t,a,n,i)}async function or(e,t){!function(e,t){let{entry:r,sessionName:a,suiteInvocationId:n,caseIndex:i,suiteIndex:o,suiteTotal:s,shard:l}=e;e4({type:"replay-test",file:r.path,title:r.title,status:"start",index:o,total:s,maxAttempts:t.maxAttempts,session:iY(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...oi(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let p=0;p<=e.retries&&!eR(e.requestId);p+=1){var a,n,i,o,s,l,u,d;let c=await oa(e,t,p);if((a=r).finalResponse=(n=c).response,a.finalSessionName=n.sessionName,a.attempts=n.attempt,a.finalAttemptDurationMs=n.durationMs,n.response.ok||a.attemptFailures.push({attempt:n.attempt,message:n.response.error.message,durationMs:n.durationMs}),i=e,o=c.response,s=p,o.ok||eR(i.requestId)||i4(o)||s>=i.retries)break;l=e,u=t,(d=c).response.ok||e4({type:"replay-test",file:l.entry.path,title:l.entry.title,status:"fail",index:l.suiteIndex,total:l.suiteTotal,attempt:d.attempt,maxAttempts:u.maxAttempts,durationMs:d.durationMs,retrying:!0,message:d.response.error.message,hint:d.response.error.hint,session:d.sessionName,artifactsDir:u.testArtifactsDir,...oi(l.shard)})}return r}async function oa(e,a,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,suiteIndex:d,suiteTotal:p,requestId:c,timeoutMs:f,shard:m}=e,h=n+1,g=Date.now(),w=iY(s,l,o.path,u,n),v=r.join(a.testArtifactsDir,`attempt-${h}`);i=o.path,t.mkdirSync(v,{recursive:!0}),function(e,a){var n;let i,o=r.join(a,"replay.ad");if(t.copyFileSync(e,o),n=e,".yml"!==(i=r.extname(n).toLowerCase())&&".yaml"!==i)return;let s=r.join(a,r.basename(e));r.resolve(s)!==r.resolve(o)&&t.copyFileSync(e,s)}(i,v);let y=function(e){let{requestId:t,suiteInvocationId:a,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return eM(`${t??a}${l}:test:${i+1}:${r.basename(n)}:attempt:${o+1}`,a)}({requestId:c,suiteInvocationId:l,filePath:o.path,caseIndex:u,attemptIndex:n,shardIndex:m?.shardIndex}),A=await i8({filePath:o.path,sessionName:w,requestId:y,parentRequestId:c,timeoutMs:f,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:v,shard:m,progress:{file:o.path,title:o.title,index:d,total:p,attempt:h,maxAttempts:a.maxAttempts,session:w,artifactsDir:a.testArtifactsDir,...oi(m)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),b=Date.now()-g;return!function(e){var a;let n,{response:i,filePath:o,sessionName:s,attempts:l,maxAttempts:u,attemptArtifactsDir:d}=e,p=[...Array.isArray(n=(a=i).ok?a.data?.artifactPaths:a.error.details?.artifactPaths)?[...new Set(n.filter(e=>"string"==typeof e))]:[]];i.ok||"string"!=typeof i.error.logPath||p.push(i.error.logPath);let c=function(e,a){let n=[],i=new Map;for(let o of e){if(!function(e){try{return t.statSync(e).isFile()}catch{return!1}}(o))continue;let e=function(e,t){let a=r.extname(e),n=a?e.slice(0,-a.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${a}`}(r.basename(o),i),s=r.join(a,e);r.resolve(o)!==r.resolve(s)&&t.copyFileSync(o,s),n.push(s)}return n}(p,d),f=[`file: ${o}`,`session: ${s}`,`attempt: ${l}/${u}`,`status: ${i.ok?"passed":"failed"}`];if(i.ok){let e="number"==typeof i.data?.replayed?i.data.replayed:0,t="number"==typeof i.data?.healed?i.data.healed:0;f.push(`replayed: ${e}`,`healed: ${t}`)}else f.push(`code: ${i.error.code}`,`message: ${i.error.message}`),i.error.hint&&f.push(`hint: ${i.error.hint}`),i.error.diagnosticId&&f.push(`diagnosticId: ${i.error.diagnosticId}`),i.error.logPath&&f.push(`logPath: ${i.error.logPath}`),i.error.details?.reason==="timeout"&&f.push("timeoutMode: cooperative");c.length>0&&f.push(`copiedArtifacts: ${c.map(e=>r.basename(e)).join(", ")}`);let m=r.join(d,"result.txt"),h=`${f.join("\n")}
28
+ `;t.writeFileSync(m,h),i.ok||t.writeFileSync(r.join(d,"failure.txt"),h)}({response:A,filePath:o.path,sessionName:w,attempts:h,maxAttempts:a.maxAttempts,attemptArtifactsDir:v}),{response:A,sessionName:w,attempt:h,durationMs:b}}function on(e){let t=rA(e);return t?{snapshotDiagnostics:t}:{}}function oi(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function oo(e,t,r){let a=function(e){let t=os(e?.shardAll,"--shard-all"),r=os(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new l("INVALID_ARGS","--shard-all and --shard-split are mutually exclusive");return void 0!==t?{kind:"all",count:t}:void 0!==r?{kind:"split",count:r}:void 0}(e);if(!a||0===t.length)return;let n=await ol(e,a.count);return{mode:a.kind,shardCount:a.count,total:r+("all"===a.kind?t.length*a.count:t.length),shards:n.map((e,r)=>({shardIndex:r,shardCount:a.count,device:e,entries:"all"===a.kind?t:t.filter((e,t)=>t%a.count===r)}))}}function os(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new l("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function ol(e,t){var r,a,n,i,o,s,u,d,p;let c,f,m=(r=e,"string"!=typeof(c=r?.device)||0===c.trim().length?[]:c.split(",").map(e=>e.trim()).filter(Boolean)),h=(n=await eI((a=e,f=tF(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:tH({simulatorSetPath:tL(a?.iosSimulatorDeviceSet),platform:a?.platform,target:a?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(s=n,u=i,d=o,u.map(e=>{let t=od(e),r=s.find(r=>ou(r,d)&&(r.id===e||od(r.name)===t));if(!r)throw new l("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!ou(t=e,o)&&!!tj(t.platform)&&!1!==t.booted}).sort(op));if(h.length<t){throw new l("DEVICE_NOT_FOUND",`test sharding requires ${(p=t,`${p} device${1===p?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function ou(e,t){return!(!tz(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function od(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function op(e,t){return e.id.localeCompare(t.id)}async function oc(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:i}=e;if((t.positionals?.length??0)===0)return T("INVALID_ARGS","test requires at least one path or glob");try{var s,l,u,d;let e,o,p,c,f,m,h=Date.now(),g=await of(t);s=g,e4({type:"replay-test-suite",status:"start",total:s.total,runnable:s.runnable.length,skipped:s.entries.length-s.runnable.length,artifactsDir:s.suiteArtifactsDir,shardMode:s.shardPlan?.mode,shardCount:s.shardPlan?.shardCount});let w=g.shardPlan?function(e){let{entries:t,total:r}=e,a=[];for(let[e,n]of t.entries())"skip"===n.kind&&(e4({type:"replay-test",file:n.path,status:"skip",index:e+1,total:r,message:n.message}),a.push({file:n.path,status:"skipped",durationMs:0,reason:n.reason,message:n.message}));return a}({entries:g.entries,total:g.total}):[];g.shardPlan?w.push(...await om({shards:g.shardPlan.shards,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:i})):w.push(...await ow({discoveryEntries:g.entries,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:i}));let v=(l=g.total,u=w,d=Date.now()-h,e=u.filter(e=>"passed"===e.status).length,p=(o=u.filter(e=>"failed"===e.status)).length,c=u.filter(e=>"skipped"===e.status).length,f=e+p,m=rS(u.map(e=>"skipped"===e.status?void 0:e.snapshotDiagnostics)),{total:l,executed:f,passed:e,failed:p,skipped:c,notRun:Math.max(0,l-f-c),durationMs:d,failures:o,tests:u,...m?{snapshotDiagnostics:m}:{}});return{ok:!0,data:v}}catch(t){let e=o(t);return T(e.code,e.message)}}async function of(e){var a,n,i,o;let s=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,s=new Set(i2(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!i2(i))return[...new Set(e.flatMap(e=>iZ(e,a,n).paths))].map(e=>r.normalize(e)).sort((e,t)=>e.localeCompare(t));let o=[],s=[];for(let i of e){let e=function(e,a,n){let i=ek.expandHome(e,a);return t.existsSync(i)&&t.statSync(i).isDirectory()?{paths:function e(a,n){let i=[],o=t.opendirSync(a);try{let t;for(;null!==(t=o.readSync());){let o=r.join(a,t.name);t.isDirectory()?i.push(...e(o,n)):t.isFile()&&n.has(r.extname(t.name))&&i.push(o)}}finally{o.closeSync()}return i}(i,n),source:"directory"}:iZ(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?i3(e.paths):e.paths.map(e=>r.normalize(e)).sort(i0))}return i3([...o,...s.flat()])}(a,n??process.cwd(),s,o),d=[];for(let e of u){var p,c,f,m;let a=t.readFileSync(e,"utf8"),n=rr(a),s=(p=a,c=e,i2(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=iz(re(e));return t.name}(p):void 0);if(!i){d.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){i2(o)?d.push({kind:"run",path:e,title:s,metadata:n}):d.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${i}`});continue}f=i,m=n.platform,("apple"===f?tG(m):m===f)&&d.push({kind:"run",path:e,title:s,metadata:n})}if(0===d.filter(e=>"run"===e.kind).length){let e=i?` for --platform ${i}`:"";throw new l("INVALID_ARGS",`No replay tests matched${e}.`)}return d}({inputs:(n=e).positionals??[],cwd:n.meta?.cwd,platformFilter:n.flags?.platform,replayBackend:n.flags?.replayBackend}),u=s.flatMap((e,t)=>"run"===e.kind?[{entry:e,suiteIndex:t+1}]:[]),d=s.length-u.length,p=(a=e.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),c=await oo(e.flags,u,d);return{entries:s,runnable:u,shardPlan:c,suiteInvocationId:p,suiteArtifactsDir:(i=e,o=p,function(e){let{artifactsDir:t,cwd:a,suiteInvocationId:n}=e,i=ek.expandHome(t??".agent-device/test-artifacts",a);return r.join(i,n)}({artifactsDir:"string"==typeof i.flags?.artifactsDir?i.flags.artifactsDir:void 0,cwd:i.meta?.cwd,suiteInvocationId:o})),total:c?.total??s.length}}async function om(e){return(await Promise.allSettled(e.shards.map(async t=>await oh({...e,shard:t})))).flatMap((t,r)=>{var a,n;let i;if("fulfilled"===t.status)return t.value;let o=e.shards[r];return o?[(a=o,n=e.sessionName,i=s(t.reason),{file:a.entries[0]?.entry.path??`shard-${a.shardIndex+1}`,session:og(n,a),status:"failed",durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:a.shardIndex,shardCount:a.shardCount,deviceId:a.device.id,deviceName:a.device.name})]:[]})}async function oh(e){let{shard:t,sessionName:r}=e;return await ov({...e,entries:t.entries,sessionName:og(r,t),shard:t})}function og(e,t){return`${e}:shard-${t.shardIndex+1}`}async function ow(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p}=e,c=[],f=0;for(let[e,m]of t.entries()){if(eR(i))break;if("skip"===m.kind){e4({type:"replay-test",file:m.path,status:"skip",index:e+1,total:l,message:m.message}),c.push({file:m.path,status:"skipped",durationMs:0,reason:m.reason,message:m.message});continue}f+=1;let t=await ot({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:iQ(o?.retries,m.metadata.retries),timeoutMs:iX(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p});if(c.push(t),oy(t,o,i))break}return c}async function ov(e){let{entries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c}=e,f=[];for(let[e,m]of t.entries()){if(eR(i))break;let{entry:t,suiteIndex:h}=m,g=await ot({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:iQ(o?.retries,t.metadata.retries),timeoutMs:iX(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c});if(f.push(g),oy(g,o,i))break}return f}function oy(e,t,r){return eR(r)||t?.failFast===!0||i4(e)}let oA={maestro:{parse:function(e,t={}){var a;let n;return ij(e,(n=(a=t).visitedPaths??new Set,a.sourcePath&&n.add(r.resolve(a.sourcePath)),{baseDir:a.sourcePath?r.dirname(a.sourcePath):void 0,platform:t7(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function ob(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,a=rC(null!==r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r}}async function oS(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(r$(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=n.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),r$(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&o_(r)?t.slice(0,-1):t}(e),a=r[0]??"";a&&!a.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=rD(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=ob(e.positionals??[]);r&&t.push(r)}return Q(t).filter(e=>e.trim().length>0)})(t).map(e=>rV(e)).filter(e=>null!==e);if(0===o.length)return null;let s=r$(t.command)||"fill"===t.command,l=r$(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await oI(i,t,a,s,n);for(let e of o){let r=r_(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=rx(r.node,i.device.platform,{action:"fill"===t.command?"fill":r$(t.command)?"click":"get"}).join(" || ");if(r$(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&o_(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=_(t);if(!e)continue;return{...t,positionals:[a,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,a]}}if("is"===t.command){let{predicate:e,split:r}=rD(t.positionals);if(!e)continue;let n=r?.rest.join(" ").trim()??"",i=[e,a];return"text"===e&&n.length>0&&i.push(n),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=ob(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function o_(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function oI(e,t,r,a,n){let i=ey(await f(e.device,"snapshot",[],t.flags?.out,{...e_(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return Z(e,i),n.set(e.name,e),i}let ok=.35,oN=120,oD=360,ox=8;function oR(e,t){return Math.round(Math.min(oD,Math.max(oN,"number"==typeof e?e*ok:0,1.5*t)))}let oM=new WeakMap,oP=new WeakMap,oL=new WeakMap;function oO(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function o$(e){var t;let r,a=!0===e.raw||"1"===process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...a?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&(t=e.scope,(r=ed(oC(n.data)))&&oM.set(t,r)),n}function oC(e){return Array.isArray(e?.nodes)?e:void 0}function oE(e,t){e&&oP.set(e,{selector:t})}function oV(e){e&&oL.delete(e)}let oF=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function oq(e,t,r,a,n,i={}){let o=oK(e,t,a);if(r.childOf){let t=oK(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=rR(e.nodes);o=o.filter(r=>t.some(t=>rN(e.nodes,r,t,n)))}let s=oU({nodes:e.nodes,matches:o,platform:a}),l=oz(e.nodes,s.matches,r.index,oH(t),n,!0===i.requireOnScreen,i.promoteTapTarget,i.preferredContext);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&0===s.matches.length?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}function oT(e,t,r,a){let n=oK(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=oU({nodes:e.nodes,matches:n,platform:r}),o=oz(e.nodes,i.matches,void 0,oH(t),a,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:i.matches.length}:{ok:!1,message:i.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:n.length>0?`Maestro selector matched ${n.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function oU(e){let t=e.matches.filter(t=>rO({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tk(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tI(a),i=n.filter(t=>rO({predicate:"visible",node:t,nodes:e,platform:r}).pass);if(0===i.length)return 0===n.length?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(i.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&0===s.length}}(e.nodes,t,e.platform);return{matches:r.matches,blockedByReactNativeOverlay:r.blockedByReactNativeOverlay}}function oG(e){return e?.platform==="android"?"android":"ios"}function oH(e){let t=rF(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),a=r[0];return a&&r.every(e=>e===a)?a:null}function oK(e,t,r,a={}){for(let n of rF(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!rM(e,t,r)||t.terms.every(t=>(function(e,t,r,a){var n,i,o;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?rM(e,{raw:t.key,terms:[t]},r):oB((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:rI(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function oB(e,t,r={}){var a;let n=e??"",i=rE(n),o=rE(t);if(i===o||!1!==r.allowLeadingCompositeLabelMatch&&function(e,t){if(!e||!t||!e.startsWith(t))return!1;let r=e.at(t.length);return","===r||":"===r||";"===r}(i,o))return!0;if(a=t,!/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(a))return!1;try{return new RegExp(t).test(n)}catch{return!1}}function oj(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let a=function(e,t,r){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);)if(a.rect)return a.rect.width>0&&a.rect.height>0?a.rect:null;return null}(e,t,r);return a?{rect:a,inherited:!0}:null}function oz(e,t,r,a,n,i=!1,o=!1,s){var l,u,d,p,c,f,m,h,g,w,v,y,A,b,S,_,I,k,N;let D,x,R,M,P=rR(e),L=(l=e,u=t,d=P,p=a,c=r,f=n,m=i,R=(x=(D=u.map(e=>{var t;let r;return(r=oj(l,t=e,d))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?x:D,p&&void 0===c?(h=R,g=f,w=m,M=h.filter(e=>{var t,r;let a,n;return t=e.rect,r=g,a=r?.referenceWidth??1/0,n=r?.referenceHeight??1/0,t.x<a&&t.y<n&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:h):D),O=function(e,t,r,a,n,i){var o,s,l,u,d,p,c;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=a,u=n,d=i,u&&l?function(e,t,r,a){let n=t.filter(e=>0===o2(e.node,r));if(n.length>=2){let t=oJ(e,n,r,a);if(t)return t}let i=t.filter(e=>1===o2(e.node,r));return n.length>0||i.length<2?null:oJ(e,i,r,a)}(o,s,l,d)??oW(o,s,l,d):oW(o,s,l,d));return(p=f,c=a,n&&c&&p)?function(e,t,r){var a,n,i,o,s,l,u,d,p,c,f,m,h,g,w,v,y,A;let b,S,_,I,k,N,D,x;if(a=t,n=r,!(("cell"===(b=rP(a.node.type??""))||"other"===b||"scrollview"===b||"scroll-area"===b)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=o2(a.node,n)))return null;let R=(i=e,o=t,s=r,l=rR(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&rN(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=rP(t.type??""))&&"cell"!==n&&"other"!==n||1>=o2(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!o1(r,t.rect)&&oZ(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(_=Math.floor((S=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),S[_]??0),P=function(e,t){let r=[],a=e.x,n=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(n,i.x+i.width);t>a&&r.push({x:a,width:t-a}),a=Math.max(a,o)}return n>a&&r.push({x:a,width:n-a}),r}(t.rect,R.map(e=>e.rect)),L=(u=t,d=r,p=P,c=M,N=p.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),D=(f=u,m=d,I=p.find(e=>1>Math.abs(e.x-f.rect.x)),k=Math.max(48,Math.min(220,8*m.length+24)),(h=f,g=m,w=I,v=k,w&&"scrollview"===rP(h.node.type??"")&&1>=o2(h.node,g)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&w.width<=.55*h.rect.width&&w.width>=.6*v)?{x:f.rect.x,width:Math.min(k,I.width)}:null),x=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!x?D:1===N.length?N[0]??null:D);return L?(y=t,A=L,{...y,rect:{x:A.x,y:y.rect.y,width:A.width,height:y.rect.height}}):null}(e,f,a)??f:f}(e,L,r,a,o,s);return v=e,y=O,A=P,b=o,S=n,y?b?(_=v,I=y,k=A,N=S,(o0(I.node)?null:rk(_,I.node,k,e=>{if(!o0(e))return null;let t=oj(_,e,k);return t&&function(e,t,r){var a,n;if(!o1(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>oZ(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=oX(t),o=oX(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(I.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:y.node,rect:y.rect}):{node:y.node,rect:y.rect}:null}function oW(e,t,r,a){return(function(e,t,r,a){var n;let i,o,s;if(!r||t.length<2)return t;let l=t.filter(e=>0===o2(e.node,r));if(l.length<2)return t;let u=rR(e),d=l.map(t=>({candidate:t,container:oY(e,t.node,u)})).filter(e=>!!e.container);if(d.length<2||d.length!==l.length)return t;let p=d.filter(e=>{var t;return t=e,d.some(e=>e!==t&&t.container.index!==e.container.index&&o3(t.container.rect,e.container.rect)>=.6)});if(p.length<2)return t;let c=(o=Math.max(...i=(n=p).map(e=>oX(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>oX(e.container.rect)===o).map(e=>e.candidate));if(c.length>0)return c;let f=function(e,t,r,a){if(!r)return[];let n=oY(e,r.node,a),i=n&&o1(n.rect,r.rect)?n:null,o=t.map(e=>({entry:e,score:function(e,t,r){if(r)return e.index===r.index?0:.6>o3(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(o3(e.rect,t.rect)>=.6)return 0;let a=e.index-t.node.index;return a>=0?a:1e5+Math.abs(a)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,p,a,u);if(f.length>0)return f;let m=Math.max(...p.map(e=>e.container.index)),h=p.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,a).sort((e,t)=>(function(e,t,r){var a,n;let i=function(e,t,r){if(r){let a=o2(e.node,r)-o2(t.node,r);if(0!==a)return a}let a=oQ(e.node)-oQ(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&oQ(e.node)===oQ(t.node)?oX(t.rect)-oX(e.rect):oX(e.rect)-oX(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(a=e.rect,n=t.rect,Math.round(a.x)!==Math.round(n.x)||Math.round(a.y)!==Math.round(n.y)||Math.round(a.width)!==Math.round(n.width)||Math.round(a.height)!==Math.round(n.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function oJ(e,t,r,a){let n=rR(e),i=t.filter(r=>{var a;return(a=r).rect.width>=16&&a.rect.width<=260&&a.rect.height>=24&&a.rect.height<=80&&t.some(t=>{var a,i,o,s;return a=e,i=t,o=r,s=n,!(i.node.index===o.node.index||!o1(i.rect,o.rect)||oX(i.rect)<2*oX(o.rect))&&rN(a,o.node,i.node,s)})});return oW(e,i,r,a)}function oY(e,t,r){return rk(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=rP(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function oX(e){return e.width*e.height}function oQ(e){return oF.get(rP(e.type??""))??3}function oZ(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}function o0(e){let t=rP(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function o1(e,t){return t.x>=e.x-1&&t.y>=e.y-1&&t.x+t.width<=e.x+e.width+1&&t.y+t.height<=e.y+e.height+1}function o3(e,t){let r=Math.max(e.x,t.x),a=Math.min(e.x+e.width,t.x+t.width),n=Math.max(e.y,t.y);return Math.max(0,a-r)*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-n)/Math.max(1,Math.min(oX(e),oX(t)))}function o2(e,t){let r=[e.label,rI(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rE(e)===rE(t))?1:r.some(e=>oB(e,t))?2:3}async function o5(e){let t=ss(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=so(e.baseReq,t.selector);return r?await o4(e,t,r):await o6(e,t)}async function o4(e,t,r){let a=Date.now(),n=await o8(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await sl(e,t.selector,"assertVisible");if(!r.visible){let n=si(e.baseReq,t,r,a);return"return"===n.kind?n.response:await o6(e,t)}}return oE(e.scope,t.selector),sp({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await o7(e,t,n,a)}async function o8(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function o6(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await sl(e,t.selector,"assertVisible");if(l.visible)return sp(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=si(e.baseReq,t,l,n);if("return"===u.kind)return u.response;let d=function(e){var t,r,a,n;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,a=e.startedAt,n=e.deadlineMs,!t&&r-a<n)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:i});if("capture-again"===d){o=!0;continue}if("finish"===d)break;await rq(250)}let s=r??oO("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await o9(e,t,a);return l||sc(s,a,e.baseReq)}async function o7(e,t,r,a){let n=await sl(e,t.selector,"assertVisible");if(n.visible)return sp(n.response,t.selector,a);let i=si(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await o9(e,t,n.snapshot);return o||sc(r,n.snapshot,e.baseReq)}async function o9(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=oL.get(e);return oL.delete(e),t}(e.scope);return a?"tap"===a.kind?await se(e,t,r,a):await st(e,t,a):null}async function se(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=oG(e.baseReq.flags),o=ed(t),s=oq(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:tp(s.rect)}};let l=oH(r.selector);return l&&(a=t,(n=l.trim().toLowerCase())&&a.nodes.some(e=>[e.label,e.value,e.identifier].some(e=>e?.trim().toLowerCase().includes(n))))?{ok:!0,target:{kind:"text",query:l}}:{ok:!1}}(e,r,a);return n.ok&&(tJ({level:"info",phase:"maestro_assert_visible_retry_tap",data:{selector:t.selector,tapSelector:a.selector,originalPoint:a.point,retryTarget:n.target,timeoutMs:5e3}}),(await sa(e,n.target)).ok)?await sr(e,t,"retryTap"):null}async function st(e,t,r){return(tJ({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await sn(e,r)).ok)?await sr(e,t,"retrySwipe"):null}async function sr(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=so(e.baseReq,a.selector);if(!n)return await o6(e,a);let i=Date.now(),o=await o8(e,a,n);return o.ok?(oE(e.scope,a.selector),sp({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await o7(e,a,o,i)}async function sa(e,t){return"text"===t.kind?await e.invoke({...e.baseReq,command:"find",positionals:[t.query,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}}):await e.invoke({...e.baseReq,command:"click",positionals:[String(t.point.x),String(t.point.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}async function sn(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function si(e,t,r,a){var n,i,o,s,l,u,d;return!(n=r.response).ok&&"COMMAND_FAILED"===n.error.code&&n.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=su(oH(e));if(!sd(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>su(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!sd(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,d=a,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-d,timeoutMs:u}})}:{kind:"continue"}}function so(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:oH(t)}function ss(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:oO("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:oO("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function sl(e,t,r){let a=await o$(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=oC(s.data);if(!l)return{visible:!1,response:oO("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=oT(l,i,oG(n.baseReq.flags),ed(l));return u.ok?(oE(n.scope,i),{visible:!0,response:{ok:!0,data:{selector:i,matches:u.matches,nodeIndex:u.node.index,nodeType:u.node.type,nodeLabel:u.node.label,nodeIdentifier:u.node.identifier,rect:u.rect}}}):{visible:!1,response:oO("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function su(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function sd(e){return"loading"===e||"loading..."===e}function sp(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function sc(e,a,n){var i;if(e.ok||!a)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,a){try{t.mkdirSync(a,{recursive:!0});let n=r.join(a,"failure-snapshot.json"),i=r.join(a,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
29
+ `);let o=ts(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return t.writeFileSync(i,`${o.join("\n")}
30
+ `),[n,i]}catch{return[]}}(a,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function sf(e){let t,r=ss(e.positionals,{command:"assertNotVisible",defaultTimeoutMs:3e3});if(!r.ok)return r.response;let a=Date.now(),n=0;for(;Date.now()-a<=r.timeoutMs;){let i=await sl(e,r.selector,"assertNotVisible");if(!i.visible&&i.infrastructureFailure)return i.response;if(i.visible)n=0,t=i.response;else{n+=1;let e=Date.now()-a;if(n>=2||e>=r.timeoutMs)return{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:e,timeoutMs:r.timeoutMs}}}await rq(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:oO("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function sm(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return oO("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await o$(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=oC(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?a?t===a?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:a}:{done:!0,response:e}:{done:!1}}(n,t,a);if(i.done)return i.response;t=i.signature??t,r=n,await rq(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function sh(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return oO("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return oO("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=oH(n),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await sN(e,n,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let a=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!a.ok)return a}return t=d,r=n,a=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${a}ms for selector: ${r}. Last wait: ${t.error.message}`}}:oO("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function sg(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return oO("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await o$(e);if(!i.ok)return i;let o=oC(i.data);if(!o)return oO("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=ed(o);if(!s)return oO("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=ta(s,a,n),u=await e.invoke({...e.baseReq,command:"click",positionals:[String(l.x),String(l.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});return u.ok&&oV(e.scope),u}async function sw(e){let t=await sv(e);if(t)return t;let r=await sS(e);return r.ok?await sb(e,r,r.durationMs):r.response}async function sv(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==oG(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function sy(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return oO("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:oO("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await sD(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rq(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??oO("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function sA(e){let[t,r="up",a]=e.positionals;if(!t)return oO("INVALID_ARGS","swipe.label requires a label selector.");let n=await sP(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=tp(e.rect),a=e.frame,n=oR(a?.referenceWidth,e.rect.width),i=oR(a?.referenceHeight,e.rect.height),o=ox,s=a?a.referenceWidth-o:r.x+n,l=a?a.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:tb(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:tb(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:tb(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:tb(r.x+n,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(n.target,r);return i.ok?await sb(e,i,a):oO("INVALID_ARGS",i.message)}async function sb(e,t,r){var a,n;let i=[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]],o=await e.invoke({...e.baseReq,command:"swipe",positionals:i});return o.ok&&(a=e.scope,n={kind:"swipe",positionals:i},a&&oL.set(a,n)),o}async function sS(e){var t;let r=((t=e.scope)?oM.get(t):void 0)??await s_(e);if(!r)return{ok:!1,response:oO("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[a,...n]=e.positionals;return"direction"===a?function(e,t,r){let[a,n]=e;if(!a)return{ok:!1,response:oO("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(a){case"up":case"down":var i,o,s;let l;return i=a,o=t,s=n,{ok:!0,start:tf({x:(l=ti({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:tf({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=sk(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=sI(r,t,i,50,o,50);return{ok:!0,start:ta(t,i,n.startY,{marginPx:s}),end:ta(t,o,n.endY,{marginPx:s}),durationMs:a}}(a,t,r,n);default:return{ok:!1,response:oO("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,oG(e.baseReq.flags)):"percent"===a?function(e,t,r){let[a,n,i,o,s]=e,l=[a,n,i,o].map(Number);if(l.some(e=>!Number.isFinite(e)))return{ok:!1,response:oO("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,d,p,c]=l,f=sk(r,u,d,p,c),m=sI(r,t,u,d,p,c);return{ok:!0,start:ta(t,u,f.startY,{marginPx:m}),end:ta(t,p,f.endY,{marginPx:m}),durationMs:s}}(n,r,oG(e.baseReq.flags)):{ok:!1,response:oO("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function s_(e){let t=await o$(e);if(t.ok)return ed(oC(t.data))}function sI(e,t,r,a,n,i){return"ios"!==e||a!==i||30>Math.abs(n-r)?1:Math.max(1,Math.round(.15*t.referenceWidth))}function sk(e,t,r,a,n){return"android"!==e||r!==n||50!==r||30>Math.abs(a-t)?{startY:r,endY:n}:{startY:65,endY:65}}async function sN(e,t,r,a){let n=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(a)]});return n.ok||!r?n:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(a)]})}async function sD(e,t,r){let a=oH(t),n=await sx(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await sM(e,a):{retry:!0,response:n.response}}async function sx(e,t,r){let a=await sP(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await sR(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function sR(e,t,r,a){let n=tp(r.rect);tJ({level:"debug",phase:"maestro_tap_target",data:{selector:t,node:{index:r.node.index,type:r.node.type,label:r.node.label,value:r.node.value,identifier:r.node.identifier,visibleToUser:r.node.visibleToUser},rect:r.rect,point:n}});let i=await e.invoke({...e.baseReq,command:"click",positionals:[String(n.x),String(n.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});if(i.ok){var o,s,l;(o=e.scope)&&oP.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&oL.set(s,l)}return{response:i,targetResolved:!0}}async function sM(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(tJ({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?(oV(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function sP(e,t,r,a,n){let i=await o$({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=oC(i.data);if(!o)return{ok:!1,response:oO("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=ed(o),l=oG(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?oP.get(n):void 0;if(!i)return;let o=oT(t,i.selector,r,a);if(o.ok)return tJ({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),d=oq(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!d.ok){let e=oH(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rE(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,rI(t),t.identifier,t.value].filter(e=>!!e).map(e=>rE(e));e.some(e=>e===r)?a.push(t):e.some(e=>e.includes(r))&&n.push(t)}return a.length>0?a:n}(e,t),o=oU({nodes:e.nodes,matches:i,platform:r}),s=oz(e.nodes,o.matches,void 0,t,a,!0===n.requireOnScreen,n.promoteTapTarget,n.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return d.ok?{ok:!0,target:{node:d.node,rect:d.rect,frame:s}}:{ok:!1,response:oO("ELEMENT_NOT_FOUND",d.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function sL(e){switch(e.command){case ig:return await o5(e);case iw:return await sf(e);case iv:return await sO(e);case iy:return await sm(e);case iA:return await sh(e);case ib:return await sw(e);case iS:return await sA(e);case i_:return await sy(e);case iI:return await sg(e);case ih:return function(e){let[r]=e.positionals;if(!r)return oO("INVALID_ARGS","runScript requires a file path.");try{let n=function(e){let{scriptPath:r,env:n}=e,i=t.readFileSync(r,"utf8"),o=Object.create(null);try{var s,u;a.runInNewContext(i,(s=n,u=o,{...s,output:u,json:iT,http:{post:(e,t)=>(function(e,t,r){let a=rv(process.execPath,["-e",iq],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==a.exitCode){let r;throw new l("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=a.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:a.exitCode,stderr:a.stderr})}try{return JSON.parse(a.stdout)}catch(r){throw new l("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,1e3),stderr:a.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:r,timeout:3e4})}catch(e){throw new l("COMMAND_FAILED",`Maestro runScript failed for ${r}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:r},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new l("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:r,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:n}}}catch(t){let e=o(t);return oO(e.code,e.message,e.details)}}(e);default:return}}async function sO(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function s$(e){for(let[t,r]of e.actions.entries()){let a=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!a.ok)return a}return{ok:!0,data:{ran:e.actions.length}}}async function sC(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await s$({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(a.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=a}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function sE(e){let t=await sV(e,e.control);return t.ok?t.matched?await sT(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function sV(e,t){if("visible"===t.mode)return await sF(e,t);let r=await sq(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function sF(e,t){let r=Date.now();for(;;){let a=await sq(e,t.selector);if(!a.ok)return{ok:!1,response:a.response};if(a.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await rq(250)}}async function sq(e,t){var r,a;let n,i=await o$(e);return i.ok?(r=e,a=t,(n=oC(i.data))?{ok:!0,matched:oT(n,a,oG(r.baseReq.flags),ed(n)).ok}:{ok:!1,response:oO("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function sT(e){let t=await s$({actions:e.control.actions,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return t.ok?{ok:!0,data:{ran:t.data?.ran,condition:e.control.mode,selector:e.control.selector}}:t}async function sU(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,d=rg(a,n,{file:i,line:o}),p=Date.now();sK(l,{type:"replay_action_start",ts:new Date(p).toISOString(),replayPath:i,line:o,step:s,command:d.command,positionals:d.positionals??[]});let c=await sG({req:t,sessionName:r,resolved:d,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>sU({req:t,sessionName:r,action:e.action,scope:n,filePath:i,line:e.line,step:e.step,tracePath:l,invoke:u})}),f=Date.now();return sK(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:d.command,ok:c.ok,durationMs:f-p,resultTiming:c.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(c.data):void 0,errorCode:c.ok?void 0:c.error.code}),c}async function sG(e){var t;let{req:r,sessionName:a,resolved:n,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,tZ(t,{...n.flags??{}})),p={token:r.token,session:a,flags:d,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await sH({control:n.replayControl,baseReq:p,line:o,step:s,invoke:l,invokeReplayAction:u})??await sL({command:n.command,baseReq:p,positionals:n.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...p,command:n.command,positionals:n.positionals??[]});if(c.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(c.data);e&&rw(i,e)}return c}async function sH(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await sC({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await sE({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function sK(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
31
+ `)}async function sB(e){let{req:a,sessionName:n,logPath:i,sessionStore:s,tracePath:u,invoke:d}=e,p=a.positionals?.[0];if(!p)return T("INVALID_ARGS","replay requires a path");let c="",f=new Set;try{var m,h,g,w,v,y,A,b,S,_,I,k,N,D,x,R,M,P,L,O;c=ek.expandHome(p,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),o=e.trimStart()[0];if("{"===o||"["===o)return T("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let $=function(e,t,r={}){var a;let n=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=oA[t];if(!r)throw new l("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return n?{...n.parse(e,{...r,platform:t?.platform,env:(a=t,{...rn(t8(a?.replayShellEnv)),...ra(t9(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...t4(e),metadata:rr(e)}}(e,a.flags,{sourcePath:c}),C=$.metadata,E=C.platform||C.target?{...a,flags:(m=a.flags,h=C,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,V=$.actions,F=$.actionLines;if(a.flags?.replayUpdate===!0&&$.updateUnsupportedMessage)return T("INVALID_ARGS",$.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&C.env&&Object.keys(C.env).length>0)return T("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(a.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(sX(t.flags)||sX(t.runtime))return!0}return!1}(V))return T("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let q=rh({builtins:function(e){let{req:t,sessionName:a,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:a,AD_FILENAME:r.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let d=o.target??n.target;d&&(l.AD_TARGET=d);let p=o.device;"string"==typeof p&&p.length>0&&(l.AD_DEVICE=p);let c="string"==typeof o.serial?o.serial:o.udid;"string"==typeof c&&c.length>0&&(l.AD_DEVICE_ID=c),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:E,sessionName:n,metadata:C,resolvedPath:c}),fileEnv:C.env,shellEnv:rn(t8(a.flags?.replayShellEnv)),cliEnv:ra(t9(a.flags?.replayEnv))}),U=a.flags?.replayUpdate===!0,H=u??s.get(n)?.trace?.outPath,K=[],B=0;for(let e=0;e<V.length;e+=1){let t=V[e];if(!t||"replay"===t.command)continue;!function(e,t,r,a){var n;let i=G();i&&e4({type:"replay-test",...i,file:i.file||e,status:"progress",stepIndex:t+1,stepTotal:r,...(n=a,{stepCommand:function(e){if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(n.command),...function(e){let t=e.positionals??[],r=function(e){if(!e)return;let t=rV(e);if(!t)return;let r=t.selectors.flatMap(e=>e.terms.flatMap(e=>("label"===e.key||"text"===e.key||"id"===e.key)&&"string"==typeof e.value?[e.value]:[]));if(0===r.length)return;let a=r[0];return a&&r.every(e=>e===a)?a:void 0}(t[0]);return r?{stepValue:r}:"__maestroTapPointPercent"===e.command&&t.length>=2?{stepValue:`${t[0]},${t[1]}%`}:0===t.length?{}:{stepValue:t.join(" ")}}(n)})})}(c,e,V.length,t);let r=sW(s,n),a=await sU({req:E,sessionName:n,action:t,scope:q,filePath:c,line:F[e]??0,step:e+1,tracePath:H,invoke:d});if(K.push(...sJ(s,n,r)),a.ok){sz(a).forEach(e=>f.add(e));continue}if(sz(a).forEach(e=>f.add(e)),!U){return g=a,w=t,v=e,y=c,A=[...f],b=K,sj(g,w,v,y,A,rb(b))}let o=await oS({action:t,sessionName:n,logPath:i,sessionStore:s});if(!o){return S=a,_=t,I=e,k=c,N=[...f],D=K,sj(S,_,I,k,N,rb(D))}V[e]=o;let l=sW(s,n);if(a=await sU({req:E,sessionName:n,action:o,scope:q,filePath:c,line:F[e]??0,step:e+1,tracePath:H,invoke:d}),K.push(...sJ(s,n,l)),!a.ok){return sz(a).forEach(e=>f.add(e)),x=a,R=o,M=e,P=c,L=[...f],O=K,sj(x,R,M,P,L,rb(O))}sz(a).forEach(e=>f.add(e)),B+=1}U&&B>0&&rm(c,V,s.get(n));let j=rb(K);return{ok:!0,data:{replayed:V.length,healed:B,session:n,artifactPaths:[...f],...j?{snapshotDiagnostics:j}:{}}}}catch(t){let e=o(t);return T(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function sj(e,t,r,a,n=[],i){if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${rL(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:a,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:n,...i?{snapshotDiagnostics:i}:{}}}}}function sz(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&sY(e)))]:[]}if(!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,a="string"==typeof r.path?r.path:void 0;e?t.push(e):a&&t.push(a)}return[...new Set(t.filter(e=>sY(e)))]}function sW(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function sJ(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function sY(e){try{return t.statSync(e).isFile()}catch{return!1}}function sX(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(sX):!!e&&"object"==typeof e&&Object.values(e).some(sX)}async function sQ(e){let{req:t,sessionName:a,logPath:n,sessionStore:i,artifactsDir:o,tracePath:s}=e;if(t.flags?.recordVideo!==!0)return;let l=i.get(a);if(!l||l.recording)return;let u=rU(l.device.platform),d=o?r.join(o,`recording${u}`):rG(l.device.platform);s0(s,{type:"video_recording_start",session:a,videoPath:d}),tJ({phase:"replay_test_video_recording_start",data:{session:a,videoPath:d}});let p=await rT({req:{token:t.token,session:a,command:"record",positionals:["start",d],flags:{},meta:t.meta},sessionName:a,sessionStore:i,logPath:n});if(!p.ok)return s0(s,{type:"video_recording_start_failed",session:a,videoPath:d,errorCode:p.error.code}),p;let c=Date.now();return await rq(1e3),s0(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-c,requestedDurationMs:1e3}),tJ({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-c,data:{session:a,requestedDurationMs:1e3}}),p}async function sZ(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,tracePath:i,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!n.get(r)?.recording)return;s0(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rq(3e3);let l=Date.now(),u=await rT({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return sz(u).forEach(e=>o.add(e)),s0(i,{type:"video_recording_stop",session:r,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-s,errorCode:u.ok?void 0:u.error.code}),tJ({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function s0(e,t){oe(e,{...t,ts:new Date().toISOString()})}async function s1(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:o}=e;return"replay"===t.command?await sB({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o}):"test"===t.command?await oc({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:i,target:s,requestId:l,artifactsDir:u,artifactPaths:d,tracePath:p,shard:c})=>{let f=function(e){let{platform:t,target:r,artifactsDir:a,shard:n}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===a&&void 0===n)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==a?{artifactsDir:a}:{}};if(!n)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:n.device.platform,target:n.device.target,shardAll:void 0,shardSplit:void 0,shardCount:n.shardCount,shardIndex:n.shardIndex};return"android"===n.device.platform?{...s,serial:n.device.id}:{...s,udid:n.device.id}}({parentFlags:t.flags,platform:i,target:s,artifactsDir:u,shard:c}),m={req:t,sessionName:r,logPath:a,sessionStore:n,artifactsDir:u,tracePath:p},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await sQ(e)}}(m);return await sB({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:a,sessionStore:n,tracePath:p,invoke:async e=>{var t;let r=await sQ(m);return r&&!r.ok?r:(t=await o(e),d&&sz(t).forEach(e=>d.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await sZ({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await a8({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n,leaseRegistry:i})}}):null}function s3(e,t){var r;e.push(t),e4({type:"command",status:"progress",message:[tv(r=t),...tl(r)].join("\n")})}async function s2(e,t){let{device:r,metroPort:a,shouldProbeMetro:n,androidAdbExecutor:i}=t;if("android"!==r.platform||!n)return;let o=tM(r,i);s3(e,await s5(o,r.id,a))}async function s5(e,t,r){try{let a=await e(["reverse","--list"],{allowFailure:!0,timeoutMs:2e3}),n=`tcp:${r} tcp:${r}`,i=a.stdout.includes(n);return{id:"android-reverse",status:i?"pass":"warn",summary:i?`Android adb reverse exists for Metro port ${r}.`:`Android adb reverse is missing for Metro port ${r}.`,command:i?void 0:`adb -s ${t} reverse tcp:${r} tcp:${r}`,evidence:{stdout:a.stdout.trim()}}}catch(t){let e=s(t);return{id:"android-reverse",status:"warn",summary:"Could not inspect Android adb reverse mappings.",hint:e.message,evidence:{code:e.code}}}}async function s4(e,t){let{device:r,targetApp:a,session:n}=t;if(a)try{let t=await s8(r,a);if(!t)return void s3(e,{id:"target-app",status:"info",summary:`Target app installation checks are not supported for ${r.platform}.`,evidence:{requested:a,platform:r.platform}});s3(e,{id:"target-app",status:"pass",summary:`Target app is launchable: ${t}`,evidence:{requested:a,resolved:t,sessionApp:n?.appBundleId}})}catch(a){let t=s(a);s3(e,{id:"target-app",status:"fail",summary:`Target app check failed: ${t.message}`,hint:t.hint??"Install the app or pass an exact package/bundle id or app name.",command:`agent-device apps --platform ${r.platform} --all`,evidence:{code:t.code,message:t.message}})}}async function s8(e,t){if("android"===e.platform){let{listAndroidApps:r}=await import("./3340.js"),a=s6(t,(await r(e,"all")).map(e=>({id:e.package,name:e.name})));return a?.id}if("ios"===e.platform||"macos"===e.platform){let{listIosApps:r}=await import("./apps.js"),a=s6(t,(await r(e,"all")).map(e=>({id:e.bundleId,name:e.name})));return a?.id}}function s6(e,t){let r=e.trim().toLowerCase(),a=t.find(e=>e.id.toLowerCase()===r||e.name.toLowerCase()===r);if(a)return a;let n=t.filter(e=>e.id.toLowerCase().includes(r)||e.name.toLowerCase().includes(r));if(1===n.length)return n[0];if(n.length>1)throw new l("AMBIGUOUS_MATCH",`Multiple launchable apps matched "${e}"`,{matches:n.map(e=>e.id),hint:"Pass an exact package/bundle id from agent-device apps --all."});throw new l("APP_NOT_INSTALLED",`No launchable installed app matched "${e}"`)}async function s7(e,t,r){var a,n,i,o,l,u;let d,p=(a=t,n=r,en({platform:(d=a.flags??{}).platform??n?.device.platform,target:d.target??n?.device.target,device:d.device,udid:d.udid,serial:d.serial,iosSimulatorDeviceSet:d.iosSimulatorDeviceSet,androidDeviceAllowlist:d.androidDeviceAllowlist}));try{let t=await s9(p),r=(i=t.devices,o=p,i.filter(e=>tK(e,o,{includeExplicitSelectors:!0})));return s3(e,{id:"device",status:0===r.length?"fail":"pass",summary:function(e,t,r){var a,n;if(0===e.length)return r.length>0?`No ${le(t)} devices found; ${r.slice(0,2).map(e=>`${lt(e.platform)} inventory failed: ${e.message}`).join("; ")}.`:`No ${le(t)} devices found.`;let i=e.filter(e=>!0===e.booted).length,o=`${e.length} ${le(t)} ${(a=e.length,n="device",1===a?n:`${n}s`)} available; ${i} booted`,s=function(e,t){if(t.platform||t.target)return;let r=g(e),a={android:"Android",apple:"Apple",linux:"Linux",web:"web"};return["android","apple","linux","web"].flatMap(e=>{let t=r[e];return t.available>0?[`${a[e]} ${t.available} available, ${t.booted} booted`]:[]}).join("; ")}(e,t);return s?`${o} (${s}).`:`${o}.`}(r,p,t.failures),hint:0===r.length?(l=t.failures,l.find(e=>e.hint)?.hint??"Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors."):void 0,command:0===r.length?(u=p).platform?`agent-device devices --platform ${u.platform}`:"agent-device devices":void 0,evidence:function(e,t){let r=new Map;for(let t of e){let e=r.get(t.platform)??{available:0,booted:0};e.available+=1,!0===t.booted&&(e.booted+=1),r.set(t.platform,e)}return{available:e.length,booted:e.filter(e=>!0===e.booted).length,byPlatform:Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}(r,t.failures)}),r.length>0&&function(e,t){for(let a of t){var r;s3(e,(r=a,{id:`device-${r.platform}`,status:"warn",summary:`${lt(r.platform)} device inventory could not be read: ${r.message}`,hint:r.hint??`Check the ${lt(r.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:r.platform,code:r.code}}))}}(e,t.failures),{devices:r,platform:p.platform,target:p.target}}catch(r){let t=s(r);return s3(e,{id:"device",status:"fail",summary:t.message,hint:t.hint,command:"agent-device devices",evidence:{code:t.code,details:t.details}}),{devices:[],platform:p.platform,target:p.target}}}async function s9(e){if(e.platform)return{devices:await eI(e),failures:[]};let t=[],r=[];for(let a of p)try{t.push(...await eI({...e,platform:a}))}catch(e){r.push(function(e,t){let r=s(t);return{platform:e,message:r.message,hint:r.hint,code:r.code}}(a,e))}return{devices:t,failures:r}}function le(e){let t=e.platform?lt(e.platform):"local";return e.target?`${t} ${e.target}`:t}function lt(e){return"ios"===e?"iOS":"macos"===e?"macOS":"android"===e?"Android":"linux"===e?"Linux":"web"===e?"web":"Apple"}async function lr(e,t,r,a={}){let n=`http://${e}:${t}/status`;try{var i,o;let s=await fetch(n,{signal:AbortSignal.timeout(1500)}),l=await s.text(),u=s.ok&&l.toLowerCase().includes("packager-status:running"),d=u?await la(e,t,a):void 0;return{id:"metro",status:u?"pass":"warn",summary:u?(i=n,o=d,o?.cwd?`Metro is reachable at ${i} (cwd: ${o.cwd}).`:`Metro is reachable at ${i}.`):`Metro responded at ${n}, but did not report packager-status:running.`,hint:u?void 0:"Verify this is the Metro instance for the target app, or restart Metro.",evidence:{url:n,statusCode:s.status,body:l.slice(0,120),kind:r,...d?{process:d}:{}}}}catch(e){return{id:"metro",status:"auto"===r?"warn":"fail",summary:`Metro is not reachable at ${n}.`,hint:"Start Metro for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.",command:`curl -fsS ${n}`,evidence:{url:n,error:e instanceof Error?e.message:String(e),kind:r}}}}async function la(e,t,r){try{return await (r.resolveProcessInfo??ln)(e,t)}catch{return}}async function ln(e,t){var r;if("127.0.0.1"!==(r=e)&&"localhost"!==r&&"::1"!==r&&"0.0.0.0"!==r)return;let a=await li(t);if(void 0!==a)return{pid:a,cwd:await lo(a)}}async function li(e){let t=await ry("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-Fp"],{allowFailure:!0,timeoutMs:1500});if(0===t.exitCode)return t.stdout.split("\n").map(e=>e.startsWith("p")?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function lo(e){let t=await ry("lsof",["-nP","-a","-p",String(e),"-d","cwd","-Fn"],{allowFailure:!0,timeoutMs:1500});if(0===t.exitCode)return t.stdout.split("\n").find(e=>e.startsWith("n")&&e.length>1)?.slice(1)}let ls=["daemonBaseUrl","tenant","runId","leaseId","leaseProvider"],ll=["provider","providerSessionId","providerApp","providerOsVersion","providerProject","providerBuild","providerSessionName","awsProjectArn","awsDeviceArn","awsAppArn","awsRegion","awsInteractionMode"];function lu(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}async function ld(e,t){"android"===t?s3(e,await lp()):("ios"===t||"macos"===t||"apple"===t)&&s3(e,await lc())}async function lp(){var e,t,r;let a=process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT,n=await lf(a),i=await lm("adb",["version"]);return i?{id:"toolchain",status:(t=e={license:n,sdkRoot:a,versionLine:i}).versionLine&&t.sdkRoot&&"missing"!==t.license?"pass":"info",summary:e.versionLine?`Android toolchain: ${e.versionLine}; ${e.sdkRoot?"ANDROID_HOME/ANDROID_SDK_ROOT set":"ANDROID_HOME unset"}.`:"Android toolchain: adb is present but version check failed.",hint:"missing"===e.license?"Accept Android SDK licenses before installing/building apps.":void 0,command:"missing"===e.license?"sdkmanager --licenses":void 0,evidence:{adbVersion:e.versionLine??null,androidHome:e.sdkRoot??null,license:e.license}}:(r=a,{id:"toolchain",status:"info",summary:"Android toolchain: adb not found on PATH.",hint:"Install Android platform-tools or add adb to PATH.",evidence:{androidHome:r??null,license:n}})}async function lc(){var e,t;let r=await lm("xcodebuild",["-version"]);return r?{id:"toolchain",status:(e={selectedPath:await lm("xcode-select",["-p"]),versionLine:r}).versionLine?"pass":"info",summary:(t=e).versionLine?t.selectedPath?`Apple toolchain: ${t.versionLine}; xcode-select ${t.selectedPath}.`:`Apple toolchain: ${t.versionLine}; xcode-select path unavailable.`:"Apple toolchain: xcodebuild version check failed.",evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}:{id:"toolchain",status:"info",summary:"Apple toolchain: xcodebuild version check failed.",hint:"Install/select Xcode and complete first launch/license setup if xcodebuild reports it.",command:"xcodebuild -version"}}async function lf(e){if(!e)return"unknown";try{return await i(r.join(e,"licenses","android-sdk-license")),"accepted"}catch{return"missing"}}async function lm(e,t){try{let r=await ry(e,t,{allowFailure:!0,timeoutMs:3e3});if(0!==r.exitCode)return;return r.stdout.split("\n").map(e=>e.trim()).find(Boolean)}catch{return}}async function lh(e){var t,a,n,i;let o,s,l,{req:u,sessionName:d,sessionStore:p,androidAdbExecutor:c}=e;if(u.command!==rB.doctor)return null;let f=p.get(d),m=(s=rH(u.meta?.cwd),l=lu(u.flags?.targetApp)??f?.appBundleId,{targetApp:l,metroHost:lu(u.runtime?.metroHost)??"127.0.0.1",metroPort:("number"==typeof(t=u.runtime?.metroPort)&&Number.isInteger(t)&&t>0?t:void 0)??8081,kind:s,remote:u.flags?.remote===!0,shouldProbeMetro:(a=u,"auto"!==s||"number"==typeof a.runtime?.metroPort||"string"==typeof a.runtime?.metroHost)}),h=(n=p,i=d,o=r.dirname(n.resolveSessionDir(i)),"sessions"===r.basename(o)?r.dirname(o):o),g=[];if(!function(e,...t){for(let r of t)s3(e,r)}(g,{id:"agent-device",status:"pass",summary:`agent-device ${rj()} using ${h}`,evidence:{version:rj(),stateDir:h}},...function(e,t={}){var r;let a,n=(r=e,Object.keys(a={...Object.fromEntries([...ls,...ll].flatMap(e=>"string"==typeof r.flags?.[e]?[[e,"<configured>"]]:[])),...r.flags?.sessionIsolation==="tenant"?{sessionIsolation:"tenant"}:{}}).length>0?a:void 0);return n?[{id:"remote-connection",status:t.required?"pass":"info",summary:"Remote daemon/session or provider scope is configured.",evidence:n}]:t.required?[{id:"remote-connection",status:"fail",summary:"No remote daemon/session or provider scope is configured.",hint:"Use connect, --remote-config <path>, or direct remote/provider flags for the command."}]:[]}(u,{required:m.remote}),...function(e,t,r,a={}){let n=r?e.toArray().filter(e=>e.name!==r.name&&e.device.platform===r.device.platform&&e.device.id===r.device.id).map(e=>e.name):[];return r?[{id:"session",status:n.length>0?"warn":"pass",summary:n.length>0?`Other active sessions target the same device: ${n.join(", ")}`:`Active session ${r.name} targets ${r.device.name}`,hint:n.length>0?"Close stale sessions before a QA run if they belong to old attempts.":void 0,command:n.length>0?`agent-device close --session ${n[0]} --platform ${r.device.platform}`:void 0,evidence:{session:r.name,sameDeviceSessions:n,sessionStateDir:e.resolveSessionDir(r.name)}}]:[{id:"session",status:"info",summary:a.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:"This is expected before a run. Use open when app foreground state matters."}]}(p,d,f,{remote:m.remote})),m.remote)return lv(g,m);let w=await s7(g,u,f);await ld(g,f?.device.platform??w?.platform);let v=await lg({androidAdbExecutor:c,checks:g,inventory:w,options:m,session:f});return lv(g,m,{device:v,includeMetro:!0,inventory:w})}async function lg(e){let{checks:t,inventory:r,options:a,session:n,androidAdbExecutor:i}=e,o=n?.device??function(e,t,r){if(!r||!t)return;let a=t.devices.filter(e=>!0===e.booted);if(1===a.length)return a[0];s3(e,{id:"target-app-device",status:"fail",summary:0===a.length?"Target app check needs one booted device; none matched.":`Target app check needs one booted device; ${a.length} matched.`,hint:0===a.length?"Boot a device, or adjust --platform/--target/--device/--udid/--serial.":"Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.",command:t.platform?`agent-device devices --platform ${t.platform}`:"agent-device devices",evidence:{targetApp:r,booted:a.map(e=>({platform:e.platform,id:e.id,name:e.name}))}})}(t,r,a.targetApp);return o&&await lw(t,{androidAdbExecutor:i,device:o,options:a,session:n}),a.shouldProbeMetro&&s3(t,await lr(a.metroHost,a.metroPort,a.kind)),o}async function lw(e,t){let{androidAdbExecutor:r,device:a,options:n,session:i}=t;await s4(e,{device:a,session:i,targetApp:n.targetApp}),await s2(e,{androidAdbExecutor:r,device:a,metroPort:n.metroPort,shouldProbeMetro:n.shouldProbeMetro})}function lv(e,t,r={}){let a,n=e.some(e=>"fail"===e.status)?"fail":e.some(e=>"warn"===e.status)?"warn":"pass";return{ok:!0,data:{status:n,summary:"fail"===n?"Blockers found before the run.":"warn"===n?"No hard blockers found, but warnings need attention.":"No blockers found.",kind:t.kind,platform:r.device?.platform??r.inventory?.platform,target:r.device?.target??r.inventory?.target,targetApp:t.targetApp,metro:r.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:(a={fail:0,warn:1,pass:2,info:3},[...e].sort((e,t)=>a[e.status]-a[t.status]))}}}async function ly(e){var t,r,a,n,i,o,s,l,u;let d,p,{req:c,sessionName:f,logPath:m,sessionStore:h}=e,g=c.positionals?.[0]??"";if("ios-runner"!==g)return T("INVALID_ARGS","prepare requires a subcommand: ios-runner");let w=h.get(f),v=c.flags??{},y=r4(rB.prepare,w,v);if(y)return y;let A=await r6({session:w,flags:v,ensureReady:!0});if(!tG(A.platform))return T("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let b=Date.now(),S=await ep(A,(t=c,r=w,a=m,n=b,p=(i=t,"number"==typeof(d=i.flags?.timeoutMs)&&Number.isFinite(d)&&d>0?d:24e4),{...e6({req:t,logPath:a,traceLogPath:r?.trace?.outPath}),cleanStaleBundles:!0,buildTimeoutMs:p,healthTimeoutMs:p,prepareDeadline:tE.fromTimeoutMs(p,n),startupTimeoutMs:p}));return{ok:!0,data:(o=g,s=A,l=Math.max(0,Date.now()-b),u=S,{action:o,platform:s.platform,deviceId:s.id,deviceName:s.name,kind:s.kind,durationMs:l,...u,message:`Prepared Apple runner: ${s.name}`})}}async function lA(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=n.get(r),d=t.flags??{},p=r4(i,u,d);if(p)return p;let c=await r6({session:u,flags:d,ensureReady:!0}),m=X(i,c);if(m)return m;let h=await f(c,i,o,t.flags?.out,{...e_(a,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,h,c):u;tD(n,e,t,i,h??{},{positionals:s??o}),e!==u&&n.set(r,e)}return{ok:!0,data:h??{}}}async function lb(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=r4(rB.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return T("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await r6({session:i,flags:o,ensureReady:!0}),d=X(rB.clipboard,u);if(d)return d;let p=await f(u,rB.clipboard,t.positionals??[],t.flags?.out,{...e_(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return tD(n,i,t,t.command,p??{}),{ok:!0,data:{platform:u.platform,...p??{}}}}async function lS(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i=new eC,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:l,androidAdbExecutor:u}=e;if(t.command===rB.doctor)return await lh({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:u});if("inventory"===S(t.command))return await nr({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await ax({req:t,sessionName:r,sessionStore:n});if("state"===S(t.command))return await ns({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rB.clipboard)return await lb({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rB.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==(t.flags??{}).platform?await lA({req:t,sessionName:r,logPath:a,sessionStore:n,command:rB.keyboard,positionals:t.positionals??[]}):T("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===S(t.command))return await n6({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:u});if(t.command===rB.prepare)return await ly({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rB.install||t.command===rB.reinstall)return await ne({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===rB.install?a9:a7});if(t.command===rK.installSource)return await rX({req:t,sessionName:r,sessionStore:n});if(t.command===rK.releaseMaterializedPaths)return await r2({req:t});if(t.command===rB.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await lA({req:t,sessionName:r,logPath:a,sessionStore:n,command:rB.push,positionals:[i,"file"===(e=eO(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>ek.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):T("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===rB.triggerAppEvent?await lA({req:t,sessionName:r,logPath:a,sessionStore:n,command:rB.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await aH(e.device,r,e.appBundleId,aU)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===rB.open?await a0({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===S(t.command)?await s1({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:l??s}):t.command===rB.batch?await nt(t,r,s):t.command===rB.close?await a8({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,leaseLifecycleProvider:o}):null}export{rz as session_namespaceObject};