agent-device 0.21.0 → 0.21.2

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 (328) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.apk → agent-device-android-ime-helper-0.21.2.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.manifest.json → agent-device-android-ime-helper-0.21.2.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.manifest.json → agent-device-android-snapshot-helper-0.21.2.manifest.json} +6 -6
  7. package/apple/snapshot-bridge/README.md +58 -1
  8. package/apple/snapshot-bridge/SnapshotBridge.m +6 -0
  9. package/apple/snapshot-bridge/SnapshotBridgeCapture.h +25 -0
  10. package/apple/snapshot-bridge/SnapshotBridgeCapture.m +138 -0
  11. package/apple/snapshot-bridge/SnapshotBridgeRuntime.h +1 -0
  12. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +32 -3
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +12 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +413 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +15 -15
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +72 -0
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +63 -14
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +668 -82
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +48 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +39 -4
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1078 -211
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +290 -0
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +1 -1
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +10 -10
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +250 -74
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +101 -42
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +13 -13
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +55 -43
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +71 -4
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +144 -7
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +13 -1
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +216 -17
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +206 -22
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +289 -42
  36. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +92 -22
  37. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +617 -122
  38. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +79 -4
  39. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +71 -71
  40. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +92 -6
  41. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +67 -67
  42. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +4 -4
  43. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +17 -17
  44. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +30 -30
  45. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +31 -31
  46. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +28 -0
  47. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +101 -0
  48. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +19 -19
  49. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +55 -17
  50. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +26 -5
  51. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +126 -75
  52. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +8 -12
  53. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +9 -9
  54. package/dist/src/absence-observation-errors.js +1 -0
  55. package/dist/src/adapter.js +1 -1
  56. package/dist/src/adb-executor.js +1 -1
  57. package/dist/src/adb-failure.js +1 -1
  58. package/dist/src/agent-browser-lifecycle.js +1 -1
  59. package/dist/src/agent-browser-process-record.js +1 -1
  60. package/dist/src/agent-browser-provider.js +1 -1
  61. package/dist/src/agent-browser-tool.js +1 -1
  62. package/dist/src/agent-device-client.js +2 -2
  63. package/dist/src/ai-sdk.d.ts +1 -1
  64. package/dist/src/ai-sdk.js +1 -1
  65. package/dist/src/alert-runtime.js +1 -1
  66. package/dist/src/android-input-ownership.js +1 -1
  67. package/dist/src/app-catalog.js +1 -1
  68. package/dist/src/app-deployment-resolution.js +1 -1
  69. package/dist/src/app-helpers.js +1 -1
  70. package/dist/src/app-inventory-contract.js +1 -1
  71. package/dist/src/app-inventory.js +1 -1
  72. package/dist/src/app-launch.js +2 -2
  73. package/dist/src/app-lifecycle.js +3 -3
  74. package/dist/src/app-lifecycle2.js +1 -1
  75. package/dist/src/app-log-files.js +1 -1
  76. package/dist/src/app-log-runtime2.js +3 -3
  77. package/dist/src/app-resolution.js +1 -1
  78. package/dist/src/apple-runner-platform.js +1 -0
  79. package/dist/src/application-lifecycle-interaction.js +1 -1
  80. package/dist/src/archive.js +1 -1
  81. package/dist/src/artifact-download.js +1 -1
  82. package/dist/src/auth-session.js +1 -1
  83. package/dist/src/auth.js +1 -1
  84. package/dist/src/back-mode.js +1 -1
  85. package/dist/src/backend-snapshot-options.js +1 -1
  86. package/dist/src/boot-diagnostics.js +1 -1
  87. package/dist/src/browser-launch.js +1 -0
  88. package/dist/src/capture.js +1 -1
  89. package/dist/src/catalog.js +1 -1
  90. package/dist/src/cli-config.js +1 -1
  91. package/dist/src/cli-help.js +30 -26
  92. package/dist/src/cli.js +4 -4
  93. package/dist/src/click-button.js +1 -1
  94. package/dist/src/client-metro-companion.js +1 -1
  95. package/dist/src/client-metro.js +1 -1
  96. package/dist/src/client-types.d.ts +28 -13
  97. package/dist/src/code-signature-cache.js +1 -1
  98. package/dist/src/code-signature.js +1 -1
  99. package/dist/src/command-metadata.js +1 -1
  100. package/dist/src/command-schema.js +3 -3
  101. package/dist/src/command-tools.js +2 -2
  102. package/dist/src/command.js +1 -1
  103. package/dist/src/config.js +1 -1
  104. package/dist/src/connection-runtime.js +1 -1
  105. package/dist/src/connection.js +3 -3
  106. package/dist/src/contracts.d.ts +1 -1
  107. package/dist/src/contracts.js +1 -1
  108. package/dist/src/daemon-client-lifecycle.js +1 -1
  109. package/dist/src/daemon-process.js +1 -1
  110. package/dist/src/daemon-shutdown-report.js +1 -1
  111. package/dist/src/daemon.js +1 -1
  112. package/dist/src/debug-symbols-facade.js +1 -1
  113. package/dist/src/device-boot.js +1 -0
  114. package/dist/src/device-claim-inspection.js +1 -1
  115. package/dist/src/device-claim-rule.js +1 -1
  116. package/dist/src/device-input-state.d.ts +1 -1
  117. package/dist/src/device-inventory-context.js +1 -1
  118. package/dist/src/device-rotation.js +1 -1
  119. package/dist/src/device-selection-resolver.js +1 -1
  120. package/dist/src/device-session.js +1 -1
  121. package/dist/src/device2.js +1 -1
  122. package/dist/src/diagnostics.js +1 -1
  123. package/dist/src/dispatch-resolve.js +1 -1
  124. package/dist/src/doctor2.js +1 -1
  125. package/dist/src/durable-resource.js +1 -1
  126. package/dist/src/engine-eval-script.js +1 -0
  127. package/dist/src/error.js +1 -1
  128. package/dist/src/exec.js +1 -1
  129. package/dist/src/file.js +1 -1
  130. package/dist/src/find.js +1 -1
  131. package/dist/src/finders.js +1 -1
  132. package/dist/src/format.js +1 -2
  133. package/dist/src/generic-settle.js +1 -1
  134. package/dist/src/gesture-plan.js +1 -1
  135. package/dist/src/gesture-runtime.js +1 -1
  136. package/dist/src/harmonyos.js +1 -1
  137. package/dist/src/hdc.js +1 -1
  138. package/dist/src/helper.js +2 -2
  139. package/dist/src/human-control-contract.js +1 -1
  140. package/dist/src/human-control.js +1 -1
  141. package/dist/src/index.d.ts +1 -1
  142. package/dist/src/index.js +1 -1
  143. package/dist/src/input-actions.js +1 -1
  144. package/dist/src/input-actions2.js +2 -2
  145. package/dist/src/install-artifact-facade.js +1 -1
  146. package/dist/src/install-source-network-transport.js +1 -1
  147. package/dist/src/install-source2.js +1 -1
  148. package/dist/src/interaction-positionals.js +1 -1
  149. package/dist/src/interaction-ref-policy.js +1 -1
  150. package/dist/src/interaction.js +1 -1
  151. package/dist/src/interaction2.js +1 -1
  152. package/dist/src/interactor.js +5 -5
  153. package/dist/src/interactor2.js +1 -1
  154. package/dist/src/interactors.js +1 -1
  155. package/dist/src/internal/bin.js +1 -1
  156. package/dist/src/internal/daemon.js +2 -2
  157. package/dist/src/internal/png-worker.d.ts +3 -0
  158. package/dist/src/internal/png-worker.js +1 -1
  159. package/dist/src/internal/run-script-http-child.js +1 -1
  160. package/dist/src/inventory.js +2 -2
  161. package/dist/src/inventory2.js +1 -1
  162. package/dist/src/inventory3.js +1 -1
  163. package/dist/src/inventory5.js +1 -1
  164. package/dist/src/ios-snapshot-acquisition.js +1 -1
  165. package/dist/src/ios-snapshot-planning.js +1 -1
  166. package/dist/src/ios-snapshot-runtime.js +1 -1
  167. package/dist/src/ios-system-surface.js +1 -0
  168. package/dist/src/lease-scope.js +1 -1
  169. package/dist/src/lease.js +1 -1
  170. package/dist/src/limrun-runtime-dependencies.js +1 -1
  171. package/dist/src/limrun.d.ts +1 -1
  172. package/dist/src/linux.js +1 -1
  173. package/dist/src/local-interactor-operation-set.js +1 -1
  174. package/dist/src/location-coordinates.js +1 -1
  175. package/dist/src/managed-device-scope.js +1 -1
  176. package/dist/src/mechanics.js +16 -16
  177. package/dist/src/mobile-snapshot-semantics.js +1 -1
  178. package/dist/src/mp4-atoms.js +1 -0
  179. package/dist/src/multitouch-support.js +1 -1
  180. package/dist/src/observation.js +1 -1
  181. package/dist/src/open-target-resolution.js +1 -0
  182. package/dist/src/owner-identity.js +3 -3
  183. package/dist/src/parameterized-recorded-fill.js +1 -1
  184. package/dist/src/perf-facade.js +2 -2
  185. package/dist/src/perf-process-identity.js +1 -0
  186. package/dist/src/perf-runtime-operation-builder.js +1 -1
  187. package/dist/src/perf-runtime-plan.js +1 -1
  188. package/dist/src/perf.js +1 -1
  189. package/dist/src/physical-device-control.js +1 -1
  190. package/dist/src/platform-request-scope.js +1 -1
  191. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  192. package/dist/src/platform-runtime-app-log-process.js +1 -1
  193. package/dist/src/platform-runtime-host.js +1 -1
  194. package/dist/src/platform-runtime-managed-owner.js +1 -1
  195. package/dist/src/platform-runtime-open-target.js +1 -1
  196. package/dist/src/platform-runtime-operation-host.js +2 -2
  197. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  198. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  199. package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -1
  200. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  201. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  202. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  203. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  204. package/dist/src/platform-runtime-unavailable.js +1 -1
  205. package/dist/src/platform-runtime.js +1 -1
  206. package/dist/src/platform-runtime2.js +1 -1
  207. package/dist/src/png-crop-bytes.js +1 -0
  208. package/dist/src/png-worker-contract.js +1 -1
  209. package/dist/src/png.js +1 -0
  210. package/dist/src/prepare-kind.js +1 -1
  211. package/dist/src/process.js +1 -1
  212. package/dist/src/provider-device-runtime.js +1 -1
  213. package/dist/src/provider-session-ownership.js +1 -1
  214. package/dist/src/provider-webdriver.js +1 -1
  215. package/dist/src/proxy.js +1 -1
  216. package/dist/src/quality-warnings.js +1 -0
  217. package/dist/src/react-native.js +1 -1
  218. package/dist/src/record-runtime.js +1 -1
  219. package/dist/src/rect-center.js +1 -1
  220. package/dist/src/register-builtins.js +1 -1
  221. package/dist/src/registry.js +36 -36
  222. package/dist/src/remote-config2.js +1 -1
  223. package/dist/src/replay-divergence.js +1 -1
  224. package/dist/src/replay.js +2 -2
  225. package/dist/src/reporting.js +9 -8
  226. package/dist/src/request-admission.js +1 -1
  227. package/dist/src/request-cancel.js +1 -1
  228. package/dist/src/request-cancellation.js +1 -1
  229. package/dist/src/request-runtime-binding.js +1 -1
  230. package/dist/src/retry.js +1 -1
  231. package/dist/src/runner-cache-metadata.js +2 -2
  232. package/dist/src/runner-client.js +1 -1
  233. package/dist/src/runner-disposal.js +1 -1
  234. package/dist/src/runner-operations-facade.js +1 -1
  235. package/dist/src/runner-presentation.js +1 -1
  236. package/dist/src/runner.js +1 -1
  237. package/dist/src/runtime-transport-hints.js +1 -1
  238. package/dist/src/runtime.js +3 -3
  239. package/dist/src/runtime10.js +1 -0
  240. package/dist/src/runtime2.js +4 -4
  241. package/dist/src/runtime3.js +1 -1
  242. package/dist/src/runtime4.js +5 -4
  243. package/dist/src/runtime5.js +1 -1
  244. package/dist/src/runtime6.js +1 -1
  245. package/dist/src/runtime7.js +1 -1
  246. package/dist/src/runtime8.js +1 -1
  247. package/dist/src/runtime9.js +1 -1
  248. package/dist/src/screen-recording-live-handle.js +1 -1
  249. package/dist/src/screen-recording-options.js +1 -1
  250. package/dist/src/screen-recording-resource-recovery.js +1 -1
  251. package/dist/src/screenshot-density.js +1 -1
  252. package/dist/src/screenshot-runtime.js +1 -1
  253. package/dist/src/screenshot.js +1 -1
  254. package/dist/src/screenshot3.js +3 -3
  255. package/dist/src/script.js +1 -1
  256. package/dist/src/scroll-command.js +1 -1
  257. package/dist/src/scroll-gesture.js +1 -1
  258. package/dist/src/sdk-batch-runner.js +2 -2
  259. package/dist/src/sdk-batch.js +2 -2
  260. package/dist/src/sdk-contracts.d.ts +69 -26
  261. package/dist/src/sdk-contracts.js +2 -2
  262. package/dist/src/sdk-device.js +1 -1
  263. package/dist/src/sdk-finders.d.ts +1 -1
  264. package/dist/src/sdk-finders.js +1 -1
  265. package/dist/src/sdk-io.js +1 -1
  266. package/dist/src/sdk-remote-config.d.ts +1 -1
  267. package/dist/src/sdk-remote-config.js +1 -1
  268. package/dist/src/sdk-selectors.d.ts +80 -16
  269. package/dist/src/sdk-selectors.js +1 -1
  270. package/dist/src/selection.js +0 -0
  271. package/dist/src/selector-runtime.js +1 -1
  272. package/dist/src/selectors.js +1 -1
  273. package/dist/src/semantic-index.js +1 -1
  274. package/dist/src/server.js +3 -3
  275. package/dist/src/session-allocation.js +1 -1
  276. package/dist/src/session-observation.js +1 -0
  277. package/dist/src/session-routing.js +1 -1
  278. package/dist/src/session-runtime-admission.js +1 -1
  279. package/dist/src/session-snapshot.js +1 -1
  280. package/dist/src/session-store.js +3 -3
  281. package/dist/src/session-target-evidence.js +1 -1
  282. package/dist/src/session2.js +5 -5
  283. package/dist/src/settings.js +1 -1
  284. package/dist/src/simulator-boot.js +3 -0
  285. package/dist/src/simulator.js +1 -1
  286. package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
  287. package/dist/src/snapshot-runtime-binding.js +1 -1
  288. package/dist/src/snapshot-runtime.js +1 -1
  289. package/dist/src/snapshot-state.js +1 -1
  290. package/dist/src/snapshot2.js +1 -1
  291. package/dist/src/snapshot3.js +1 -1
  292. package/dist/src/snapshot4.js +1 -1
  293. package/dist/src/src.js +1 -1
  294. package/dist/src/src7.js +2 -2
  295. package/dist/src/src8.js +2 -2
  296. package/dist/src/string-enum.js +1 -1
  297. package/dist/src/takeover.js +1 -1
  298. package/dist/src/telemetry.js +1 -1
  299. package/dist/src/tool-provider.js +2 -2
  300. package/dist/src/tool-provider2.js +1 -1
  301. package/dist/src/tool-provider3.js +1 -1
  302. package/dist/src/toolchain-probe.js +1 -1
  303. package/dist/src/touch-reference-frame.js +1 -0
  304. package/dist/src/touch-runtime.js +1 -1
  305. package/dist/src/transport.js +1 -1
  306. package/dist/src/tree.js +1 -1
  307. package/dist/src/tv-remote.js +1 -1
  308. package/dist/src/type-text-runtime.js +1 -1
  309. package/dist/src/update-check.js +1 -1
  310. package/dist/src/vars.js +2 -0
  311. package/dist/src/verified-file.js +1 -1
  312. package/dist/src/version.js +1 -1
  313. package/dist/src/video.js +2 -2
  314. package/dist/src/viewport.js +1 -0
  315. package/dist/src/web.js +1 -1
  316. package/dist/src/web2.js +1 -1
  317. package/dist/src/webdriver-ios-snapshot.js +1 -1
  318. package/dist/src/webdriver-source.js +1 -1
  319. package/dist/src/window-state.js +1 -0
  320. package/package.json +4 -2
  321. package/server.json +2 -2
  322. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.0.apk.sha256 +0 -1
  323. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk +0 -0
  324. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk.sha256 +0 -1
  325. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -93
  326. package/dist/src/platform-runtime-apple-resources.js +0 -1
  327. package/dist/src/runner-selector-query.js +0 -1
  328. package/dist/src/snapshot-quality-verdict.js +0 -1
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{i as t,n,r,s as i}from"./sdk-remote-config.js";import{n as a}from"./path-resolution.js";import"./file.js";import o from"node:path";import s from"node:fs";function c(n){let r=n.env??process.env,c=d(n);if(!s.existsSync(c))throw new e(`INVALID_ARGS`,`Remote config file not found: ${c}`);let l;try{l=s.readFileSync(c,`utf8`)}catch(t){throw new e(`INVALID_ARGS`,`Failed to read remote config file: ${c}`,{cause:t instanceof Error?t.message:String(t)})}let u;try{u=JSON.parse(l)}catch(t){throw new e(`INVALID_ARGS`,`Invalid JSON in remote config file: ${c}`,{cause:t instanceof Error?t.message:String(t)})}if(!u||typeof u!=`object`||Array.isArray(u))throw new e(`INVALID_ARGS`,`Remote config file must contain a JSON object: ${c}`);let f={},p=u,m=o.dirname(c);for(let[n,o]of Object.entries(p)){let s=t(n);if(!s)throw new e(`INVALID_ARGS`,`Unsupported remote config key "${n}" in remote config file ${c}.`);let l=i(s,o,`remote config file ${c}`,n);f[s.key]=typeof l==`string`&&`path`in s&&s.path?a(l,{cwd:m,env:r}):l}return{resolvedPath:c,profile:f}}function l(e=process.env){let t={};for(let a of n){let n=r(a.key).map(t=>({name:t,value:e[t]})).find(e=>typeof e.value==`string`&&e.value.trim().length>0);n&&(t[a.key]=i(a,n.value,`environment variable ${n.name}`,n.name))}return t}function u(...e){let t={};for(let r of e)if(r)for(let e of n){let n=r[e.key];n!==void 0&&(t[e.key]=n)}return t}function d(e){let t=e.env??process.env;return a(e.configPath,{cwd:e.cwd,env:t})}function f(e){let t=c(e);return{resolvedPath:t.resolvedPath,profile:u(l(e.env),t.profile)}}export{d as n,f as r,c as t};
1
+ import{C as e}from"./sdk-contracts.js";import{i as t,n,r,s as i}from"./sdk-remote-config.js";import{n as a}from"./path-resolution.js";import"./file.js";import o from"node:path";import s from"node:fs";function c(n){let r=n.env??process.env,c=d(n);if(!s.existsSync(c))throw new e(`INVALID_ARGS`,`Remote config file not found: ${c}`);let l;try{l=s.readFileSync(c,`utf8`)}catch(t){throw new e(`INVALID_ARGS`,`Failed to read remote config file: ${c}`,{cause:t instanceof Error?t.message:String(t)})}let u;try{u=JSON.parse(l)}catch(t){throw new e(`INVALID_ARGS`,`Invalid JSON in remote config file: ${c}`,{cause:t instanceof Error?t.message:String(t)})}if(!u||typeof u!=`object`||Array.isArray(u))throw new e(`INVALID_ARGS`,`Remote config file must contain a JSON object: ${c}`);let f={},p=u,m=o.dirname(c);for(let[n,o]of Object.entries(p)){let s=t(n);if(!s)throw new e(`INVALID_ARGS`,`Unsupported remote config key "${n}" in remote config file ${c}.`);let l=i(s,o,`remote config file ${c}`,n);f[s.key]=typeof l==`string`&&`path`in s&&s.path?a(l,{cwd:m,env:r}):l}return{resolvedPath:c,profile:f}}function l(e=process.env){let t={};for(let a of n){let n=r(a.key).map(t=>({name:t,value:e[t]})).find(e=>typeof e.value==`string`&&e.value.trim().length>0);n&&(t[a.key]=i(a,n.value,`environment variable ${n.name}`,n.name))}return t}function u(...e){let t={};for(let r of e)if(r)for(let e of n){let n=r[e.key];n!==void 0&&(t[e.key]=n)}return t}function d(e){let t=e.env??process.env;return a(e.configPath,{cwd:e.cwd,env:t})}function f(e){let t=c(e);return{resolvedPath:t.resolvedPath,profile:u(l(e.env),t.profile)}}export{d as n,f as r,c as t};
@@ -1,2 +1,2 @@
1
- import{F as e}from"./sdk-contracts.js";function t(e){let t=e?.resume;if(typeof t?.allowed==`boolean`&&!(!Number.isInteger(t.from)||typeof t.planDigest!=`string`)&&!(!t.allowed&&typeof t.reason!=`string`)&&(t.repairSessionHeld===void 0||t.repairSessionHeld===!0)&&!(t.alternateFrom!==void 0&&!Number.isInteger(t.alternateFrom)))return t}const n={digest:8192,default:24576,full:65536};function r(e){return e===`digest`||e===`full`?e:`default`}function i(e,t=256){let n=Buffer.from(e,`utf8`);if(n.length<=t)return e;let r=`…<truncated>`,i=Buffer.byteLength(r,`utf8`),a=Math.max(0,t-i);for(;a>0&&(n[a]&192)==128;)--a;return`${n.subarray(0,a).toString(`utf8`)}${r}`}function a(t,n=256){return i(e(t),n)}function o(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function s(e){return(t,n)=>a(o(t,e),n)}function c(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function l(e,t){let n=r(t),i=n===`digest`?8:20,a=c(e.screen,i),o=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:a,suggestions:o}}function u(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function d(e){let{divergence:t,level:i,writeOverflowArtifact:a}=e,o=r(i),s=n[o],c=l(t,i),d=u(c);if(d<=s)return c;let p=d-s,m=a(l(t,`full`)),h=f(c);return`artifactPath`in m?{...h,overflow:{omittedBytes:p,artifactPath:m.artifactPath}}:{...h,artifactUnavailable:!0}}function f(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:a(e.step.source.path),line:e.step.source.line}},action:a(e.action),cause:{code:e.cause.code,message:a(e.cause.message),...e.cause.hint?{hint:a(e.cause.hint)}:{}},screen:{state:`unavailable`,reason:`omitted-for-size`,hint:`The screen digest and suggestions were omitted to stay within the response byte budget. See overflow.artifactPath (or retry at --level full) for the complete report.`},suggestions:[],suggestionCount:e.suggestionCount,resume:e.resume,repairHint:e.repairHint,...e.targetBinding?{targetBinding:e.targetBinding}:{}}}function p(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...E(n.step),...S(n.kind,n.targetBinding),...m(n.repairHint,n.resume),...D(n.screen),...j(n.suggestions,n.suggestionCount),...N(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
1
+ import{z as e}from"./sdk-contracts.js";function t(e){let t=e?.resume;if(typeof t?.allowed==`boolean`&&!(!Number.isInteger(t.from)||typeof t.planDigest!=`string`)&&!(!t.allowed&&typeof t.reason!=`string`)&&(t.repairSessionHeld===void 0||t.repairSessionHeld===!0)&&!(t.alternateFrom!==void 0&&!Number.isInteger(t.alternateFrom)))return t}const n={digest:8192,default:24576,full:65536};function r(e){return e===`digest`||e===`full`?e:`default`}function i(e,t=256){let n=Buffer.from(e,`utf8`);if(n.length<=t)return e;let r=`…<truncated>`,i=Buffer.byteLength(r,`utf8`),a=Math.max(0,t-i);for(;a>0&&(n[a]&192)==128;)--a;return`${n.subarray(0,a).toString(`utf8`)}${r}`}function a(t,n=256){return i(e(t),n)}function o(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function s(e){return(t,n)=>a(o(t,e),n)}function c(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function l(e,t){let n=r(t),i=n===`digest`?8:20,a=c(e.screen,i),o=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:a,suggestions:o}}function u(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function d(e){let{divergence:t,level:i,writeOverflowArtifact:a}=e,o=r(i),s=n[o],c=l(t,i),d=u(c);if(d<=s)return c;let p=d-s,m=a(l(t,`full`)),h=f(c);return`artifactPath`in m?{...h,overflow:{omittedBytes:p,artifactPath:m.artifactPath}}:{...h,artifactUnavailable:!0}}function f(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:a(e.step.source.path),line:e.step.source.line}},action:a(e.action),cause:{code:e.cause.code,message:a(e.cause.message),...e.cause.hint?{hint:a(e.cause.hint)}:{}},screen:{state:`unavailable`,reason:`omitted-for-size`,hint:`The screen digest and suggestions were omitted to stay within the response byte budget. See overflow.artifactPath (or retry at --level full) for the complete report.`},suggestions:[],suggestionCount:e.suggestionCount,resume:e.resume,repairHint:e.repairHint,...e.targetBinding?{targetBinding:e.targetBinding}:{}}}function p(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...E(n.step),...S(n.kind,n.targetBinding),...m(n.repairHint,n.resume),...D(n.screen),...j(n.suggestions,n.suggestionCount),...N(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
2
2
  `):null}function m(e,t){if(typeof e!=`string`)return[];let n=v(e,t);return[`Repair hint: ${e}${n?` — ${n}`:``}`]}function h(e){let t=e;if(!t||typeof t.allowed!=`boolean`)return;if(!t.allowed)return{allowed:!1,reason:typeof t.reason==`string`?t.reason:void 0};let{from:n,planDigest:r,alternateFrom:i}=t;if(typeof n==`number`&&typeof r==`string`&&r.length!==0)return{allowed:!0,from:n,planDigest:r,alternateFrom:typeof i==`number`?i:void 0}}function g(e,t){return`replay --from ${e} --plan-digest ${t}`}function _(e){return e?.repairSessionHeld===!0}function v(e,t){let n=y(e,h(t));if(n!==void 0)return _(t)?`${n} Read-only inspection while armed (snapshot -i, get attrs, find, is) is excluded from the healed script by default — no --no-record needed. If the step you are repairing is itself a read, add --record to that command so it lands in the heal.`:n}function y(e,t){switch(e){case`record-and-heal`:return t?.allowed?`press the correct control via a blessed @ref from screen.refs (recorded), then ${g(t.from,t.planDigest)}.`:`press the correct control via a blessed @ref from screen.refs (recorded). ${x(t)}`;case`state-repair`:return t?.allowed?`fix app state with --no-record actions, then ${g(t.from,t.planDigest)} to re-run it.`:`fix app state with --no-record actions. ${x(t)}`;case`caution`:return b({lead:`something already matches the recorded selector; a blind re-press may repeat the mistake.`,guidance:t});case`manual`:return b({lead:`no safe automated repair could be proven; inspect the screen and repair by hand.`,guidance:t});default:return}}function b(e){let{lead:t,guidance:n}=e;if(!n?.allowed)return`${t} ${x(n)}`;let r=`if you fixed app state with --no-record actions: ${g(n.from,n.planDigest)}`;return n.alternateFrom===void 0?`${t} ${r}.`:`${t} ${r}; ${`if you performed the step's intent as a recorded action: ${g(n.alternateFrom,n.planDigest)}`}.`}function x(e){return e&&!e.allowed&&e.reason?`This step cannot currently be resumed automatically (${e.reason}) — run a fresh full replay instead.`:`This step cannot currently be resumed automatically — run a fresh full replay instead.`}function S(e,t){if(typeof e!=`string`||e===`action-failure`)return[];let n=t;return n?[C(e,n.matchCount),...w(n.mismatches),...T(n.candidates)]:[]}function C(e,t){return`Target binding: ${e}${typeof t==`number`?` (matchCount ${t})`:``} — recorded target evidence did not verify.`}function w(e){return!Array.isArray(e)||e.length===0?[]:[` mismatches: ${e.slice(0,5).join(`; `)}`]}function T(e){return!Array.isArray(e)||e.length===0?[]:[` ${e.length} candidate(s) shared the recorded identity:`,...e.slice(0,5).map(e=>` ${A(e)}`)]}function E(e){let t=e;if(typeof t?.index!=`number`)return[];let n=t.source,r=typeof n?.path==`string`&&typeof n.line==`number`?` (${n.path}:${n.line})`:``;return[`Divergence at step ${t.index}${r}`]}function D(e){let t=e;return t?.state===`available`&&Array.isArray(t.refs)?O(t.refs,t.refsGeneration):t?.state===`unavailable`?[k(t)]:[]}function O(e,t){let n=e.slice(0,8).map(A),r=e.length-n.length;return[`Screen: ${e.length} actionable ref(s) captured (refsGeneration ${t}).`,...n,...r>0?[` ... ${r} more`]:[]]}function k(e){let t=typeof e.hint==`string`&&e.hint.length>0?` ${e.hint}`:``;return`Screen: unavailable (${String(e.reason??`unknown`)}).${t}`}function A(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` @${String(t.ref)} [${String(t.role)}]${n}`}function j(e,t){return Array.isArray(e)&&e.length>0?[`Suggestions:`,...e.slice(0,5).map(M)]:typeof t==`number`&&t>0?[`Suggestions: ${t} available (omitted at this response level; rerun with --json for the full report).`]:[]}function M(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` - [${String(t.basis)}]${n} ${String(t.selector)}`}function N(e,t){return e&&typeof e==`object`?[`Full report written to ${String(e.artifactPath)}.`]:t===!0?[`Full report exceeded the response budget and the overflow artifact could not be written.`]:[]}export{o as a,t as i,s as n,p as r,d as t};
@@ -1,3 +1,3 @@
1
- import{y as e}from"./sdk-contracts.js";import{in as t,sn as n}from"./sdk-batch.js";import{n as r,r as i}from"./script.js";import{n as a}from"./path-resolution.js";import"./file.js";import"./gesture-plan.js";import{i as o,s}from"./src8.js";import{t as c}from"./compatibility-policy.js";import{t as l}from"./shared.js";import u from"node:path";import d from"node:fs";function f(e,t){return`${e},${t}`}const p={open:m,back:()=>({kind:`commands`,commands:[`back`]}),home:()=>({kind:`commands`,commands:[{pressKey:`Home`}]}),keyboard:_};function m(e){let[t,n]=e.positionals;if(!t)return{kind:`unsupported`,message:`open requires an app id or URL`};if(v(t))return{kind:`commands`,commands:[{openLink:t}]};let r=h(e,t);return n&&v(n)?{kind:`config`,appId:t,commands:[r,{openLink:n}]}:n?{kind:`unsupported`,message:`open with a non-URL second argument is unsupported`}:{kind:`config`,appId:t,commands:[r]}}function h(e,t){let n=g(e);return n?{launchApp:{appId:t,...n}}:`launchApp`}function g(e){let t=e.flags?.launchArgs,n={};return e.flags?.relaunch===!0&&(n.stopApp=!0),e.flags?.clearAppState===!0&&(n.clearState=!0),Array.isArray(t)&&t.length>0&&(n.launchArguments=t),Object.keys(n).length>0?n:void 0}function _(e){let[t]=e.positionals;return t===`dismiss`?{kind:`commands`,commands:[`hideKeyboard`]}:t===`enter`||t===`return`?{kind:`commands`,commands:[{pressKey:`Enter`}]}:{kind:`unsupported`,message:`keyboard ${t??``}`.trim()}}function v(e){return/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}var y=s();function b(e){return`${e.map(e=>(0,y.stringify)(e).trimEnd()).join(`
1
+ import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{an as n,cn as r}from"./sdk-batch.js";import{n as i,r as a}from"./script.js";import{n as o}from"./path-resolution.js";import"./file.js";import"./gesture-plan.js";import{i as s,s as c}from"./src8.js";import{t as l}from"./compatibility-policy.js";import{t as u}from"./shared.js";import d from"node:path";import f from"node:fs";function p(e,t){return`${e},${t}`}const m={open:h,back:()=>({kind:`commands`,commands:[`back`]}),home:()=>({kind:`commands`,commands:[{pressKey:`Home`}]}),keyboard:v};function h(e){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`open requires an app id or URL`};if(t(n))return{kind:`commands`,commands:[{openLink:n}]};let i=g(e,n);return r&&t(r)?{kind:`config`,appId:n,commands:[i,{openLink:r}]}:r?{kind:`unsupported`,message:`open with a non-URL second argument is unsupported`}:{kind:`config`,appId:n,commands:[i]}}function g(e,t){return{launchApp:{appId:t,..._(e)}}}function _(e){let t=e.flags?.launchArgs,n={};return e.flags?.relaunch===!0&&(n.stopApp=!0),e.flags?.clearAppState===!0&&(n.clearState=!0),Array.isArray(t)&&t.length>0&&(n.launchArguments=t),n}function v(e){let[t]=e.positionals;return t===`dismiss`?{kind:`commands`,commands:[`hideKeyboard`]}:t===`enter`||t===`return`?{kind:`commands`,commands:[{pressKey:`Enter`}]}:{kind:`unsupported`,message:`keyboard ${t??``}`.trim()}}var y=c();function b(e){return`${e.map(e=>(0,y.stringify)(e).trimEnd()).join(`
2
2
  ---
3
- `)}\n`}function x(t,n){let r={config:S(n.metadata),warnings:[],unsupported:[]},i=[];for(let[e,a]of t.entries()){let t=n.actionLines?.[e]??e+1,o=w(a,n.resolveSelector);switch(o.kind){case`commands`:i.push(...o.commands),J(r,o.warnings,a,t);break;case`config`:K(r,o.appId,a,t),i.push(...o.commands),J(r,o.warnings,a,t);break;case`unsupported`:r.unsupported.push({line:t,action:Q(a),message:o.message})}}if(r.unsupported.length>0)throw new e(`INVALID_ARGS`,`Cannot export replay to Maestro YAML: unsupported .ad action ${Z(r.unsupported)}.`,{unsupported:r.unsupported});return{yaml:X(r.config,i),warnings:r.warnings}}function S(e){return e?.env&&Object.keys(e.env).length>0?{env:e.env}:{}}const C={...p,click:T,press:T,longpress:E,fill:A,type:j,wait:M,find:P,screenshot:F,scroll:I,swipe:L};function w(e,t){return C[e.command]?.(e,t)??{kind:`unsupported`,message:`${e.command} has no Maestro equivalent`}}function T(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`${e.command} requires a target`};let i=V(n,r,t);if(!i)return{kind:`unsupported`,message:`tap target is not Maestro-compatible`};let a=H(e);return a.ok?e.flags?.doubleTap===!0?{kind:`commands`,commands:[{doubleTapOn:i}],warnings:[...N(n),...k(e,`doubleTapOn`)]}:typeof e.flags?.holdMs==`number`?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...N(n),O(e.flags.holdMs),...k(e,`longPressOn`)]}:{kind:`commands`,commands:[G(i,a.options)],warnings:N(n)}:{kind:`unsupported`,message:a.message}}function E(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`longpress requires a target`};let i=V(n,r,t);return i?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...N(n),...D(e).map(O)]}:{kind:`unsupported`,message:`longpress target is not Maestro-compatible`}}function D(e){let[t,n,r]=e.positionals,i=$(t)&&$(n)?r:n;return i&&$(i)?[Number(i)]:[]}function O(e){return`long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of ${e}ms`}function k(e,t){let n=[];return typeof e.flags?.count==`number`&&e.flags.count>1&&n.push(`tap --count ${e.flags.count} is not represented by Maestro ${t}`),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&n.push(`tap --interval-ms ${e.flags.intervalMs} is not represented by Maestro ${t}`),n}function A(e,t){let[n,r]=e.positionals;if(!n||r===void 0)return{kind:`unsupported`,message:`fill requires a target and text`};let i=V(n,void 0,t);return i?r.length===0?{kind:`commands`,commands:[{tapOn:i},`eraseText`],warnings:[...N(n),`fill "" exports as tapOn + eraseText; Maestro erases at most its 50-character default`]}:{kind:`commands`,commands:[{tapOn:i},{inputText:r}],warnings:[...N(n),`fill exports as tapOn + inputText; Maestro may append text instead of replacing existing field contents`]}:{kind:`unsupported`,message:`fill target is not Maestro-compatible`}}function j(e){let[t]=e.positionals;if(t===void 0)return{kind:`unsupported`,message:`type requires text`};let n=q(t);return n===null?{kind:`commands`,commands:[{inputText:t}]}:{kind:`commands`,commands:[{eraseText:n}]}}function M(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`wait requires a target or duration`};if($(n))return{kind:`commands`,commands:[{waitForAnimationToEnd:{timeout:Number(n)}}],warnings:[`wait <ms> exports as waitForAnimationToEnd and may return before the full duration`]};if(n===`absent`)return{kind:`unsupported`,message:`strict wait absent requires zero selector matches and is unsupported by Maestro`};if(n===`text`&&r)return{kind:`commands`,commands:[{extendedWaitUntil:{visible:r,timeout:Y(e,c.extendedWaitUntilTimeoutMs)}}]};let i=t(n);return i?{kind:`commands`,commands:[{extendedWaitUntil:{visible:i,timeout:Y(e,c.extendedWaitUntilTimeoutMs)}}],warnings:N(n)}:{kind:`unsupported`,message:`wait selector is not Maestro-compatible`}}function N(e){return n(e,`label`)?[`label= selectors export as Maestro text; Maestro text matching is broader than agent-device label-only matching`]:[]}function P(e){let[t,n,r]=e.positionals;return t!==`text`||!n||!r?{kind:`unsupported`,message:`only find text <query> exists|missing exports to Maestro`}:r===`exists`?{kind:`commands`,commands:[{assertVisible:n}]}:r===`missing`||r===`not-exists`?{kind:`commands`,commands:[{assertNotVisible:n}]}:{kind:`unsupported`,message:`find text assertion "${r}" is unsupported`}}function F(e){let[t]=e.positionals;return t?{kind:`commands`,commands:[{takeScreenshot:t}]}:{kind:`unsupported`,message:`screenshot requires an output path`}}function I(e){let[t]=e.positionals;return!t||t===`down`?{kind:`commands`,commands:[`scroll`]}:{kind:`unsupported`,message:`scroll ${t} is not exported yet`}}function L(e){let t=R(e);if(!t)return{kind:`unsupported`,message:`only coordinate swipe exports to Maestro`};let n=z(e);if(n===null)return{kind:`unsupported`,message:`swipe count must be a positive integer`};let r=B(e);return r?{kind:`unsupported`,message:r}:{kind:`commands`,commands:Array.from({length:n},()=>({swipe:t}))}}function R(e){let[t,n,r,i]=e.positionals;if(!(!$(t)||!$(n)||!$(r)||!$(i)))return{start:f(t,n),end:f(r,i),duration:100}}function z(e){let t=e.flags?.count??1;return Number.isInteger(t)&&t>=1?t:null}function B(e){if(e.flags?.pauseMs!==void 0)return`swipe --pause-ms has no Maestro equivalent`;if(e.flags?.pattern&&e.flags.pattern!==`one-way`)return`swipe ping-pong pattern has no Maestro equivalent`}function V(e,t,n){return $(e)&&$(t)?{point:f(e,t)}:e.startsWith(`@`)?null:n(e)}function H(e){let t=W(e);return t?{ok:!1,message:t}:{ok:!0,options:U(e)}}function U(e){let t={};return typeof e.flags?.count==`number`&&e.flags.count>1&&(t.repeat=e.flags.count),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&(t.delay=e.flags.intervalMs),t}function W(e){if(e.flags?.jitterPx!==void 0)return`tap --jitter-px has no Maestro equivalent`;if(e.flags?.clickButton&&e.flags.clickButton!==`primary`)return`tap --button ${e.flags.clickButton} has no Maestro equivalent`}function G(e,t){return Object.keys(t).length===0?{tapOn:e}:typeof e==`string`?{tapOn:{text:e,...t}}:e&&typeof e==`object`&&!Array.isArray(e)?{tapOn:{...e,...t}}:{tapOn:e}}function K(e,t,n,r){if(!e.config.appId){e.config.appId=t;return}e.config.appId!==t&&e.unsupported.push({line:r,action:Q(n),message:`multiple app ids cannot be represented in one Maestro config (${e.config.appId} vs ${t})`})}function q(e){return e.length===0||![...e].every(e=>e===`\b`)?null:e.length}function J(e,t,n,r){for(let i of t??[])e.warnings.push({line:r,action:Q(n),message:i})}function Y(e,t){let n=e.positionals.at(-1);return n&&$(n)?Number(n):t}function X(e,t){return b(Object.keys(e).length>0?[e,t]:[t])}function Z(e){return e.map(e=>`line ${e.line} (${e.action}): ${e.message}`).join(`; `)}function Q(e){return[e.command,...e.positionals??[]].join(` `).trim()}function $(e){return e!==void 0&&Number.isFinite(Number(e))}const ee=async e=>{let{positionals:t}=e;return t[0]===`export`?await ne(e):te(e)};function te({positionals:t,flags:n}){if(t.length>1)throw new e(`INVALID_ARGS`,`replay accepts exactly one input path: replay <path>`);if(n.out!==void 0)throw new e(`INVALID_ARGS`,`replay --out is only supported with replay export.`);return!1}async function ne({positionals:n,flags:s}){re(n,s);let c=n[1];if(!c)throw new e(`INVALID_ARGS`,`replay export requires an input path.`);let f=a(c),p=d.readFileSync(f,`utf8`),m=r(p),h=x(m.actions,{actionLines:m.actionLines,metadata:i(p),resolveSelector:e=>t(e,o)}),g=typeof s.out==`string`?a(s.out):void 0;g&&(d.mkdirSync(u.dirname(g),{recursive:!0}),d.writeFileSync(g,h.yaml));for(let e of h.warnings)process.stderr.write(`Warning: line ${e.line}: ${e.message}\n`);return await l(s,{format:`maestro`,sourcePath:f,...g?{path:g}:{yaml:h.yaml},warnings:h.warnings},()=>g??h.yaml),!0}function re(t,n){if(t.length>2)throw new e(`INVALID_ARGS`,`replay export accepts exactly one input path: replay export <file.ad>`);if(n.replayUpdate)throw new e(`INVALID_ARGS`,`replay export does not support --update.`);if(n.replayMaestro)throw new e(`INVALID_ARGS`,`replay export reads .ad files; omit --maestro.`);if(n.replayEnv?.length)throw new e(`INVALID_ARGS`,`replay export does not evaluate --env substitutions.`)}export{ee as replayCommand};
3
+ `)}\n`}function x(t,n){let r={config:S(n.metadata),warnings:[],unsupported:[]},i=[];for(let[e,a]of t.entries()){let t=n.actionLines?.[e]??e+1,o=w(a,n.resolveSelector);switch(o.kind){case`commands`:i.push(...o.commands),K(r,o.warnings,a,t);break;case`config`:r.config.appId??=o.appId,i.push(...o.commands),K(r,o.warnings,a,t);break;case`unsupported`:r.unsupported.push({line:t,action:X(a),message:o.message})}}if(r.unsupported.length>0)throw new e(`INVALID_ARGS`,`Cannot export replay to Maestro YAML: unsupported .ad action ${Y(r.unsupported)}.`,{unsupported:r.unsupported});return{yaml:J(r.config,i),warnings:r.warnings}}function S(e){return e?.env&&Object.keys(e.env).length>0?{env:e.env}:{}}const C={...m,click:T,press:T,longpress:E,fill:A,type:j,wait:M,find:P,screenshot:F,scroll:I,swipe:L};function w(e,t){return C[e.command]?.(e,t)??{kind:`unsupported`,message:`${e.command} has no Maestro equivalent`}}function T(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`${e.command} requires a target`};let i=B(n,r,t);if(!i)return{kind:`unsupported`,message:`tap target is not Maestro-compatible`};let a=V(e);return a.ok?e.flags?.doubleTap===!0?{kind:`commands`,commands:[{doubleTapOn:i}],warnings:[...N(n),...k(e,`doubleTapOn`)]}:typeof e.flags?.holdMs==`number`?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...N(n),O(e.flags.holdMs),...k(e,`longPressOn`)]}:{kind:`commands`,commands:[W(i,a.options)],warnings:N(n)}:{kind:`unsupported`,message:a.message}}function E(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`longpress requires a target`};let i=B(n,r,t);return i?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...N(n),...D(e).map(O)]}:{kind:`unsupported`,message:`longpress target is not Maestro-compatible`}}function D(e){let[t,n,r]=e.positionals,i=Z(t)&&Z(n)?r:n;return i&&Z(i)?[Number(i)]:[]}function O(e){return`long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of ${e}ms`}function k(e,t){let n=[];return typeof e.flags?.count==`number`&&e.flags.count>1&&n.push(`tap --count ${e.flags.count} is not represented by Maestro ${t}`),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&n.push(`tap --interval-ms ${e.flags.intervalMs} is not represented by Maestro ${t}`),n}function A(e,t){let[n,r]=e.positionals;if(!n||r===void 0)return{kind:`unsupported`,message:`fill requires a target and text`};let i=B(n,void 0,t);return i?r.length===0?{kind:`commands`,commands:[{tapOn:i},`eraseText`],warnings:[...N(n),`fill "" exports as tapOn + eraseText; Maestro erases at most its 50-character default`]}:{kind:`commands`,commands:[{tapOn:i},{inputText:r}],warnings:[...N(n),`fill exports as tapOn + inputText; Maestro may append text instead of replacing existing field contents`]}:{kind:`unsupported`,message:`fill target is not Maestro-compatible`}}function j(e){let[t]=e.positionals;if(t===void 0)return{kind:`unsupported`,message:`type requires text`};let n=G(t);return n===null?{kind:`commands`,commands:[{inputText:t}]}:{kind:`commands`,commands:[{eraseText:n}]}}function M(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`wait requires a target or duration`};if(Z(n))return{kind:`commands`,commands:[{waitForAnimationToEnd:{timeout:Number(n)}}],warnings:[`wait <ms> exports as waitForAnimationToEnd and may return before the full duration`]};if(n===`absent`)return{kind:`unsupported`,message:`strict wait absent requires zero selector matches and is unsupported by Maestro`};if(n===`text`&&r)return{kind:`commands`,commands:[{extendedWaitUntil:{visible:r,timeout:q(e,l.extendedWaitUntilTimeoutMs)}}]};let i=t(n);return i?{kind:`commands`,commands:[{extendedWaitUntil:{visible:i,timeout:q(e,l.extendedWaitUntilTimeoutMs)}}],warnings:N(n)}:{kind:`unsupported`,message:`wait selector is not Maestro-compatible`}}function N(e){return r(e,`label`)?[`label= selectors export as Maestro text; Maestro text matching is broader than agent-device label-only matching`]:[]}function P(e){let[t,n,r]=e.positionals;return t!==`text`||!n||!r?{kind:`unsupported`,message:`only find text <query> exists|missing exports to Maestro`}:r===`exists`?{kind:`commands`,commands:[{assertVisible:n}]}:r===`missing`||r===`not-exists`?{kind:`commands`,commands:[{assertNotVisible:n}]}:{kind:`unsupported`,message:`find text assertion "${r}" is unsupported`}}function F(e){let[t]=e.positionals;return t?{kind:`commands`,commands:[{takeScreenshot:t}]}:{kind:`unsupported`,message:`screenshot requires an output path`}}function I(e){let[t]=e.positionals;return!t||t===`down`?{kind:`commands`,commands:[`scroll`]}:{kind:`unsupported`,message:`scroll ${t} is not exported yet`}}function L(e){let t=R(e);if(!t)return{kind:`unsupported`,message:`only coordinate swipe exports to Maestro`};let n=z(e);if(n===null)return{kind:`unsupported`,message:`swipe count must be a positive integer`};let r=ee(e);return r?{kind:`unsupported`,message:r}:{kind:`commands`,commands:Array.from({length:n},()=>({swipe:t}))}}function R(e){let[t,n,r,i]=e.positionals;if(!(!Z(t)||!Z(n)||!Z(r)||!Z(i)))return{start:p(t,n),end:p(r,i),duration:100}}function z(e){let t=e.flags?.count??1;return Number.isInteger(t)&&t>=1?t:null}function ee(e){if(e.flags?.pauseMs!==void 0)return`swipe --pause-ms has no Maestro equivalent`;if(e.flags?.pattern&&e.flags.pattern!==`one-way`)return`swipe ping-pong pattern has no Maestro equivalent`}function B(e,t,n){return Z(e)&&Z(t)?{point:p(e,t)}:e.startsWith(`@`)?null:n(e)}function V(e){let t=U(e);return t?{ok:!1,message:t}:{ok:!0,options:H(e)}}function H(e){let t={};return typeof e.flags?.count==`number`&&e.flags.count>1&&(t.repeat=e.flags.count),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&(t.delay=e.flags.intervalMs),t}function U(e){if(e.flags?.jitterPx!==void 0)return`tap --jitter-px has no Maestro equivalent`;if(e.flags?.clickButton&&e.flags.clickButton!==`primary`)return`tap --button ${e.flags.clickButton} has no Maestro equivalent`}function W(e,t){return Object.keys(t).length===0?{tapOn:e}:typeof e==`string`?{tapOn:{text:e,...t}}:e&&typeof e==`object`&&!Array.isArray(e)?{tapOn:{...e,...t}}:{tapOn:e}}function G(e){return e.length===0||![...e].every(e=>e===`\b`)?null:e.length}function K(e,t,n,r){for(let i of t??[])e.warnings.push({line:r,action:X(n),message:i})}function q(e,t){let n=e.positionals.at(-1);return n&&Z(n)?Number(n):t}function J(e,t){return b(Object.keys(e).length>0?[e,t]:[t])}function Y(e){return e.map(e=>`line ${e.line} (${e.action}): ${e.message}`).join(`; `)}function X(e){return[e.command,...e.positionals??[]].join(` `).trim()}function Z(e){return e!==void 0&&Number.isFinite(Number(e))}const Q=async e=>{let{positionals:t}=e;return t[0]===`export`?await te(e):$(e)};function $({positionals:t,flags:n}){if(t.length>1)throw new e(`INVALID_ARGS`,`replay accepts exactly one input path: replay <path>`);if(n.out!==void 0)throw new e(`INVALID_ARGS`,`replay --out is only supported with replay export.`);return!1}async function te({positionals:t,flags:r}){ne(t,r);let c=t[1];if(!c)throw new e(`INVALID_ARGS`,`replay export requires an input path.`);let l=o(c),p=f.readFileSync(l,`utf8`),m=i(p),h=x(m.actions,{actionLines:m.actionLines,metadata:a(p),resolveSelector:e=>n(e,s)}),g=typeof r.out==`string`?o(r.out):void 0;g&&(f.mkdirSync(d.dirname(g),{recursive:!0}),f.writeFileSync(g,h.yaml));for(let e of h.warnings)process.stderr.write(`Warning: line ${e.line}: ${e.message}\n`);return await u(r,{format:`maestro`,sourcePath:l,...g?{path:g}:{yaml:h.yaml},warnings:h.warnings},()=>g??h.yaml),!0}function ne(t,n){if(t.length>2)throw new e(`INVALID_ARGS`,`replay export accepts exactly one input path: replay export <file.ad>`);if(n.replayUpdate)throw new e(`INVALID_ARGS`,`replay export does not support --update.`);if(n.replayMaestro)throw new e(`INVALID_ARGS`,`replay export reads .ad files; omit --maestro.`);if(n.replayEnv?.length)throw new e(`INVALID_ARGS`,`replay export does not evaluate --env substitutions.`)}export{Q as replayCommand};
@@ -1,10 +1,11 @@
1
- import{y as e}from"./sdk-contracts.js";import{r as t}from"./replay-divergence.js";import{n}from"./entities.js";import{n as r,t as i}from"./color.js";import{t as a}from"./status-markers.js";import o from"node:path";import s from"node:fs";import c from"node:os";import{pathToFileURL as l}from"node:url";const u=[`onSuiteStart`,`onTestStart`,`onTestStep`,`onTestResult`,`onSuiteEnd`,`getExitCode`];async function ee(e){let t=te(e.modulePath);return re(await d(await ne(t),e.modulePath)({spec:e.raw,modulePath:t}),e.modulePath)}function d(t,n){let r=t.createReporter??t.default??t.reporter;if(!r)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export default, createReporter, or reporter.`);return typeof r==`function`?r:()=>r}function te(e){if(e.startsWith(`file:`))return e;let t=e.startsWith(`~/`)?o.join(c.homedir(),e.slice(2)):e;return o.resolve(process.cwd(),t)}async function ne(t){try{return await(t.startsWith(`file:`)?import(t):import(l(t).href))}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`INVALID_ARGS`,`Failed to load custom test reporter ${t}: ${r}`)}}function re(t,n){if(!t||typeof t!=`object`)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export a reporter object or factory.`);let r=t;if(typeof r.name!=`string`||r.name.trim().length===0)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must define name.`);for(let t of u)if(r[t]!==void 0&&typeof r[t]!=`function`)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} ${t} must be a function.`);return r}function f(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,``).replace(/\.$/,``)}s`}function ie(e){if(e.status===`skipped`)return[];let t=p(e);return t.length===0?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...t.map(({stop:e,start:t})=>v(e,t))]}function ae(e){let t=p(e),n=t.findIndex(({stop:e})=>e.ok===!1);if(n<0)return[];let r=t.slice(Math.max(0,n-2),n+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...r.map(({stop:e,start:t})=>v(e,t))]}function p(e){let t=oe(e);if(!t)return[];let n=se(t);if(n.length===0)return[];let r=[],i=[];for(let e of n){if(ce(e)){r.push(e);continue}le(e)&&i.push({stop:e,start:m(r,e)})}return i}function m(e,t){let n=t.command,r=e.findIndex(e=>e.step===t.step&&(n===void 0||e.command===void 0||e.command===n));if(!(r<0))return e.splice(r,1)[0]}function oe(e){return e.artifactsDir?o.join(e.artifactsDir,`attempt-${e.attempts}`,`replay-timing.ndjson`):void 0}function se(e){try{return s.readFileSync(e,`utf8`).split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return y(t)?[t]:[]}catch{return[]}})}catch{return[]}}function ce(e){return e.type===`replay_action_start`&&h(e)&&g(e,`line`)&&_(e,`command`)&&(e.positionals===void 0||Array.isArray(e.positionals))}function le(e){return de([e.type===`replay_action_stop`&&h(e)&&g(e,`line`)&&_(e,`command`),ue(e,`ok`),g(e,`durationMs`),_(e,`errorCode`),e.resultTiming===void 0||y(e.resultTiming)])}function h(e){return typeof e.step==`number`}function g(e,t){return e[t]===void 0||typeof e[t]==`number`}function _(e,t){return e[t]===void 0||typeof e[t]==`string`}function ue(e,t){return e[t]===void 0||typeof e[t]==`boolean`}function de(e){return e.every(Boolean)}function v(e,t){return` ${e.ok===!1?`[FAIL] `:e.ok===!0?``:`[info] `}${pe(t,e)}${fe(e,t)}`}function fe(e,t){let n=t?.line??e.line,r=[typeof n==`number`?`line ${n}`:``,typeof e.durationMs==`number`?f(e.durationMs):``,e.errorCode??``,e.resultTiming?`timing ${JSON.stringify(e.resultTiming)}`:``].filter(Boolean);return r.length>0?` (${r.join(`, `)})`:``}function pe(e,t){return[me(e?.command??t.command),...(e?.positionals??[]).map(he)].join(` `)}function me(e){return e??`unknown`}function he(e){return typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function y(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const b={interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`]},ge=b.interval;function _e(e={}){let t=new Set,n=!1,r=0,i=0,a=()=>{t.clear(),n=!1,r=0},o=t=>{if(!e.liveProgress)return;let a=ve(i);i+=1;let o=be(t.test,e,a),s=k(n?r:0,e.columns,e.terminalReflowsOnResize!==!1);return n=!0,r=M(o),{text:`${s}${o}`,newline:!1}},s=i=>{if(Oe(i.test)){let e=ke(i.test);if(t.has(e))return;t.add(e)}let a=ye(i.test,e);if(!a)return;let o=n?`${k(r,e.columns,e.terminalReflowsOnResize!==!1)}${a}`:a;return n=!1,r=0,{text:o,newline:!0}};return{render(e){if(e.type===`suite-start`){a();return}return e.type===`test-step`?o(e):e.type===`test-result`?s(e):void 0}}}function ve(e){return b.frames[e%b.frames.length]??b.frames[0]}function ye(e,t={}){if(e.status===`fail`&&e.retrying)return;let n=[w(e)];return Ce(n,e,t),t.verbose&&n.push(...Ne(e)),n.join(`
2
- `)}function be(e,t,n){let i=e.title?.trim(),a=o.basename(e.file),s=r(process.stderr),c=xe(n,{useColor:s}),l=`${O(e,{useColor:s})}${Se(e,{useColor:s})}`,u=`${c} `;return j(i?`${u}${j(i,Math.max(0,A(t.columns)-M(u)-M(l)))}${l}`:`${u}${a}${l}`,t.columns)}function xe(e,t={}){return t.useColor?D(e,`blue`):e}function Se(e,t={}){let n=`${e.stepIndex??0}/${e.stepTotal??0}`,r=e.stepCommand?.trim(),i=e.stepValue?.trim();if(!t.useColor)return` [${[n,r,i].filter(Boolean).join(` `)}]`;let a=D(`[`,`dim`),o=D(`]`,`dim`);return` ${a}${[D(n,`dim`),r?D(r,`magenta`):``,i?D(i,`green`):``].filter(Boolean).join(` `)}${o}`}function Ce(e,t,n){if(we(t,n))return;let r=Te(t),i=x(t);r&&e.push(r),i&&e.push(i),S(e,t),e.push(...C(t))}function we(e,t){return t.verbose===!0&&e.status===`fail`}function Te(e){return e.status===`fail`&&e.title?.trim()?` file: ${o.basename(e.file)}`:void 0}function x(e){let t=e.message?.replaceAll(/\s+/g,` `).trim();if(t)return` ${e.status===`fail`?`failed at: ${t}`:t}`}function S(e,t){let n=t.hint?.replaceAll(/\s+/g,` `).trim();t.status===`fail`&&n&&e.push(` hint: ${n}`)}function C(e){if(e.status!==`fail`||e.retrying)return[];let t=[];return e.session&&t.push(` session: ${e.session}`),e.artifactsDir&&t.push(` artifacts: ${e.artifactsDir}`),t}function w(e){let t=r(process.stderr);return`${E(e)} ${T(e)}${O(e,{useColor:t})}${e.durationMs===void 0?``:` ${De(e,{useColor:t})}`}`}function T(e){let t=e.title?.trim(),n=o.basename(e.file);return t||n}function E(e){return e.status===`pass`?a(`pass`,{passFormat:e.attempt&&e.attempt>1?`yellow`:`green`}):a(e.status===`fail`?`fail`:`skip`)}function D(e,t){return i(e,t,{validateStream:!1})}function O(e,t={}){if(typeof e.shardIndex!=`number`)return``;let n=typeof e.shardCount==`number`?e.shardCount:`?`,r=Ee(e),i=` [${e.shardIndex+1}/${n}${r?` ${r}`:``}]`;return t.useColor?D(i,`dim`):i}function Ee(e){return e.deviceName?.trim()||e.deviceId?.trim()||void 0}function De(e,t={}){let n=f(e.durationMs??0);return t.useColor?D(n,`yellow`):n}function Oe(e){return e.status===`pass`||e.status===`skip`||e.status===`fail`&&!e.retrying}function ke(e){let t=typeof e.shardIndex==`number`?e.shardIndex:``;return[e.status,e.index,e.total,e.file,e.title??``,t].join(`\0`)}function k(e,t,n){let r=n?Math.max(1,Math.ceil(e/A(t))):1,i=`\r\x1B[2K`;for(let e=1;e<r;e+=1)i+=`\x1B[1A\r\x1B[2K`;return i}function A(e){let t=typeof e==`function`?e():e;return typeof t==`number`&&Number.isFinite(t)&&t>0?Math.floor(t):80}function j(e,t){let n=A(t);return M(e)<=n?e:n<=0?``:n<=3?`.`.repeat(n):`${je(e,n-3)}...${Ae(e)?`\x1B[0m`:``}`}function M(e){let t=0;for(let n=0;n<e.length;){let r=N(e,n);if(r){n+=r.length;continue}t+=1,n+=1}return t}function Ae(e){return e.includes(`\x1B[`)}function je(e,t){if(t<=0)return``;let n=0,r=``;for(let i=0;i<e.length&&n<t;){let t=N(e,i);if(t){r+=t,i+=t.length;continue}r+=e[i],i+=1,n+=1}return r}function N(e,t){if(!e.startsWith(`\x1B[`,t))return null;for(let n=t+2;n<e.length;n+=1)if(Me(e.charCodeAt(n)))return e.slice(t,n+1);return null}function Me(e){return e>=64&&e<=126}function Ne(e){return e.status!==`pass`&&e.status!==`fail`||!e.artifactsDir||!e.attempt?[]:ie(e.status===`pass`?Pe(e):Fe(e)).map(e=>` ${e}`)}function Pe(e){return{...P(e),status:`passed`,replayed:0,healed:0}}function Fe(e){return{...P(e),status:`failed`,error:{code:`COMMAND_FAILED`,message:e.message??`Unknown test failure`}}}function P(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??``}}function F(e){return+(e.failed>0)}function Ie(e){return e.status===`failed`}function I(e){return e.status===`passed`&&e.attempts>1}function L(e){let t=K(e),n=o.basename(e.file);return`${t&&t.length>0?t:n}${q(e)}`}function Le(e){return`${K(e)??o.basename(e.file)}${q(e)}`}function R(e,t){return`artifactsDir`in e&&e.artifactsDir?`${t}: ${e.artifactsDir}`:void 0}function Re(e){return K(e)?`file: ${o.basename(e.file)}`:void 0}function z(e){return e.hint?`hint: ${e.hint}`:void 0}function B(e,t){return e.diagnosticId?`${t}: ${e.diagnosticId}`:void 0}function V(e,t){return e.logPath?`${t}: ${e.logPath}`:void 0}function H(e,t,n={}){n.includeMessage&&e.push(`errorMessage: ${t.message}`),W(e,z(t)),W(e,B(t,`diagnosticId`)),W(e,V(t,`logPath`)),n.includeDetails!==!1&&U(e,t,n.detailsIndent)}function U(e,t,n){let r=t.details?JSON.stringify(t.details,null,n):void 0;r&&e.push(`details: ${r}`)}function ze(e,t){!(`shardIndex`in t)||typeof t.shardIndex!=`number`||(e.push(`shardIndex: ${t.shardIndex}`),W(e,typeof t.shardCount==`number`?`shardCount: ${t.shardCount}`:void 0),W(e,typeof t.deviceId==`string`?`deviceId: ${t.deviceId}`:void 0),W(e,typeof t.deviceName==`string`?`deviceName: ${t.deviceName}`:void 0))}function Be(e){return e.status===`passed`?(e.warnings??[]).map(e=>`warning: ${e}`):[]}function W(e,t){t&&e.push(t)}function G(e){return(Math.max(0,e)/1e3).toFixed(3)}function Ve(e){return e!==void 0}function K(e){let t=e.title?.trim();return t&&t.length>0?t:void 0}function q(e){if(!(`shardIndex`in e)||typeof e.shardIndex!=`number`)return``;let t=typeof e.shardCount==`number`?e.shardCount:`?`,n=He(e);return` [${e.shardIndex+1}/${t}${n?` ${n}`:``}]`}function He(e){return(`deviceName`in e?e.deviceName?.trim():void 0)||(`deviceId`in e?e.deviceId?.trim():void 0)||void 0}function Ue(){let e,t,n,r=!1,i=(n,r)=>{o(),t=n.type===`test-step`?n:void 0,e??=_e({verbose:r.verbose,liveProgress:J(r),columns:()=>r.stderr.columns,terminalReflowsOnResize:We()});let i=e.render(n);i&&(r.stderr.write(i.newline?`${i.text}\n`:i.text),n.type===`test-step`&&J(r)&&a(r))},a=r=>{n||!t||(n=setInterval(()=>{if(!t)return;let n=e?.render(t);n&&r.stderr.write(n.newline?`${n.text}\n`:n.text)},ge),n.unref?.())},o=()=>{n&&=(clearInterval(n),void 0)},s=e=>{r||!J(e)||(e.stderr.write(`\x1B[?25l`),r=!0)},c=e=>{r&&=(e.stderr.write(`\x1B[?25h`),!1)};return{name:`default`,onSuiteStart:(e,t)=>{s(t),i({type:`suite-start`,suite:e},t)},onTestStep:(e,t)=>{i({type:`test-step`,test:e},t)},onTestResult:(e,t)=>{i({type:`test-result`,test:e},t)},onSuiteEnd:(e,n)=>{o(),t=void 0,c(n),Ge(e,n)},getExitCode:F}}function J(e){return e.stderr.isTTY&&!process.env.CI}function We(){return!process.env.TMUX&&!process.env.STY}function Ge(e,t){let n=e.tests.filter(I);t.stdout.write(`${Ke(e,n.length)}\n`),$e(e.tests.filter(Ie),t),Qe(n,t)}function Ke(e,t){let n=typeof e.durationMs==`number`?e.durationMs:void 0,i=r();return`Test summary: ${qe(e.passed,{useColor:i})} ${Je(e.total,{useColor:i})}${e.failed>0?`, ${e.failed} failed`:``}${t>0?`, ${t} flaky`:``}${n===void 0?``:` in ${Ye(n,{useColor:i})}`}`}function qe(e,t={}){let n=`${e} passed`;return t.useColor?i(n,`green`):n}function Je(e,t={}){let n=`(${e})`;return t.useColor?i(n,`dim`):n}function Ye(e,t={}){let n=f(e);return t.useColor?i(n,`yellow`):n}function Xe(){return r()?i(`✓`,`yellow`):`✓`}function Ze(e){return[z(e.error),R(e,`artifacts`),V(e.error,`log`),B(e.error,`diagnostic`)].filter(Ve)}function Qe(e,t){if(e.length!==0){t.stdout.write(`
1
+ import{C as e}from"./sdk-contracts.js";import{r as t}from"./replay-divergence.js";import{n}from"./entities.js";import{n as r,t as i}from"./color.js";import{t as a}from"./status-markers.js";import o from"node:path";import s from"node:fs";import c from"node:os";import{pathToFileURL as l}from"node:url";const u=[`onSuiteStart`,`onTestStart`,`onTestStep`,`onTestResult`,`onSuiteEnd`,`getExitCode`];async function ee(e){let t=te(e.modulePath);return re(await d(await ne(t),e.modulePath)({spec:e.raw,modulePath:t}),e.modulePath)}function d(t,n){let r=t.createReporter??t.default??t.reporter;if(!r)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export default, createReporter, or reporter.`);return typeof r==`function`?r:()=>r}function te(e){if(e.startsWith(`file:`))return e;let t=e.startsWith(`~/`)?o.join(c.homedir(),e.slice(2)):e;return o.resolve(process.cwd(),t)}async function ne(t){try{return await(t.startsWith(`file:`)?import(t):import(l(t).href))}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`INVALID_ARGS`,`Failed to load custom test reporter ${t}: ${r}`)}}function re(t,n){if(!t||typeof t!=`object`)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export a reporter object or factory.`);let r=t;if(typeof r.name!=`string`||r.name.trim().length===0)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must define name.`);for(let t of u)if(r[t]!==void 0&&typeof r[t]!=`function`)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} ${t} must be a function.`);return r}function f(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,``).replace(/\.$/,``)}s`}function ie(e){if(e.status===`skipped`)return[];let t=p(e);return t.length===0?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...t.map(({stop:e,start:t})=>v(e,t))]}function ae(e){let t=p(e),n=t.findIndex(({stop:e})=>e.ok===!1);if(n<0)return[];let r=t.slice(Math.max(0,n-2),n+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...r.map(({stop:e,start:t})=>v(e,t))]}function p(e){let t=oe(e);if(!t)return[];let n=se(t);if(n.length===0)return[];let r=[],i=[];for(let e of n){if(ce(e)){r.push(e);continue}le(e)&&i.push({stop:e,start:m(r,e)})}return i}function m(e,t){let n=t.command,r=e.findIndex(e=>e.step===t.step&&(n===void 0||e.command===void 0||e.command===n));if(!(r<0))return e.splice(r,1)[0]}function oe(e){return e.artifactsDir?o.join(e.artifactsDir,`attempt-${e.attempts}`,`replay-timing.ndjson`):void 0}function se(e){try{return s.readFileSync(e,`utf8`).split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return y(t)?[t]:[]}catch{return[]}})}catch{return[]}}function ce(e){return e.type===`replay_action_start`&&h(e)&&g(e,`line`)&&_(e,`command`)&&(e.positionals===void 0||Array.isArray(e.positionals))}function le(e){return de([e.type===`replay_action_stop`&&h(e)&&g(e,`line`)&&_(e,`command`),ue(e,`ok`),g(e,`durationMs`),_(e,`errorCode`),e.resultTiming===void 0||y(e.resultTiming)])}function h(e){return typeof e.step==`number`}function g(e,t){return e[t]===void 0||typeof e[t]==`number`}function _(e,t){return e[t]===void 0||typeof e[t]==`string`}function ue(e,t){return e[t]===void 0||typeof e[t]==`boolean`}function de(e){return e.every(Boolean)}function v(e,t){return` ${e.ok===!1?`[FAIL] `:e.ok===!0?``:`[info] `}${pe(t,e)}${fe(e,t)}`}function fe(e,t){let n=t?.line??e.line,r=[typeof n==`number`?`line ${n}`:``,typeof e.durationMs==`number`?f(e.durationMs):``,e.errorCode??``,e.resultTiming?`timing ${JSON.stringify(e.resultTiming)}`:``].filter(Boolean);return r.length>0?` (${r.join(`, `)})`:``}function pe(e,t){return[me(e?.command??t.command),...(e?.positionals??[]).map(he)].join(` `)}function me(e){return e??`unknown`}function he(e){return typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function y(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const b={interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`]},ge=b.interval;function _e(e={}){let t=new Set,n=!1,r=0,i=0,a=()=>{t.clear(),n=!1,r=0},o=t=>{if(!e.liveProgress)return;let a=ve(i);i+=1;let o=be(t.test,e,a),s=O(n?r:0,e.columns,e.terminalReflowsOnResize!==!1);return n=!0,r=j(o),{text:`${s}${o}`,newline:!1}},s=i=>{if(ke(i.test)){let e=Ae(i.test);if(t.has(e))return;t.add(e)}let a=ye(i.test,e);if(!a)return;let o=n?`${O(r,e.columns,e.terminalReflowsOnResize!==!1)}${a}`:a;return n=!1,r=0,{text:o,newline:!0}};return{render(e){if(e.type===`suite-start`){a();return}return e.type===`test-step`?o(e):e.type===`test-result`?s(e):void 0}}}function ve(e){return b.frames[e%b.frames.length]??b.frames[0]}function ye(e,t={}){if(e.status===`fail`&&e.retrying)return;let n=[C(e)];return Ce(n,e,t),t.verbose&&n.push(...Pe(e)),n.join(`
2
+ `)}function be(e,t,n){let i=e.title?.trim(),a=o.basename(e.file),s=r(process.stderr),c=xe(n,{useColor:s}),l=`${D(e,{useColor:s})}${Se(e,{useColor:s})}`,u=`${c} `;return A(i?`${u}${A(i,Math.max(0,k(t.columns)-j(u)-j(l)))}${l}`:`${u}${a}${l}`,t.columns)}function xe(e,t={}){return t.useColor?E(e,`blue`):e}function Se(e,t={}){let n=`${e.stepIndex??0}/${e.stepTotal??0}`,r=e.stepCommand?.trim(),i=e.stepValue?.trim();if(!t.useColor)return` [${[n,r,i].filter(Boolean).join(` `)}]`;let a=E(`[`,`dim`),o=E(`]`,`dim`);return` ${a}${[E(n,`dim`),r?E(r,`magenta`):``,i?E(i,`green`):``].filter(Boolean).join(` `)}${o}`}function Ce(e,t,n){if(we(t,n))return;let r=Te(t),i=Ee(t);r&&e.push(r),i&&e.push(i),x(e,t),e.push(...S(t))}function we(e,t){return t.verbose===!0&&e.status===`fail`}function Te(e){return e.status===`fail`&&e.title?.trim()?` file: ${o.basename(e.file)}`:void 0}function Ee(e){let t=e.message?.replaceAll(/\s+/g,` `).trim();if(t)return` ${e.status===`fail`?`failed at: ${t}`:t}`}function x(e,t){let n=t.hint?.replaceAll(/\s+/g,` `).trim();t.status===`fail`&&n&&e.push(` hint: ${n}`)}function S(e){if(e.status!==`fail`||e.retrying)return[];let t=[];return e.session&&t.push(` session: ${e.session}`),e.artifactsDir&&t.push(` artifacts: ${e.artifactsDir}`),t}function C(e){let t=r(process.stderr);return`${T(e)} ${w(e)}${D(e,{useColor:t})}${e.durationMs===void 0?``:` ${Oe(e,{useColor:t})}`}`}function w(e){let t=e.title?.trim(),n=o.basename(e.file);return t||n}function T(e){return e.status===`pass`?a(`pass`,{passFormat:e.attempt&&e.attempt>1?`yellow`:`green`}):a(e.status===`fail`?`fail`:`skip`)}function E(e,t){return i(e,t,{validateStream:!1})}function D(e,t={}){if(typeof e.shardIndex!=`number`)return``;let n=typeof e.shardCount==`number`?e.shardCount:`?`,r=De(e),i=` [${e.shardIndex+1}/${n}${r?` ${r}`:``}]`;return t.useColor?E(i,`dim`):i}function De(e){return e.deviceName?.trim()||e.deviceId?.trim()||void 0}function Oe(e,t={}){let n=f(e.durationMs??0);return t.useColor?E(n,`yellow`):n}function ke(e){return e.status===`pass`||e.status===`skip`||e.status===`fail`&&!e.retrying}function Ae(e){let t=typeof e.shardIndex==`number`?e.shardIndex:``;return[e.status,e.index,e.total,e.file,e.title??``,t].join(`\0`)}function O(e,t,n){let r=n?Math.max(1,Math.ceil(e/k(t))):1,i=`\r\x1B[2K`;for(let e=1;e<r;e+=1)i+=`\x1B[1A\r\x1B[2K`;return i}function k(e){let t=typeof e==`function`?e():e;return typeof t==`number`&&Number.isFinite(t)&&t>0?Math.floor(t):80}function A(e,t){let n=k(t);return j(e)<=n?e:n<=0?``:n<=3?`.`.repeat(n):`${Me(e,n-3)}...${je(e)?`\x1B[0m`:``}`}function j(e){let t=0;for(let n=0;n<e.length;){let r=M(e,n);if(r){n+=r.length;continue}t+=1,n+=1}return t}function je(e){return e.includes(`\x1B[`)}function Me(e,t){if(t<=0)return``;let n=0,r=``;for(let i=0;i<e.length&&n<t;){let t=M(e,i);if(t){r+=t,i+=t.length;continue}r+=e[i],i+=1,n+=1}return r}function M(e,t){if(!e.startsWith(`\x1B[`,t))return null;for(let n=t+2;n<e.length;n+=1)if(Ne(e.charCodeAt(n)))return e.slice(t,n+1);return null}function Ne(e){return e>=64&&e<=126}function Pe(e){return e.status!==`pass`&&e.status!==`fail`||!e.artifactsDir||!e.attempt?[]:ie(e.status===`pass`?Fe(e):Ie(e)).map(e=>` ${e}`)}function Fe(e){return{...N(e),status:`passed`,replayed:0,healed:0}}function Ie(e){return{...N(e),status:`failed`,error:{code:`COMMAND_FAILED`,message:e.message??`Unknown test failure`}}}function N(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??``}}function P(e){return+(e.failed>0)}function Le(e){return e.status===`failed`}function F(e){return e.status===`passed`&&e.attempts>1}function I(e){let t=G(e),n=o.basename(e.file);return`${t&&t.length>0?t:n}${K(e)}`}function Re(e){return`${G(e)??o.basename(e.file)}${K(e)}`}function L(e,t){return`artifactsDir`in e&&e.artifactsDir?`${t}: ${e.artifactsDir}`:void 0}function ze(e){return G(e)?`file: ${o.basename(e.file)}`:void 0}function R(e){return e.hint?`hint: ${e.hint}`:void 0}function z(e,t){return e.diagnosticId?`${t}: ${e.diagnosticId}`:void 0}function B(e,t){return e.logPath?`${t}: ${e.logPath}`:void 0}function V(e,t,n={}){n.includeMessage&&e.push(`errorMessage: ${t.message}`),U(e,R(t)),U(e,z(t,`diagnosticId`)),U(e,B(t,`logPath`)),n.includeDetails!==!1&&H(e,t,n.detailsIndent)}function H(e,t,n){let r=t.details?JSON.stringify(t.details,null,n):void 0;r&&e.push(`details: ${r}`)}function Be(e,t){!(`shardIndex`in t)||typeof t.shardIndex!=`number`||(e.push(`shardIndex: ${t.shardIndex}`),U(e,typeof t.shardCount==`number`?`shardCount: ${t.shardCount}`:void 0),U(e,typeof t.deviceId==`string`?`deviceId: ${t.deviceId}`:void 0),U(e,typeof t.deviceName==`string`?`deviceName: ${t.deviceName}`:void 0))}function Ve(e){return e.status===`passed`?(e.warnings??[]).map(e=>`warning: ${e}`):[]}function U(e,t){t&&e.push(t)}function W(e){return(Math.max(0,e)/1e3).toFixed(3)}function He(e){return e!==void 0}function G(e){let t=e.title?.trim();return t&&t.length>0?t:void 0}function K(e){if(!(`shardIndex`in e)||typeof e.shardIndex!=`number`)return``;let t=typeof e.shardCount==`number`?e.shardCount:`?`,n=Ue(e);return` [${e.shardIndex+1}/${t}${n?` ${n}`:``}]`}function Ue(e){return(`deviceName`in e?e.deviceName?.trim():void 0)||(`deviceId`in e?e.deviceId?.trim():void 0)||void 0}function We(){let e,t,n,r=!1,i=(n,r)=>{o(),t=n.type===`test-step`?n:void 0,e??=_e({verbose:r.verbose,liveProgress:q(r),columns:()=>r.stderr.columns,terminalReflowsOnResize:Ge()});let i=e.render(n);i&&(r.stderr.write(i.newline?`${i.text}\n`:i.text),n.type===`test-step`&&q(r)&&a(r))},a=r=>{n||!t||(n=setInterval(()=>{if(!t)return;let n=e?.render(t);n&&r.stderr.write(n.newline?`${n.text}\n`:n.text)},ge),n.unref?.())},o=()=>{n&&=(clearInterval(n),void 0)},s=e=>{r||!q(e)||(e.stderr.write(`\x1B[?25l`),r=!0)},c=e=>{r&&=(e.stderr.write(`\x1B[?25h`),!1)};return{name:`default`,onSuiteStart:(e,t)=>{s(t),i({type:`suite-start`,suite:e},t)},onTestStep:(e,t)=>{i({type:`test-step`,test:e},t)},onTestResult:(e,t)=>{i({type:`test-result`,test:e},t)},onSuiteEnd:(e,n)=>{o(),t=void 0,c(n),Ke(e,n)},getExitCode:P}}function q(e){return e.stderr.isTTY&&!process.env.CI}function Ge(){return!process.env.TMUX&&!process.env.STY}function Ke(e,t){let n=e.tests.filter(F);t.stdout.write(`${qe(e,n.length)}\n`),et(e.tests.filter(Le),t),$e(n,t)}function qe(e,t){let n=typeof e.durationMs==`number`?e.durationMs:void 0,i=r();return`Test summary: ${Je(e.passed,{useColor:i})} ${Ye(e.total,{useColor:i})}${e.failed>0?`, ${e.failed} failed`:``}${t>0?`, ${t} flaky`:``}${n===void 0?``:` in ${Xe(n,{useColor:i})}`}`}function Je(e,t={}){let n=`${e} passed`;return t.useColor?i(n,`green`):n}function Ye(e,t={}){let n=`(${e})`;return t.useColor?i(n,`dim`):n}function Xe(e,t={}){let n=f(e);return t.useColor?i(n,`yellow`):n}function Ze(){return r()?i(`✓`,`yellow`):`✓`}function Qe(e){return[R(e.error),L(e,`artifacts`),B(e.error,`log`),z(e.error,`diagnostic`)].filter(He)}function $e(e,t){if(e.length!==0){t.stdout.write(`
3
3
  `),t.stdout.write(`Flaky tests:
4
- `);for(let n of e){t.stdout.write(` ${Xe()} ${L(n)} after ${n.attempts} attempts${nt(n)}\n`);for(let e of n.attemptFailures??[]){let n=typeof e.durationMs==`number`?` (${f(e.durationMs)})`:``;t.stdout.write(` attempt ${e.attempt} failed${n}: ${e.message}\n`)}}}}function $e(e,t){if(e.length!==0){t.stdout.write(`
4
+ `);for(let n of e){t.stdout.write(` ${Ze()} ${I(n)} after ${n.attempts} attempts${rt(n)}\n`);for(let e of n.attemptFailures??[]){let n=typeof e.durationMs==`number`?` (${f(e.durationMs)})`:``;t.stdout.write(` attempt ${e.attempt} failed${n}: ${e.message}\n`)}}}}function et(e,t){if(e.length!==0){t.stdout.write(`
5
5
  `),t.stdout.write(`Failures:
6
- `);for(let n of e)t.stdout.write(` ${L(n)}\n`),et(n,t,` `)}}function et(e,t,n){let r=Re(e);r&&t.stdout.write(`${n}${r}\n`),t.stdout.write(`${n}${e.error?.message??`Unknown test failure`}\n`);for(let r of Ze(e))t.stdout.write(`${n}${r}\n`);if(tt(e,t,n),t.debug)for(let r of ae(e))t.stdout.write(`${n}${r}\n`)}function tt(e,n,r){let i=t(e.error?.details);if(i)for(let e of i.split(`
7
- `))n.stdout.write(`${r}${e}\n`)}function nt(e){let t=[typeof e.finalAttemptDurationMs==`number`?`passed attempt ${f(e.finalAttemptDurationMs)}`:``,e.durationMs>0?`total ${f(e.durationMs)}`:``].filter(Boolean);return t.length>0?` (${t.join(`, `)})`:``}function rt(e){let t=it(e);return{name:`junit`,onSuiteEnd:e=>at(t,e),getExitCode:F}}function it(t){if(t&&t.trim().length>0)return t;throw new e(`INVALID_ARGS`,`The junit test reporter requires an output path. Use --reporter junit:<path>.`)}function at(t,n){let r=o.dirname(t);try{s.mkdirSync(r,{recursive:!0}),s.writeFileSync(t,ot(n),`utf8`)}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`COMMAND_FAILED`,`Failed to write JUnit report to ${t}: ${r}`)}}function ot(e){let t=[`<?xml version="1.0" encoding="UTF-8"?>`,`<testsuites>`,` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${G(e.durationMs)}">`];for(let n of e.tests)t.push(...st(n));return t.push(` </testsuite>`),t.push(`</testsuites>`),`${t.join(`
8
- `)}\n`}function st(e){let t=n(Le(e)),r=[` <testcase classname="${n(`${o.dirname(e.file)===`.`?e.file:o.dirname(e.file)}${q(e)}`)}" name="${t}" file="${n(e.file)}" time="${G(e.durationMs)}">`];e.status===`failed`?r.push(` <failure message="${n(e.error.message)}">${n(ct(e))}</failure>`):e.status===`skipped`&&r.push(` <skipped message="${n(e.message)}" />`);let i=lt(e);return i&&r.push(` <system-out>${n(i)}</system-out>`),r.push(` </testcase>`),r}function ct(e){let t=[e.error.message];return H(t,e.error,{includeDetails:!1}),W(t,R(e,`artifactsDir`)),U(t,e.error,2),t.join(`
9
- `)}function lt(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return ut(t,e),t.join(`
10
- `)}function ut(e,t){W(e,`attempts`in t?`attempts: ${t.attempts}`:void 0),W(e,`session`in t?`session: ${t.session}`:void 0),W(e,`replayed`in t?`replayed: ${t.replayed}`:void 0),W(e,`healed`in t?`healed: ${t.healed}`:void 0);for(let n of Be(t))e.push(n);W(e,R(t,`artifactsDir`)),ze(e,t),t.status===`failed`&&dt(e,t),W(e,I(t)?`flaky: true`:void 0)}function dt(e,t){e.push(`errorCode: ${t.error.code}`),H(e,t.error,{includeMessage:!0})}function ft(e){if(e.type===`command`)return;if(e.type===`replay-test-suite`)return{type:`suite-start`,suite:{total:e.total,runnable:e.runnable,skipped:e.skipped,artifactsDir:e.artifactsDir,shardMode:e.shardMode,shardCount:e.shardCount}};let t={file:e.file,title:e.title,index:e.index,total:e.total,attempt:e.attempt,maxAttempts:e.maxAttempts,session:e.session,artifactsDir:e.artifactsDir,shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.deviceId,deviceName:e.deviceName};return e.status===`start`?{type:`test-start`,test:t}:e.status===`progress`?{type:`test-step`,test:{...t,stepIndex:e.stepIndex,stepTotal:e.stepTotal,stepCommand:e.stepCommand,stepValue:e.stepValue}}:{type:`test-result`,test:{...t,status:e.status,durationMs:e.durationMs,retrying:e.retrying,message:e.message,hint:e.hint}}}function pt(e){let t=e.reporters&&e.reporters.length>0?e.reporters.map(Y):e.json?[]:[Y(`default`)];return e.reportJunit&&t.push(Y(`junit:${e.reportJunit}`)),t}function Y(t){let n=t.trim();if(!n)throw new e(`INVALID_ARGS`,`Test reporter spec cannot be empty.`);if(ht(n))return{kind:`custom`,modulePath:n,raw:n};let{name:r,value:i}=mt(n);if(r==="default"){if(i!==void 0)throw new e(`INVALID_ARGS`,`The default test reporter does not accept options.`);return{kind:`builtin`,name:r,raw:n}}if(r===`junit`)return i===void 0?{kind:`builtin`,name:r,raw:n}:{kind:`builtin`,name:r,raw:n,outputPath:i};throw new e(`INVALID_ARGS`,`Unknown test reporter "${r}". Built-in reporters: default, junit:<path>. Custom reporters must be file paths.`)}function mt(e){let t=e.indexOf(`:`);return t<0?{name:e.trim()}:{name:e.slice(0,t).trim(),value:e.slice(t+1)}}function ht(e){return e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`~`)||e.startsWith(`file:`)}const X={"suite-start":`onSuiteStart`,"test-start":`onTestStart`,"test-step":`onTestStep`,"test-result":`onTestResult`};async function gt(e){let t=pt(e);return await Promise.all(t.map(xt))}async function _t(e,t,n){for(let r of e)await r.onSuiteEnd?.(t,n)}function vt(e,t,n){let r=ft(t);if(!r)return;let i=X[r.type];for(let t of e)try{let e=yt(t,r,n);e instanceof Promise&&e.catch(e=>Z(t,i,n,e))}catch(e){Z(t,i,n,e)}}function yt(e,t,n){switch(t.type){case`suite-start`:return e.onSuiteStart?.(t.suite,n);case`test-start`:return e.onTestStart?.(t.test,n);case`test-step`:return e.onTestStep?.(t.test,n);case`test-result`:return e.onTestResult?.(t.test,n)}}function Z(e,t,n,r){let i=r instanceof Error?r.message:String(r);n.stderr.write(`Reporter ${e.name} ${String(t)} failed: ${i}\n`)}function bt(e,t){let n=F(t);for(let r of e){let e=r.getExitCode?.(t);e!==void 0&&(n=Math.max(n,e))}return n}async function xt(e){return e.kind===`custom`?await ee(e):e.name==="default"?Ue():rt(e.outputPath)}async function St(e){let{suite:t,json:n,debug:r,verbose:i,reporter:a,reportJunit:o}=e,s=e.reporterRuntime??await Q({debug:r,verbose:i,reporter:a,reportJunit:o,json:n});if(await _t(s.reporters,t,s.context),n){let{printJson:e}=await import(`./json.js`);e({success:!0,data:t})}return bt(s.reporters,t)}async function Q(e){let t=await gt({reporters:e.reporter,reportJunit:e.reportJunit,json:e.json}),n=Ct({debug:e.debug,verbose:e.verbose});return{reporters:t,context:n,onProgress(e){vt(t,e,n)}}}function Ct(e){return{debug:e.debug,verbose:e.verbose??e.debug,stdout:$(process.stdout),stderr:$(process.stderr)}}function $(e){return{isTTY:e.isTTY===!0,columns:e.columns,write:t=>e.write(t)}}export{Q as createReplayTestReporterRuntime,St as renderReplayTestResponse};
6
+ `);for(let n of e)t.stdout.write(` ${I(n)}\n`),tt(n,t,` `)}}function tt(e,t,n){let r=ze(e);r&&t.stdout.write(`${n}${r}\n`),t.stdout.write(`${n}${e.error?.message??`Unknown test failure`}\n`);for(let r of Qe(e))t.stdout.write(`${n}${r}\n`);if(nt(e,t,n),t.debug)for(let r of ae(e))t.stdout.write(`${n}${r}\n`)}function nt(e,n,r){let i=t(e.error?.details);if(i)for(let e of i.split(`
7
+ `))n.stdout.write(`${r}${e}\n`)}function rt(e){let t=[typeof e.finalAttemptDurationMs==`number`?`passed attempt ${f(e.finalAttemptDurationMs)}`:``,e.durationMs>0?`total ${f(e.durationMs)}`:``].filter(Boolean);return t.length>0?` (${t.join(`, `)})`:``}function it(e){let t=at(e);return{name:`junit`,onSuiteEnd:e=>ot(t,e),getExitCode:P}}function at(t){if(t&&t.trim().length>0)return t;throw new e(`INVALID_ARGS`,`The junit test reporter requires an output path. Use --reporter junit:<path>.`)}function ot(t,n){let r=o.dirname(t);try{s.mkdirSync(r,{recursive:!0}),s.writeFileSync(t,st(n),`utf8`)}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`COMMAND_FAILED`,`Failed to write JUnit report to ${t}: ${r}`)}}function st(e){let t=[`<?xml version="1.0" encoding="UTF-8"?>`,`<testsuites>`,` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${W(e.durationMs)}">`];for(let n of e.tests)t.push(...ct(n));return t.push(` </testsuite>`),t.push(`</testsuites>`),`${t.join(`
8
+ `)}\n`}function ct(e){let t=J(Re(e)),n=[` <testcase classname="${J(`${o.dirname(e.file)===`.`?e.file:o.dirname(e.file)}${K(e)}`)}" name="${t}" file="${J(e.file)}" time="${W(e.durationMs)}">`];e.status===`failed`?n.push(` <failure message="${J(e.error.message)}">${J(lt(e))}</failure>`):e.status===`skipped`&&n.push(` <skipped message="${J(e.message)}" />`);let r=ut(e);return r&&n.push(` <system-out>${J(r)}</system-out>`),n.push(` </testcase>`),n}function J(e){let t=e.replaceAll(/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu,`�`);return n(t).replaceAll(` `,`&#9;`).replaceAll(`
9
+ `,`&#10;`).replaceAll(`\r`,`&#13;`)}function lt(e){let t=[e.error.message];return V(t,e.error,{includeDetails:!1}),U(t,L(e,`artifactsDir`)),H(t,e.error,2),t.join(`
10
+ `)}function ut(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return dt(t,e),t.join(`
11
+ `)}function dt(e,t){U(e,`attempts`in t?`attempts: ${t.attempts}`:void 0),U(e,`session`in t?`session: ${t.session}`:void 0),U(e,`replayed`in t?`replayed: ${t.replayed}`:void 0),U(e,`healed`in t?`healed: ${t.healed}`:void 0);for(let n of Ve(t))e.push(n);U(e,L(t,`artifactsDir`)),Be(e,t),t.status===`failed`&&ft(e,t),U(e,F(t)?`flaky: true`:void 0)}function ft(e,t){e.push(`errorCode: ${t.error.code}`),V(e,t.error,{includeMessage:!0})}function pt(e){if(e.type===`command`)return;if(e.type===`replay-test-suite`)return{type:`suite-start`,suite:{total:e.total,runnable:e.runnable,skipped:e.skipped,artifactsDir:e.artifactsDir,shardMode:e.shardMode,shardCount:e.shardCount}};let t={file:e.file,title:e.title,index:e.index,total:e.total,attempt:e.attempt,maxAttempts:e.maxAttempts,session:e.session,artifactsDir:e.artifactsDir,shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.deviceId,deviceName:e.deviceName};return e.status===`start`?{type:`test-start`,test:t}:e.status===`progress`?{type:`test-step`,test:{...t,stepIndex:e.stepIndex,stepTotal:e.stepTotal,stepCommand:e.stepCommand,stepValue:e.stepValue}}:{type:`test-result`,test:{...t,status:e.status,durationMs:e.durationMs,retrying:e.retrying,message:e.message,hint:e.hint}}}function mt(e){let t=e.reporters&&e.reporters.length>0?e.reporters.map(Y):e.json?[]:[Y(`default`)];return e.reportJunit&&t.push(Y(`junit:${e.reportJunit}`)),t}function Y(t){let n=t.trim();if(!n)throw new e(`INVALID_ARGS`,`Test reporter spec cannot be empty.`);if(X(n))return{kind:`custom`,modulePath:n,raw:n};let{name:r,value:i}=ht(n);if(r==="default"){if(i!==void 0)throw new e(`INVALID_ARGS`,`The default test reporter does not accept options.`);return{kind:`builtin`,name:r,raw:n}}if(r===`junit`)return i===void 0?{kind:`builtin`,name:r,raw:n}:{kind:`builtin`,name:r,raw:n,outputPath:i};throw new e(`INVALID_ARGS`,`Unknown test reporter "${r}". Built-in reporters: default, junit:<path>. Custom reporters must be file paths.`)}function ht(e){let t=e.indexOf(`:`);return t<0?{name:e.trim()}:{name:e.slice(0,t).trim(),value:e.slice(t+1)}}function X(e){return e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`~`)||e.startsWith(`file:`)}const gt={"suite-start":`onSuiteStart`,"test-start":`onTestStart`,"test-step":`onTestStep`,"test-result":`onTestResult`};async function _t(e){let t=mt(e);return await Promise.all(t.map(St))}async function vt(e,t,n){for(let r of e)await r.onSuiteEnd?.(t,n)}function yt(e,t,n){let r=pt(t);if(!r)return;let i=gt[r.type];for(let t of e)try{let e=bt(t,r,n);e instanceof Promise&&e.catch(e=>Z(t,i,n,e))}catch(e){Z(t,i,n,e)}}function bt(e,t,n){switch(t.type){case`suite-start`:return e.onSuiteStart?.(t.suite,n);case`test-start`:return e.onTestStart?.(t.test,n);case`test-step`:return e.onTestStep?.(t.test,n);case`test-result`:return e.onTestResult?.(t.test,n)}}function Z(e,t,n,r){let i=r instanceof Error?r.message:String(r);n.stderr.write(`Reporter ${e.name} ${String(t)} failed: ${i}\n`)}function xt(t,n){let r=P(n);for(let i of t){let t=i.getExitCode?.(n);if(t!==void 0){if(!Number.isInteger(t)||t<0||t>255)throw new e(`INVALID_ARGS`,`Test reporter ${i.name} getExitCode must return an integer from 0 to 255 or undefined.`);r=Math.max(r,t)}}return r}async function St(e){return e.kind===`custom`?await ee(e):e.name==="default"?We():it(e.outputPath)}async function Ct(e){let{suite:t,json:n,debug:r,verbose:i,reporter:a,reportJunit:o}=e,s=e.reporterRuntime??await Q({debug:r,verbose:i,reporter:a,reportJunit:o,json:n});await vt(s.reporters,t,s.context);let c=xt(s.reporters,t);if(n){let{printJson:e}=await import(`./json.js`);e({success:!0,data:t})}return c}async function Q(e){let t=await _t({reporters:e.reporter,reportJunit:e.reportJunit,json:e.json}),n=wt({debug:e.debug,verbose:e.verbose});return{reporters:t,context:n,onProgress(e){yt(t,e,n)}}}function wt(e){return{debug:e.debug,verbose:e.verbose??e.debug,stdout:$(process.stdout),stderr:$(process.stderr)}}function $(e){return{isTTY:e.isTTY===!0,columns:e.columns,write:t=>e.write(t)}}export{Q as createReplayTestReporterRuntime,Ct as renderReplayTestResponse};
@@ -1 +1 @@
1
- import{x as e,y as t}from"./sdk-contracts.js";import{T as n,w as r}from"./sdk-device.js";import{Yt as i}from"./sdk-batch.js";function a(a){let o=a.resolve?.(a.device,a.intent);if(!o||!i(o.lease.owner,a.intent.owner)||o.lease.fence.token!==a.intent.fence.token||o.lease.fence.generation!==a.intent.fence.generation||n(r(o.lease.reachability.device))!==n(r(a.device))||o.lease.reachability.device.simulatorSetPath!==a.device.simulatorSetPath)throw new t(`UNSUPPORTED_OPERATION`,`Managed binding has no matching lease admission.`,{reason:`managed-lease-admission-unavailable`});let{lease:s,horizon:c}=o,l=AbortSignal.any([a.scope.signal,a.lifetime]),u=!1,d=async n=>{let r=await s.run(c,l,n);if(r.status===`admitted`)return r.value;throw r.status===`abandoned`?e():new t(`COMMAND_FAILED`,`Managed lease does not authorize execution.`,{...r,reason:r.status===`teardown-required`?`managed-lease-teardown-required`:`managed-command-deadline-exceeded`,retriable:!1})},f=async e=>{if(!u)throw new t(`COMMAND_FAILED`,`Managed request is not admitted.`,{reason:`managed-request-not-admitted`});return await d(e)},p=async()=>await f(async()=>{}),m=Object.freeze({device:s.reachability.device,owner:s.owner,fence:s.fence,admit:f,run:s.reachability.run});return{scope:{...a.scope,managedDevice:m},bind:d,activate:()=>{if(l.aborted)throw e();u=!0},ensureReady:p}}export{a as createManagedRequestAdmission};
1
+ import{C as e,T as t}from"./sdk-contracts.js";import{T as n,w as r}from"./sdk-device.js";import{Xt as i}from"./sdk-batch.js";function a(a){let o=a.resolve?.(a.device,a.intent);if(!o||!i(o.lease.owner,a.intent.owner)||o.lease.fence.token!==a.intent.fence.token||o.lease.fence.generation!==a.intent.fence.generation||n(r(o.lease.reachability.device))!==n(r(a.device))||o.lease.reachability.device.simulatorSetPath!==a.device.simulatorSetPath)throw new e(`UNSUPPORTED_OPERATION`,`Managed binding has no matching lease admission.`,{reason:`managed-lease-admission-unavailable`});let{lease:s,horizon:c}=o,l=AbortSignal.any([a.scope.signal,a.lifetime]),u=!1,d=async n=>{let r=await s.run(c,l,n);if(r.status===`admitted`)return r.value;throw r.status===`abandoned`?t():new e(`COMMAND_FAILED`,`Managed lease does not authorize execution.`,{...r,reason:r.status===`teardown-required`?`managed-lease-teardown-required`:`managed-command-deadline-exceeded`,retriable:!1})},f=async t=>{if(!u)throw new e(`COMMAND_FAILED`,`Managed request is not admitted.`,{reason:`managed-request-not-admitted`});return await d(t)},p=async()=>await f(async()=>{}),m=Object.freeze({device:s.reachability.device,owner:s.owner,fence:s.fence,admit:f,run:s.reachability.run});return{scope:{...a.scope,managedDevice:m},bind:d,activate:()=>{if(l.aborted)throw t();u=!0},ensureReady:p}}export{a as createManagedRequestAdmission};
@@ -1 +1 @@
1
- import{x as e,y as t}from"./sdk-contracts.js";const n=new Set,r=new Map;function i(e,t){if(typeof e==`string`&&e.length>0)return e;let n=(typeof t==`string`?t:typeof t==`number`&&Number.isFinite(t)?String(t):`generated`).trim().replaceAll(/[^a-zA-Z0-9_-]/g,`_`).slice(0,32)||`generated`,r=Math.random().toString(36).slice(2,10);return`req:${n}:${process.pid}:${Date.now()}:${r}`}const a=5e4,o=1e4;function s(e){if(e.size<=a)return;let t=0;for(let n of e.keys()){if(t>=o)break;e.delete(n),t++}}function c(e){if(e.size<=a)return;let t=0;for(let n of e){if(t>=o)break;e.delete(n),t++}}function l(e){if(!e)return;if(r.has(e))throw new t(`INVALID_ARGS`,`Request ID is already in flight: ${e}`,{requestId:e,reason:`duplicate_request_id`});s(r);let i=new AbortController;return r.set(e,i),n.has(e)&&i.abort(),{requestId:e,controller:i}}function u(t){t&&(c(n),n.add(t),r.get(t)?.abort(e()))}function d(e,t){e&&(t&&(t.requestId!==e||r.get(e)!==t.controller)||(n.delete(e),r.delete(e)))}function f(e){e&&d(e.requestId,e)}function p(e){return e?n.has(e):!1}function m(e){if(e)return r.get(e)?.signal}function h(t){if(p(t))throw e()}export{u as a,h as c,p as i,d as n,l as o,m as r,i as s,f as t};
1
+ import{C as e,T as t}from"./sdk-contracts.js";const n=new Set,r=new Map;function i(e,t){if(typeof e==`string`&&e.length>0)return e;let n=(typeof t==`string`?t:typeof t==`number`&&Number.isFinite(t)?String(t):`generated`).trim().replaceAll(/[^a-zA-Z0-9_-]/g,`_`).slice(0,32)||`generated`,r=Math.random().toString(36).slice(2,10);return`req:${n}:${process.pid}:${Date.now()}:${r}`}const a=5e4,o=1e4;function s(e){if(e.size<=a)return;let t=0;for(let n of e.keys()){if(t>=o)break;e.delete(n),t++}}function c(e){if(e.size<=a)return;let t=0;for(let n of e){if(t>=o)break;e.delete(n),t++}}function l(t){if(!t)return;if(r.has(t))throw new e(`INVALID_ARGS`,`Request ID is already in flight: ${t}`,{requestId:t,reason:`duplicate_request_id`});s(r);let i=new AbortController;return r.set(t,i),n.has(t)&&i.abort(),{requestId:t,controller:i}}function u(e){e&&(c(n),n.add(e),r.get(e)?.abort(t()))}function d(e,t){e&&(t&&(t.requestId!==e||r.get(e)!==t.controller)||(n.delete(e),r.delete(e)))}function f(e){e&&d(e.requestId,e)}function p(e){return e?n.has(e):!1}function m(e){if(e)return r.get(e)?.signal}function h(e){if(p(e))throw t()}export{u as a,h as c,p as i,d as n,l as o,m as r,i as s,f as t};
@@ -1 +1 @@
1
- const e=`limrun`,t=e;function n(e){if(e===`ios-instance`)return`ios`;if(e===`android-instance`)return`android`}function r(e,t,n){return{platform:e===`ios`?`apple`:`android`,...e===`ios`?{appleOs:`ios`}:{},id:a(e,t.leaseId),name:`Limrun ${e} ${n.slice(0,8)}`,kind:e===`ios`?`simulator`:`emulator`,target:`mobile`,booted:!0}}function i(e){let[n,r,i]=e.split(`:`);if(n===t&&(r===`ios`||r===`android`)&&i)return{platform:r,leaseId:i}}function a(e,n){return`${t}:${e}:${n}`}function o(e){let t=i(e.id);return!t||e.target!==`mobile`?!1:t.platform===`ios`?s(e):c(e)}function s(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&e.iosPhysicalDeviceBackend===void 0}function c(e){return e.platform===`android`&&e.appleOs===void 0&&e.kind===`emulator`&&e.iosPhysicalDeviceBackend===void 0}async function l(e,t,n=`Limrun provider operation aborted`,r){if(!t)try{return await e}finally{r?.()}return await new Promise((i,a)=>{let o=()=>a(t.reason??Error(n));if(t.aborted){e.then(e=>{r?.(),i(e)},e=>{r?.(),a(e)}),o();return}t.addEventListener(`abort`,o,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,o),r?.(),i(e)},e=>{t.removeEventListener(`abort`,o),r?.(),a(e)})})}function u(){let e=new Set;return{wait:async(t,n,r)=>{let i,a=new Promise(e=>{i=e});return e.add(a),a.then(()=>e.delete(a)),await l(t,n,r,i)},[Symbol.asyncDispose]:async()=>{for(;e.size>0;)await Promise.all(e)}}}async function d(e,t,n,r){return await(e?e.wait(t,n,r):l(t,n,r))}export{r as a,n as c,e as i,l as n,o,u as r,i as s,d as t};
1
+ const e=`limrun`,t=e;function n(e){if(e===`ios-instance`)return`ios`;if(e===`android-instance`)return`android`}function r(e,t,n){return{platform:e===`ios`?`apple`:`android`,...e===`ios`?{appleOs:`ios`}:{},id:a(e,t.leaseId),name:`Limrun ${e} ${n.slice(0,8)}`,kind:e===`ios`?`simulator`:`emulator`,target:`mobile`,booted:!0}}function i(e){let[n,r,i]=e.split(`:`);if(n===t&&(r===`ios`||r===`android`)&&i)return{platform:r,leaseId:i}}function a(e,n){return`${t}:${e}:${n}`}function o(e){let t=i(e.id);return!t||e.target!==`mobile`?!1:t.platform===`ios`?s(e):c(e)}function s(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&e.iosPhysicalDeviceBackend===void 0}function c(e){return e.platform===`android`&&e.appleOs===void 0&&e.kind===`emulator`&&e.iosPhysicalDeviceBackend===void 0}async function l(e,t,n=`Limrun provider operation aborted`,r){if(!t)try{return await e}finally{r?.()}return await new Promise((i,a)=>{let o=()=>a(t.reason??Error(n));if(t.aborted){e.then(e=>{r?.(),i(e)},e=>{r?.(),a(e)}),o();return}t.addEventListener(`abort`,o,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,o),r?.(),i(e)},e=>{t.removeEventListener(`abort`,o),r?.(),a(e)})})}function u(){let e=new Set;return{wait:async(t,n,r)=>{let i,a=new Promise(t=>{i=()=>{e.delete(a),t()}});return e.add(a),await l(t,n,r,i)},[Symbol.asyncDispose]:async()=>{for(;e.size>0;)await Promise.all(e)}}}async function d(e,t,n,r){return await(e?e.wait(t,n,r):l(t,n,r))}export{r as a,n as c,e as i,l as n,o,u as r,i as s,d as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{T as t,l as n,w as r}from"./sdk-device.js";import{Kt as i}from"./sdk-batch.js";import{t as a}from"./ttl-memo.js";import{t as o}from"./platform-runtime-android-mechanics.js";import{r as s}from"./provider-device-runtime.js";import{t as c}from"./async-lifecycle.js";const l=`No active session. Run open first.`;function u(e,t,n,r){return{ok:!1,error:{code:e,message:t,...r?.hint?{hint:r.hint}:{},...r?.retriable===void 0?{}:{retriable:r.retriable},...n?{details:n}:{}}}}function d(){return u(`SESSION_NOT_FOUND`,l)}async function f(e,t={}){if(n(e)){if(e.kind===`simulator`){let{ensureBootedSimulator:n}=await import(`./simulator-facade.js`);return await n(e,{deviceHub:t.deviceHub,focusExisting:t.focusExisting,onColdBootStart:t.onIosSimulatorColdBootStart}),!0}if(e.kind===`device`){let{resolveIosPhysicalDeviceControl:t}=await import(`./physical-device-facade.js`);return await t(e).ensureReady(e),!0}}if(e.platform===`android`){let{waitForAndroidBoot:t}=await o();return await t(e.id),!0}return!1}const p=a({ttlMs:5e3});async function m(e,t={}){if(s(e))return;let n=g(e);if(p.get(n)===!0){if(!t.focusExisting)return;p.delete(n)}await f(e,t)&&h(n)}function h(e){p.set(e,!0)}function g(e){let t=e.kind===`simulator`?e.simulatorSetPath??``:``;return JSON.stringify([e.platform,e.kind,e.id,e.target??``,t])}const _=new WeakMap;async function v(t,n={}){switch(t.owner.kind){case`provider-runtime`:return;case`managed-local`:{let n=_.get(t);if(n){await n();return}throw new e(`UNSUPPORTED_OPERATION`,`Managed-device readiness is unavailable until allocator confirmation.`,{reason:`managed-readiness-unavailable`})}case`local-family`:await m(t.device,n)}}function y(e){let n=new c,a=new AbortController,o=new Map,s=async(t,n)=>(await e.admitDeviceClaim(t.device,t.owner,n),t);return{inspectFacts:async t=>await e.gateway.inspectFacts(t),bindDevice:async(a,c)=>{let l=t(r(a)),u=o.get(l);if(!u){let t={kind:`ordinary`};u=e.gateway.bind({device:a,intent:t,scope:e.scope}).then(e=>n.use(e)).then(e=>s(e,t)),o.set(l,u),u.catch(()=>{o.get(l)===u&&o.delete(l)})}return i(await u,c)},bindExactDevice:async(t,r,o,c,l)=>{let u={kind:`exact-owner`,owner:r,fence:o},d;if(r.kind===`managed-local`){let{createManagedRequestAdmission:n}=await import(`./request-admission.js`);d=n({device:t,intent:u,scope:l,lifetime:a.signal,resolve:e.resolveManagedLease})}d&&await e.admitDeviceClaim(t,r,u);let f=d?await d.bind(()=>e.gateway.bind({device:t,intent:u,scope:d.scope})):await e.gateway.bind({device:t,intent:u,scope:l}),p=await b(n,f,l),m=d?p:await s(p,u),h=i(m,c);return d?.activate(),d&&_.set(h,d.ensureReady),h},[Symbol.asyncDispose]:async()=>{a.abort(),await n[Symbol.asyncDispose]()}}}async function b(e,t,n){try{return e.use(t)}catch(e){try{await t[Symbol.asyncDispose]()}catch(t){n.diagnostics.emit({level:`error`,phase:`request_runtime_late_binding_cleanup_failed`,data:{error:x(t),primaryError:x(e)}})}throw e}}function x(e){return e instanceof Error?e.message:String(e)}export{d as a,u as i,v as n,l as r,y as t};
1
+ import{C as e}from"./sdk-contracts.js";import{T as t,l as n,w as r}from"./sdk-device.js";import{qt as i}from"./sdk-batch.js";import{t as a}from"./ttl-memo.js";import{t as o}from"./platform-runtime-android-mechanics.js";import{t as s}from"./async-lifecycle.js";let c={isActive:()=>!1};function l(e){c=e}function u(e){return c.isActive(e)}const d=`No active session. Run open first.`;function f(e,t,n,r){return{ok:!1,error:{code:e,message:t,...r?.hint?{hint:r.hint}:{},...r?.retriable===void 0?{}:{retriable:r.retriable},...n?{details:n}:{}}}}function p(){return f(`SESSION_NOT_FOUND`,d)}async function m(e,t={}){if(n(e)){if(e.kind===`simulator`){let{ensureBootedSimulator:n}=await import(`./simulator-facade.js`);return await n(e,{deviceHub:t.deviceHub,focusExisting:t.focusExisting,onColdBootStart:t.onIosSimulatorColdBootStart}),!0}if(e.kind===`device`){let{resolveIosPhysicalDeviceControl:t}=await import(`./physical-device-facade.js`);return await t(e).ensureReady(e),!0}}if(e.platform===`android`){let{waitForAndroidBoot:t}=await o();return await t(e.id),!0}return!1}const h=a({ttlMs:5e3});async function g(e,t={}){if(u(e))return;let n=v(e);if(h.get(n)===!0){if(!t.focusExisting)return;h.delete(n)}await m(e,t)&&_(n)}function _(e){h.set(e,!0)}function v(e){let t=e.kind===`simulator`?e.simulatorSetPath??``:``;return JSON.stringify([e.platform,e.kind,e.id,e.target??``,t])}const y=new WeakMap;async function b(t,n={}){switch(t.owner.kind){case`provider-runtime`:return;case`managed-local`:{let n=y.get(t);if(n){await n();return}throw new e(`UNSUPPORTED_OPERATION`,`Managed-device readiness is unavailable until allocator confirmation.`,{reason:`managed-readiness-unavailable`})}case`local-family`:await g(t.device,n)}}function x(e){let n=new s,a=new AbortController,o=new Map,c=async(t,n)=>(await e.admitDeviceClaim(t.device,t.owner,n),t);return{inspectFacts:async t=>await e.gateway.inspectFacts(t),bindDevice:async(a,s)=>{let l=t(r(a)),u=o.get(l);if(!u){let t={kind:`ordinary`};u=e.gateway.bind({device:a,intent:t,scope:e.scope}).then(e=>n.use(e)).then(e=>c(e,t)),o.set(l,u),u.catch(()=>{o.get(l)===u&&o.delete(l)})}return i(await u,s)},bindExactDevice:async(t,r,o,s,l)=>{let u={kind:`exact-owner`,owner:r,fence:o},d;if(r.kind===`managed-local`){let{createManagedRequestAdmission:n}=await import(`./request-admission.js`);d=n({device:t,intent:u,scope:l,lifetime:a.signal,resolve:e.resolveManagedLease})}d&&await e.admitDeviceClaim(t,r,u);let f=d?await d.bind(()=>e.gateway.bind({device:t,intent:u,scope:d.scope})):await e.gateway.bind({device:t,intent:u,scope:l}),p=await S(n,f,l),m=d?p:await c(p,u),h=i(m,s);return d?.activate(),d&&y.set(h,d.ensureReady),h},[Symbol.asyncDispose]:async()=>{a.abort(),await n[Symbol.asyncDispose]()}}}async function S(e,t,n){try{return e.use(t)}catch(e){try{await t[Symbol.asyncDispose]()}catch(t){n.diagnostics.emit({level:`error`,phase:`request_runtime_late_binding_cleanup_failed`,data:{error:C(t),primaryError:C(e)}})}throw e}}function C(e){return e instanceof Error?e.message:String(e)}export{p as a,f as i,b as n,l as o,d as r,u as s,x as t};
package/dist/src/retry.js CHANGED
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{x as t,y as n}from"./sdk-contracts.js";import{r}from"./diagnostics.js";import{t as i}from"./timeouts.js";function a(e){return[`1`,`true`,`yes`,`on`].includes((e??``).trim().toLowerCase())}const o={maxAttempts:3,baseDelayMs:200,maxDelayMs:2e3,jitter:.2};var s=class e{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(t,n=Date.now()){return new e(n,t)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return this.remainingMs(e)<=0}};async function c(e,r={},i={}){let a={maxAttempts:r.maxAttempts??o.maxAttempts,baseDelayMs:r.baseDelayMs??o.baseDelayMs,maxDelayMs:r.maxDelayMs??o.maxDelayMs,jitter:r.jitter??o.jitter,shouldRetry:r.shouldRetry},s=!1,c;for(let n=1;n<=a.maxAttempts;n+=1){if(i.signal?.aborted)throw t();if(i.deadline?.isExpired()&&n>1)break;try{let t=await e({attempt:n,maxAttempts:a.maxAttempts,deadline:i.deadline});return i.onEvent?.({phase:i.phase,event:`succeeded`,attempt:n,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs()}),f({phase:i.phase,event:`succeeded`,attempt:n,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs()}),t}catch(e){c=e;let t=i.classifyReason?.(e),r={phase:i.phase,event:`attempt_failed`,attempt:n,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs(),reason:t};if(i.onEvent?.(r),f(r),n>=a.maxAttempts||a.shouldRetry&&!a.shouldRetry(e,n))break;let o=u(a.baseDelayMs,a.maxDelayMs,a.jitter,n),p=i.deadline?Math.min(o,i.deadline.remainingMs()):o;if(p<=0)break;let m={phase:i.phase,event:`retry_scheduled`,attempt:n,maxAttempts:a.maxAttempts,delayMs:p,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs(),reason:t};i.onEvent?.(m),f(m),i.retryWakeSignal&&!s?s=await l(p,i.signal,i.retryWakeSignal)===`signaled`:await d(p,i.signal)}}let p={phase:i.phase,event:`exhausted`,attempt:a.maxAttempts,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs(),reason:i.classifyReason?.(c)};throw i.onEvent?.(p),f(p),c||new n(`COMMAND_FAILED`,`retry failed`)}function l(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(o),t?.removeEventListener(`abort`,s),n.removeEventListener(`abort`,c),r(e))},o=setTimeout(()=>a(`delay`),e),s=()=>a(`delay`),c=()=>a(`signaled`);if(t?.addEventListener(`abort`,s,{once:!0}),n.addEventListener(`abort`,c,{once:!0}),t?.aborted){a(`delay`);return}n.aborted&&a(`signaled`)})}function u(e,t,n,r){let i=Math.min(t,e*2**(r-1)),a=i*n;return Math.max(0,i+(Math.random()*2-1)*a)}function d(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=!1,i=()=>{r||(r=!0,t&&t.removeEventListener(`abort`,o),n())},a=setTimeout(i,e);function o(){clearTimeout(a),i()}t&&t.addEventListener(`abort`,o,{once:!0})})}function f(e){r({level:e.event===`attempt_failed`||e.event===`exhausted`?`warn`:`debug`,phase:`retry`,data:{...e}})}var p=e({Deadline:()=>s,isEnvTruthy:()=>a,retryWithPolicy:()=>c,sleep:()=>i});export{c as i,s as n,a as r,p as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t,T as n}from"./sdk-contracts.js";import{r}from"./diagnostics.js";import{t as i}from"./timeouts.js";function a(e){return[`1`,`true`,`yes`,`on`].includes((e??``).trim().toLowerCase())}const o={maxAttempts:3,baseDelayMs:200,maxDelayMs:2e3,jitter:.2};var s=class e{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(t,n=Date.now()){return new e(n,t)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return this.remainingMs(e)<=0}};async function c(e,r={},i={}){let a={maxAttempts:r.maxAttempts??o.maxAttempts,baseDelayMs:r.baseDelayMs??o.baseDelayMs,maxDelayMs:r.maxDelayMs??o.maxDelayMs,jitter:r.jitter??o.jitter,shouldRetry:r.shouldRetry},s=!1,c;for(let t=1;t<=a.maxAttempts;t+=1){if(i.signal?.aborted)throw n();if(i.deadline?.isExpired()&&t>1)break;try{let n=await e({attempt:t,maxAttempts:a.maxAttempts,deadline:i.deadline});return i.onEvent?.({phase:i.phase,event:`succeeded`,attempt:t,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs()}),f({phase:i.phase,event:`succeeded`,attempt:t,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs()}),n}catch(e){c=e;let n=i.classifyReason?.(e),r={phase:i.phase,event:`attempt_failed`,attempt:t,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs(),reason:n};if(i.onEvent?.(r),f(r),t>=a.maxAttempts||a.shouldRetry&&!a.shouldRetry(e,t))break;let o=u(a.baseDelayMs,a.maxDelayMs,a.jitter,t),p=i.deadline?Math.min(o,i.deadline.remainingMs()):o;if(p<=0)break;let m={phase:i.phase,event:`retry_scheduled`,attempt:t,maxAttempts:a.maxAttempts,delayMs:p,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs(),reason:n};i.onEvent?.(m),f(m),i.retryWakeSignal&&!s?s=await l(p,i.signal,i.retryWakeSignal)===`signaled`:await d(p,i.signal)}}let p={phase:i.phase,event:`exhausted`,attempt:a.maxAttempts,maxAttempts:a.maxAttempts,elapsedMs:i.deadline?.elapsedMs(),remainingMs:i.deadline?.remainingMs(),reason:i.classifyReason?.(c)};throw i.onEvent?.(p),f(p),c||new t(`COMMAND_FAILED`,`retry failed`)}function l(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(o),t?.removeEventListener(`abort`,s),n.removeEventListener(`abort`,c),r(e))},o=setTimeout(()=>a(`delay`),e),s=()=>a(`delay`),c=()=>a(`signaled`);if(t?.addEventListener(`abort`,s,{once:!0}),n.addEventListener(`abort`,c,{once:!0}),t?.aborted){a(`delay`);return}n.aborted&&a(`signaled`)})}function u(e,t,n,r){let i=Math.min(t,e*2**(r-1)),a=i*n;return Math.max(0,i+(Math.random()*2-1)*a)}function d(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=!1,i=()=>{r||(r=!0,t&&t.removeEventListener(`abort`,o),n())},a=setTimeout(i,e);function o(){clearTimeout(a),i()}t&&t.addEventListener(`abort`,o,{once:!0})})}function f(e){r({level:e.event===`attempt_failed`||e.event===`exhausted`?`warn`:`debug`,phase:`retry`,data:{...e}})}var p=e({Deadline:()=>s,isEnvTruthy:()=>a,retryWithPolicy:()=>c,sleep:()=>i});export{c as i,s as n,a as r,p as t};
@@ -1,2 +1,2 @@
1
- import{y as e}from"./sdk-contracts.js";import{c as t,u as n,y as r}from"./sdk-device.js";import i from"node:path";import a from"node:fs";import o from"node:crypto";import s from"node:os";let c;function l(e){if(c&&c!==e)throw Error(`Apple runner host is already bound to a different implementation.`);c=e}function u(){if(!c)throw Error(`Apple runner host is not bound. Construct the client via createAppleRunnerClient() before using runner operations.`);return c}const d=(e,t,n)=>u().runCmdStreaming(e,t,n),ee=(e,t,n)=>u().runCmdSync(e,t,n),te=(e,t,n)=>u().runCmdBackground(e,t,n),ne=(e,t,n)=>u().requireExecSuccess(e,t,n),re=e=>u().emitDiagnostic(e),ie=(e,t,n)=>u().withDiagnosticTimer(e,t,n),f=(e,t,n)=>u().retryWithPolicy(e,t,n),p=e=>u().isEnvTruthy(e),ae=e=>u().isProcessAlive(e),oe=e=>u().isProcessGroupAlive(e),se=e=>u().readProcessStartTime(e),ce=e=>u().readProcessCommand(e),le=(e,t)=>u().signalPidsBestEffort(e,t),ue=(e,t)=>u().signalProcessGroupBestEffort(e,t),m=()=>u().findProjectRoot(),de=e=>u().readVersion(e),fe=e=>u().acquireProcessLock(e),pe=(e,t,n)=>u().withKeyedLock(e,t,n),me=e=>u().publishFileSync(e),he=e=>u().classifyOwnerLiveness(e),ge=e=>u().createTtlMemo(e),_e=e=>u().parseBooleanLiteral(e),ve=e=>u().isRecord(e),ye=e=>u().resolveIosSimulatorDeviceSetPath(e),be=e=>u().emitRequestProgress(e),xe=e=>u().getRequestSignal(e),Se=e=>u().isRequestCanceled(e),h=e=>u().classifyBootFailure(e),g=e=>u().bootFailureHint(e),_=(e,t,n)=>u().runAppleToolCommand(e,t,n),v=(e,t)=>u().runXcrun(e,t),y=(e,t)=>u().readApplePlistJson(e,t),b=(e,t)=>u().buildSimctlArgsForDevice(e,t),x=e=>u().resolveIosPhysicalDeviceControl(e),S=(e,t)=>u().visitXmlPlistEntries(e,t),C=()=>u().leaseOwnerStateDir(),w=e=>u().hasDeviceClaimAuthority(e),T={fromTimeoutMs(e,t){return u().deadlineFromTimeoutMs(e,t)}},E={iOS:{sdkName:{simulator:`iphonesimulator`,device:`iphoneos`},derivedBaseName:{simulator:`ios-simulator`,device:`ios-device`},xctestrunHints:{simulator:{preferred:[`iphonesimulator`],disallowed:[`iphoneos`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`iphoneos`],disallowed:[`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}},tvOS:{sdkName:{simulator:`appletvsimulator`,device:`appletvos`},derivedBaseName:{simulator:`tvos-simulator`,device:`tvos-device`},xctestrunHints:{simulator:{preferred:[`appletvsimulator`],disallowed:[`appletvos`,`iphoneos`,`iphonesimulator`,`macos`]},device:{preferred:[`appletvos`],disallowed:[`appletvsimulator`,`iphoneos`,`iphonesimulator`,`macos`]}}},macOS:{sdkName:{simulator:`macosx`,device:`macosx`},derivedBaseName:{simulator:`macos`,device:`macos`},xctestrunHints:{simulator:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]},device:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]}}},visionOS:{sdkName:{simulator:`xrsimulator`,device:`xros`},derivedBaseName:{simulator:`visionos-simulator`,device:`visionos-device`},xctestrunHints:{simulator:{preferred:[`xrsimulator`],disallowed:[`xros`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`xros`],disallowed:[`xrsimulator`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}}};function D(i){if(!t(i.platform))throw new e(`UNSUPPORTED_PLATFORM`,`Unsupported platform for Apple runner: ${i.platform}`);return n(i)?`macOS`:r(i.target,i.appleOs)}function O(e,t){return E[e].sdkName[M(t)]}function k(e){return E[D(e)].derivedBaseName[M(e.kind)]}function A(e){return E[D(e)].xctestrunHints[M(e.kind)]}function j(e){let t=D(e);return t===`macOS`?`platform=macOS,arch=${N()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`platform=${t},id=${e.id}`}function Ce(e){let t=D(e);return t===`macOS`?`platform=macOS,arch=${N()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`generic/platform=${t}`}function we(e){let t=D(e);return t===`macOS`?`platform=macOS,arch=${N()}`:e.kind===`simulator`?`generic/platform=${t} Simulator`:`generic/platform=${t}`}function M(e){return e===`simulator`?`simulator`:`device`}function N(){return process.arch===`arm64`?`arm64`:`x86_64`}const Te=i.join(`apple`,`runner`,`AgentDeviceRunner`),Ee=i.join(`dist`,`apple`,`runner`,`AgentDeviceRunner`),De=i.join(`apple`,`snapshot-presentation`),Oe=i.join(`dist`,`apple`,`snapshot-presentation`);function P(e){let t=i.join(e,Te);return a.existsSync(t)?t:i.join(e,Ee)}function F(e){return i.join(P(e),`AgentDeviceRunner.xcodeproj`)}function ke(e){let t=i.join(e,De);return a.existsSync(t)?t:i.join(e,Oe)}const Ae=new Set([`.build`,`.swiftpm`,`xcuserdata`]),je=new Set([`.build`,`.swiftpm`,`SnapshotPresentationConformance`,`Tests`,`xcuserdata`]),I=new Map;function Me(e){let t=[{path:P(e),ignoredDirectoryNames:Ae},{path:ke(e),ignoredDirectoryNames:je}],n=Pe(t),r=Ne(e,n),s=JSON.stringify(t.map(({path:e})=>e)),c=I.get(s);if(c?.fileStatsFingerprint===r)return c.sourceFingerprint;let l=o.createHash(`sha256`);for(let t of n){let n=i.relative(e,t);l.update(n),l.update(`\0`),l.update(a.readFileSync(t)),l.update(`\0`)}let u=l.digest(`hex`);return I.set(s,{fileStatsFingerprint:r,sourceFingerprint:u}),u}function Ne(e,t){let n=o.createHash(`sha256`);for(let r of t){let t=i.relative(e,r),o=a.statSync(r);n.update(t),n.update(`\0`),n.update(String(o.size)),n.update(`\0`),n.update(String(Math.trunc(o.mtimeMs))),n.update(`\0`)}return n.digest(`hex`)}function Pe(e){return[...new Set(e.flatMap(({path:e,ignoredDirectoryNames:t})=>Fe(e,t)))].sort((e,t)=>e.localeCompare(t))}function Fe(e,t){return a.existsSync(e)?L(e,t):[]}function L(e,t){let n=[];for(let r of a.readdirSync(e,{withFileTypes:!0})){let a=i.join(e,r.name);r.isDirectory()?t.has(r.name)||n.push(...L(a,t)):r.isFile()&&Ie(r.name,a)&&n.push(a)}return n}function Ie(e,t){return e===`project.pbxproj`?t.includes(`${i.sep}.xcodeproj${i.sep}`):[`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`].includes(i.extname(e))}const Le=i.join(s.homedir(),`.agent-device`,`apple-runner`),Re=`.agent-device-runner-cache.json`,ze=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`];function R(e){return e?.trim()??``}function z(e=process.env){return R(e.AGENT_DEVICE_IOS_BUNDLE_ID)||R(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function B(e=process.env){return R(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${z(e)}.uitests`}function Be(e=process.env){let t=z(e),n=B(e);return Array.from(new Set([R(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}const Ve=Be(process.env);function He(e,t=m()){let n=D(e);return{schemaVersion:2,packageVersion:de(t),runnerSourceFingerprint:Me(t),...Ue(O(n,e.kind)),platformName:n,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:we(e),runnerBundleBuildSettings:Z(process.env),runnerSigningBuildSettings:X(process.env,e.kind===`device`,e),runnerPerformanceBuildSettings:Q(),runnerSandboxBuildArgs:$()}}let V;function H(){return V??=ge(),V}function Ue(e){let t=H().get(e);if(t)return t;let n=We(e);if(!n.ok)throw Ge(n.failures);return H().set(e,n.value),n.value}function We(e){let t=Ke(U(`xcodebuild`,[`-version`])),n=U(`xcrun`,[`--sdk`,e,`--show-sdk-version`]),r=U(`xcrun`,[`--sdk`,e,`--show-sdk-build-version`]);return!t.ok||!n.ok||!r.ok?{ok:!1,failures:[t,n,r].flatMap(e=>e.ok?[]:[e.failure])}:{ok:!0,value:{xcodeVersion:t.value.version,xcodeBuildVersion:t.value.buildVersion,sdkName:e,sdkVersion:n.value,sdkBuildVersion:r.value}}}function Ge(t){return new e(`COMMAND_FAILED`,`Could not read the Xcode toolchain versions the Apple runner cache is keyed on (${t.map(e=>`${e.probe}: ${e.detail}`).join(`; `)})`,{reason:`apple_toolchain_probe_unavailable`,retriable:!0,probes:t,hint:"The Apple runner cache is keyed on the toolchain version, so a cache decision cannot be made without it. Retry once the host is less loaded, or check `xcode-select -p` and `xcodebuild -version`."})}function U(e,t){let n=[e,...t].join(` `),r;try{r=ee(e,t,{allowFailure:!0,timeoutMs:5e3,maxBuffer:131072})}catch(e){return W(n,`probe_error`,e instanceof Error?e.message:`${e}`)}if(r.exitCode!==0)return W(n,`nonzero_exit`,`exit ${r.exitCode}${r.stderr.trim()?`: ${r.stderr.trim()}`:``}`);let i=r.stdout.trim();return i?{ok:!0,value:i}:W(n,`empty_output`,`no output`)}function Ke(e){if(!e.ok)return e;let t=e.value.match(/^Xcode\s+(.+)$/m)?.[1]?.trim(),n=e.value.match(/^Build version\s+(.+)$/m)?.[1]?.trim();return!t||!n?W(`xcodebuild -version`,`unparsable_output`,`unrecognized output: ${e.value.replaceAll(`
2
- `,` `)}`):{ok:!0,value:{version:t,buildVersion:n}}}function W(e,t,n){return{ok:!1,failure:{probe:e,reason:t,detail:n.length>200?`${n.slice(0,200)}…`:n}}}function qe(e,t){let n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(n)return i.resolve(n);let r=Ye(t),a=Je(e);return i.join(a,r)}function Je(e){return i.join(Le,`derived`,k(e))}function Ye(e){return`cache-${o.createHash(`sha256`).update(J(G(e))).digest(`hex`).slice(0,16)}`}function G(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function Xe(e,t){let n=G(e),r=G(t);return[...new Set([...Object.keys(n),...Object.keys(r)])].sort((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=K(n[e]),i=K(r[e]);return t===i?[]:[{key:e,expected:q(t),actual:q(i)}]})}function K(e){return e===void 0?`(absent)`:J(e)}function q(e){return e.length<=300?e:`${e.slice(0,149)}…${e.slice(-149)}`}function J(e){return JSON.stringify(Y(e))}function Y(e){return Array.isArray(e)?e.map(e=>Y(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Y(t)]))}function Ze(e){return n(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function X(e=process.env,t=!1,r={platform:`apple`}){if(n(r))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let i=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,a=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,o=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,s=[`CODE_SIGN_STYLE=${o?`Manual`:`Automatic`}`];return i&&s.push(`DEVELOPMENT_TEAM=${i}`),a&&s.push(`CODE_SIGN_IDENTITY=${a}`),o&&s.push(`PROVISIONING_PROFILE_SPECIFIER=${o}`),s}function Z(e=process.env){let t=z(e),n=B(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function Q(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function $(){return[...ze,`OTHER_SWIFT_FLAGS=${Qe(process.env)}`]}function Qe(e){return p(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_UNIT_TESTS`:`$(inherited) -disable-sandbox`}export{pe as $,p as A,se as B,h as C,m as D,be as E,C as F,_ as G,x as H,_e as I,v as J,te as K,me as L,oe as M,ve as N,xe as O,Se as P,ie as Q,y as R,b as S,re as T,ye as U,ne as V,f as W,ue as X,le as Y,S as Z,A as _,He as a,l as b,qe as c,$ as d,X as f,j as g,Ce as h,Xe as i,ae as j,w as k,Ze as l,F as m,Re as n,z as o,J as p,d as q,G as r,Z as s,Ve as t,Q as u,T as v,he as w,g as x,fe as y,ce as z};
1
+ import{A as e,C as t,T as n}from"./sdk-contracts.js";import{u as r}from"./sdk-device.js";import{i,o as a,r as o,s,t as c}from"./apple-runner-platform.js";import l from"node:path";import u from"node:fs";import d from"node:crypto";import ee from"node:os";let f;function te(e){if(f&&f!==e)throw Error(`Apple runner host is already bound to a different implementation.`);f=e}function p(){if(!f)throw Error(`Apple runner host is not bound. Construct the client via createAppleRunnerClient() before using runner operations.`);return f}const ne=(e,t,n)=>p().runCmdStreaming(e,t,n),re=(e,t,n)=>p().runCmdSync(e,t,n),ie=(e,t,n)=>p().runCmdBackground(e,t,n),ae=(e,t,n)=>p().requireExecSuccess(e,t,n),oe=e=>p().isCommandTimeoutError(e),se=e=>p().emitDiagnostic(e),ce=(e,t,n)=>p().withDiagnosticTimer(e,t,n),le=(e,t,n)=>p().retryWithPolicy(e,t,n),m=e=>p().isEnvTruthy(e),ue=e=>p().isProcessAlive(e),de=e=>p().isProcessGroupAlive(e),fe=e=>p().readProcessStartTime(e),pe=e=>p().readProcessCommand(e),me=(e,t)=>p().signalPidsBestEffort(e,t),he=(e,t)=>p().signalProcessGroupBestEffort(e,t),h=()=>p().findProjectRoot(),ge=e=>p().readVersion(e),_e=e=>p().acquireProcessLock(e),ve=(e,t,n)=>p().withKeyedLock(e,t,n),ye=e=>p().publishFileSync(e),be=e=>p().classifyOwnerLiveness(e),xe=e=>p().createTtlMemo(e),Se=e=>p().parseBooleanLiteral(e),g=e=>p().isRecord(e),_=e=>p().resolveIosSimulatorDeviceSetPath(e),v=e=>p().emitRequestProgress(e),y=e=>p().getRequestSignal(e),b=e=>p().isRequestCanceled(e),x=e=>p().classifyBootFailure(e),S=e=>p().bootFailureHint(e),C=(e,t,n)=>p().runAppleToolCommand(e,t,n),w=(e,t)=>p().runXcrun(e,t),T=(e,t)=>p().readApplePlistJson(e,t),E=(e,t)=>p().buildSimctlArgsForDevice(e,t),D=e=>p().resolveIosPhysicalDeviceControl(e),O=(e,t)=>p().visitXmlPlistEntries(e,t),k=()=>p().leaseOwnerStateDir(),A=e=>p().hasDeviceClaimAuthority(e),j={fromTimeoutMs(e,t){return p().deadlineFromTimeoutMs(e,t)}},Ce=l.join(`apple`,`runner`,`AgentDeviceRunner`),we=l.join(`dist`,`apple`,`runner`,`AgentDeviceRunner`),Te=l.join(`apple`,`snapshot-presentation`),Ee=l.join(`dist`,`apple`,`snapshot-presentation`);function M(e){let t=l.join(e,Ce);return u.existsSync(t)?t:l.join(e,we)}function De(e){return l.join(M(e),`AgentDeviceRunner.xcodeproj`)}function Oe(e){let t=l.join(e,Te);return u.existsSync(t)?t:l.join(e,Ee)}const ke=new Set([`.build`,`.swiftpm`,`xcuserdata`]),Ae=new Set([`.build`,`.swiftpm`,`SnapshotPresentationConformance`,`Tests`,`xcuserdata`]),N=new Map;function je(e){let t=[{path:M(e),ignoredDirectoryNames:ke},{path:Oe(e),ignoredDirectoryNames:Ae}],n=Ne(t),r=Me(e,n),i=JSON.stringify(t.map(({path:e})=>e)),a=N.get(i);if(a?.fileStatsFingerprint===r)return a.sourceFingerprint;let o=d.createHash(`sha256`);for(let t of n){let n=l.relative(e,t);o.update(n),o.update(`\0`),o.update(u.readFileSync(t)),o.update(`\0`)}let s=o.digest(`hex`);return N.set(i,{fileStatsFingerprint:r,sourceFingerprint:s}),s}function Me(e,t){let n=d.createHash(`sha256`);for(let r of t){let t=l.relative(e,r),i=u.statSync(r);n.update(t),n.update(`\0`),n.update(String(i.size)),n.update(`\0`),n.update(String(Math.trunc(i.mtimeMs))),n.update(`\0`)}return n.digest(`hex`)}function Ne(e){return[...new Set(e.flatMap(({path:e,ignoredDirectoryNames:t})=>Pe(e,t)))].sort((e,t)=>e.localeCompare(t))}function Pe(e,t){return u.existsSync(e)?P(e,t):[]}function P(e,t){let n=[];for(let r of u.readdirSync(e,{withFileTypes:!0})){let i=l.join(e,r.name);r.isDirectory()?t.has(r.name)||n.push(...P(i,t)):r.isFile()&&F(r.name,i)&&n.push(i)}return n}function F(e,t){return e===`project.pbxproj`?t.includes(`${l.sep}.xcodeproj${l.sep}`):[`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`].includes(l.extname(e))}const Fe=l.join(ee.homedir(),`.agent-device`,`apple-runner`),Ie=`.agent-device-runner-cache.json`,Le=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`];function Re(e,t){return{deadline:e!==void 0&&Number.isFinite(e)?j.fromTimeoutMs(Math.max(0,e)):void 0,signal:t}}function ze(e,t){let n=e?.deadline;if(!n)return;let r=Math.floor(n.remainingMs());if(r<=0)throw I(t);return r}function I(e){return new t(`COMMAND_FAILED`,`The Apple runner budget ran out before this step began`,{phase:e,reason:`runner_phase_budget_exhausted`,retriable:!0})}function Be(e){let t=e?.deadline,r=j.fromTimeoutMs(Math.min(45e3,t?t.remainingMs():1/0));return{attemptTimeoutMs:()=>Math.min(c,Math.floor(r.remainingMs())),throwIfCanceled:()=>{if(e?.signal?.aborted)throw n({phase:`apple_toolchain_probe`})}}}function L(e){return e?.trim()??``}function R(e=process.env){return L(e.AGENT_DEVICE_IOS_BUNDLE_ID)||L(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function z(e=process.env){return L(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${R(e)}.uitests`}function Ve(e=process.env){let t=R(e),n=z(e);return Array.from(new Set([L(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}const He=Ve(process.env);function Ue(e,t=h(),n){let r=a(e);return{schemaVersion:2,packageVersion:ge(t),runnerSourceFingerprint:je(t),...We(s(r,e.kind),n),platformName:r,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:o(e),runnerBundleBuildSettings:Z(process.env),runnerSigningBuildSettings:X(process.env,e.kind===`device`,e),runnerPerformanceBuildSettings:Q(),runnerSandboxBuildArgs:$()}}let B;function V(){return B??=xe(),B}function We(e,t){let n=Be(t);n.throwIfCanceled();let r=V().get(e);if(r)return r;let i=Ge(e,n);if(!i.ok)throw Ke(i.failures);return V().set(e,i.value),i.value}function Ge(e,t){let n=Ye(H(`xcodebuild`,[`-version`],t)),r=H(`xcrun`,[`--sdk`,e,`--show-sdk-version`],t),i=H(`xcrun`,[`--sdk`,e,`--show-sdk-build-version`],t);return!n.ok||!r.ok||!i.ok?{ok:!1,failures:[n,r,i].flatMap(e=>e.ok?[]:[e.failure])}:{ok:!0,value:{xcodeVersion:n.value.version,xcodeBuildVersion:n.value.buildVersion,sdkName:e,sdkVersion:r.value,sdkBuildVersion:i.value}}}function Ke(e){return new t(`COMMAND_FAILED`,`Could not read the Xcode toolchain versions the Apple runner cache is keyed on (${e.map(e=>`${e.probe}: ${e.detail}`).join(`; `)})`,{reason:`apple_toolchain_probe_unavailable`,retriable:!0,probes:e,hint:"The Apple runner cache is keyed on the toolchain version, so a cache decision cannot be made without it. Retry once the host is less loaded, or check `xcode-select -p` and `xcodebuild -version`."})}function H(t,n,r){let i=[t,...n].join(` `),a;try{a=qe(t,n,r)}catch(t){if(r.throwIfCanceled(),e(t)||Je(t))throw t;return W(i,`probe_error`,t instanceof Error?t.message:`${t}`)}if(a.exitCode!==0)return W(i,`nonzero_exit`,`exit ${a.exitCode}${a.stderr.trim()?`: ${a.stderr.trim()}`:``}`);let o=a.stdout.trim();return o?{ok:!0,value:o}:W(i,`empty_output`,`no output`)}function qe(e,t,n){try{return U(e,t,n)}catch(r){if(!oe(r))throw r;return U(e,t,n)}}function U(e,t,n){n.throwIfCanceled();let r=n.attemptTimeoutMs();if(r<=0)throw I(`apple_toolchain_probe`);return re(e,t,{allowFailure:!0,timeoutMs:r,maxBuffer:131072})}function Je(e){return e instanceof t&&e.details?.reason===`runner_phase_budget_exhausted`}function Ye(e){if(!e.ok)return e;let t=e.value.match(/^Xcode\s+(.+)$/m)?.[1]?.trim(),n=e.value.match(/^Build version\s+(.+)$/m)?.[1]?.trim();return!t||!n?W(`xcodebuild -version`,`unparsable_output`,`unrecognized output: ${e.value.replaceAll(`
2
+ `,` `)}`):{ok:!0,value:{version:t,buildVersion:n}}}function W(e,t,n){return{ok:!1,failure:{probe:e,reason:t,detail:n.length>200?`${n.slice(0,200)}…`:n}}}function Xe(e,t){let n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(n)return l.resolve(n);let r=Qe(t),i=Ze(e);return l.join(i,r)}function Ze(e){return l.join(Fe,`derived`,i(e))}function Qe(e){return`cache-${d.createHash(`sha256`).update(J(G(e))).digest(`hex`).slice(0,16)}`}function G(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function $e(e,t){let n=G(e),r=G(t);return[...new Set([...Object.keys(n),...Object.keys(r)])].sort((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=K(n[e]),i=K(r[e]);return t===i?[]:[{key:e,expected:q(t),actual:q(i)}]})}function K(e){return e===void 0?`(absent)`:J(e)}function q(e){return e.length<=300?e:`${e.slice(0,149)}…${e.slice(-149)}`}function J(e){return JSON.stringify(Y(e))}function Y(e){return Array.isArray(e)?e.map(e=>Y(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Y(t)]))}function et(e){return r(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function X(e=process.env,t=!1,n={platform:`apple`}){if(r(n))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let i=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,a=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,o=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,s=[`CODE_SIGN_STYLE=${o?`Manual`:`Automatic`}`];return i&&s.push(`DEVELOPMENT_TEAM=${i}`),a&&s.push(`CODE_SIGN_IDENTITY=${a}`),o&&s.push(`PROVISIONING_PROFILE_SPECIFIER=${o}`),s}function Z(e=process.env){let t=R(e),n=z(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function Q(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function $(){return[...Le,`OTHER_SWIFT_FLAGS=${tt(process.env)}`]}function tt(e){return m(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_UNIT_TESTS`:`$(inherited) -disable-sandbox`}export{ue as A,ae as B,be as C,y as D,h as E,Se as F,ie as G,_ as H,ye as I,me as J,ne as K,T as L,g as M,b as N,A as O,k as P,ve as Q,pe as R,x as S,v as T,le as U,D as V,C as W,O as X,he as Y,ce as Z,j as _,$e as a,S as b,R as c,et as d,Q as f,De as g,J as h,Re as i,de as j,m as k,Z as l,X as m,Ie as n,ze as o,$ as p,w as q,G as r,Ue as s,He as t,Xe as u,_e as v,se as w,E as x,te as y,fe as z};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{E as t,P as n,b as r,x as i,y as a}from"./sdk-contracts.js";import{g as o}from"./sdk-batch-runner.js";import{c as s,l as c}from"./sdk-device.js";import{o as l}from"./sdk-remote-config.js";import{i as u}from"./alert-contract.js";import{c as d,r as f}from"./diagnostics.js";import{D as p,S as m,b as h,m as ee,p as te,t as ne,x as re,y as ie}from"./owner-identity.js";import{c as ae,d as oe,f as se,i as ce}from"./exec.js";import{t as le}from"./file.js";import"./diagnostics2.js";import"./command.js";import{i as ue,n as de,r as fe}from"./retry.js";import{n as pe,r as me}from"./version.js";import{t as he}from"./ttl-memo.js";import"./process.js";import{n as ge,t as _e}from"./boot-diagnostics.js";import{t as ve}from"./keyed-lock.js";import{i as ye,r as be}from"./request-cancel.js";import{t as xe}from"./request.js";import{r as Se}from"./device-isolation.js";import{a as Ce,o as we,r as Te}from"./tool-provider.js";import{t as Ee}from"./physical-device-control.js";import{t as De}from"./simctl.js";import{a as Oe,i as ke,o as Ae}from"./runner.js";import{$ as je,E as Me,G as g,I as Ne,J as Pe,K as Fe,Q as Ie,S as Le,T as _,U as Re,V as ze,W as Be,a as Ve,b as He,c as Ue,g as We,j as v,l as Ge,o as Ke,t as qe,v as Je}from"./runner-cache-metadata.js";import{A as y,C as Ye,D as b,E as Xe,F as Ze,M as Qe,N as x,O as S,P as $e,S as et,T as tt,_ as C,a as w,b as nt,c as rt,d as it,f as at,g as ot,h as T,i as st,j as ct,k as lt,l as ut,m as dt,n as ft,o as pt,p as mt,r as ht,t as E,u as gt,v as _t,w as vt,x as yt,y as bt}from"./runner-disposal.js";import{t as xt}from"./plist-xml.js";import{n as St,t as Ct}from"./runner-owner-state.js";import D from"node:path";import wt from"node:fs";import Tt from"node:fs/promises";const Et={PreferredScreenCaptureFormat:`screenshots`,SystemAttachmentLifetime:`keepNever`,UserAttachmentLifetime:`keepNever`};async function Dt(e,t,n,r={}){let i=r.iosXctestEnvDir?.trim(),a=i?D.resolve(i):D.dirname(e);wt.mkdirSync(a,{recursive:!0});let o=n.replaceAll(/[^a-zA-Z0-9._-]/g,`_`),s=D.join(a,`AgentDeviceRunner.env.${o}.json`),c=D.join(a,`AgentDeviceRunner.env.${o}.xctestrun`),l=await Ot(e);return Mt(l,e=>At(e,t)),jt(l),await kt(l,s,c),{xctestrunPath:c,jsonPath:s}}async function Ot(e){let t=await g(`plutil`,[`-convert`,`json`,`-o`,`-`,e],{allowFailure:!0});if(t.exitCode!==0||!t.stdout.trim())throw new a(`COMMAND_FAILED`,`Failed to read xctestrun plist`,{xctestrunPath:e,stderr:t.stderr});try{let e=JSON.parse(t.stdout);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Root must be an object`);return e}catch(t){throw new a(`COMMAND_FAILED`,`Failed to parse xctestrun JSON`,{xctestrunPath:e,error:String(t)})}}async function kt(e,t,n){wt.writeFileSync(t,JSON.stringify(e,null,2)),ze(await g(`plutil`,[`-convert`,`xml1`,`-o`,n,t],{allowFailure:!0}),`Failed to write xctestrun plist`,{tmpXctestrunPath:n})}function At(e,t){e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}}function jt(e){Mt(e,e=>Object.assign(e,Et),{requireTestBundlePath:!0})}function Mt(e,t,n={}){let r=e.TestConfigurations;if(Array.isArray(r))for(let e of r)!e||typeof e!=`object`||Nt(e.TestTargets,t,n);for(let n of Object.values(e)){let e=Pt(n,{requireTestBundlePath:!0});e&&t(e)}}function Nt(e,t,n){if(Array.isArray(e))for(let r of e){let e=Pt(r,n);e&&t(e)}}function Pt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return t.requireTestBundlePath&&!n.TestBundlePath?null:n}const Ft={tap:`preflightSkippableTouchMutation`,mouseClick:`default`,longPress:`preflightSkippableTouchMutation`,drag:`preflightSkippableTouchMutation`,remotePress:`default`,type:`default`,swipe:`preflightSkippableTouchMutation`,scroll:`preflightSkippableTouchMutation`,desktopScroll:`preflightSkippableTouchMutation`,findText:`readOnly`,querySelector:`readOnly`,readText:`readOnly`,snapshot:`readOnly`,screenshot:`readOnly`,back:`default`,backInApp:`default`,backSystem:`default`,home:`default`,rotate:`default`,gesture:`preflightSkippableTouchMutation`,gestureViewport:`readOnly`,appSwitcher:`default`,keyboardDismiss:`default`,keyboardReturn:`default`,alert:`alertAction`,sequence:`preflightSkippableTouchMutation`,recordStart:`default`,recordStop:`default`,status:`readOnlyReadinessProbe`,uptime:`readOnlyReadinessProbe`,activate:`readinessPreflightExemptMutation`,terminate:`readinessPreflightExemptMutation`,targetReset:`readinessPreflightExemptMutation`,shutdown:`default`},O={readOnly:!1,readinessProbe:!1,readinessPreflightExempt:!1,readinessPreflightSkipEligibleAfterHealthyMutation:!1},It={...O,readinessPreflightExempt:!0},k={...O,readOnly:!0},Lt={...k,readinessProbe:!0},Rt={...O,readinessPreflightSkipEligibleAfterHealthyMutation:!0};function A(e){return j(e).readOnly}function zt(e){return j(e).readinessProbe}function Bt(e){return j(e).readinessPreflightExempt}function Vt(e){return j(e).readinessPreflightSkipEligibleAfterHealthyMutation}function j(e){switch(Ft[e.command]){case`default`:return O;case`readinessPreflightExemptMutation`:return It;case`readOnly`:return k;case`alertAction`:return(e.action??`get`).toLowerCase()===`get`?k:O;case`readOnlyReadinessProbe`:return Lt;case`preflightSkippableTouchMutation`:return Rt}}function Ht(e,t){return`${e}:${t}:${Date.now()}`}function Ut(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function Wt(e=process.env){return Ne(e.AGENT_DEVICE_IOS_RUNNER_DETACH??``)!==!1}async function Gt(e,t){if(e.kind!==`simulator`||!Wt()||Re(e.simulatorSetPath))return null;let n=mt(e.id);if(!n)return null;let r=t=>(_({level:`debug`,phase:`ios_runner_lease_adoption_skipped`,data:{deviceId:e.id,runnerPid:n.runnerPid,port:n.port,reason:t}}),null);if(t.expectedRunnerSessionId!==void 0&&n.sessionId!==t.expectedRunnerSessionId)return r(`session_identity_mismatch`);let i=n.runnerPid;if(!i)return r(`runner_pid_missing`);if(!v(i))return r(`runner_process_dead`);if(!T(n,i))return r(`runner_pid_recycled`);let a=qt(e);if(!a)return r(`expected_derived_unresolved`);if(!n.xctestrunPath.startsWith(`${a}${D.sep}`))return r(`artifact_fingerprint_mismatch`);if(!await Kt(e,n.port))return r(`probe_failed`);if(!v(i)||!T(n,i))return r(`runner_pid_recycled`);let o=Jt(e,n,i,a,t);try{C(o.lease)}catch{return null}return _({level:`info`,phase:`ios_runner_lease_adopted`,data:{deviceId:e.id,sessionId:o.sessionId,runnerPid:i,port:n.port,previousOwnerPid:n.ownerPid}}),o}async function Kt(e,t){try{let n=await Xe(e,t,x({command:`uptime`}),500);return JSON.parse(await n.text())?.ok===!0}catch{return!1}}function qt(e){try{return Ue(e,Ve(e))}catch{return null}}function Jt(e,t,n,r,i){let a=t.sessionId,o={xctestrunPath:t.xctestrunPath,derived:r,cache:`exact`,artifact:`valid`,buildMs:0,xctestrunPathSource:`manifest`,reason:`adopted_from_lease`},{child:s,wait:c}=Yt(n);return{sessionId:a,device:e,deviceId:e.id,port:t.port,xctestrunPath:t.xctestrunPath,xctestrunArtifact:o,jsonPath:t.jsonPath,testPromise:c,child:s,ready:!0,startupTimeoutMs:Ut(i.startupTimeoutMs),lease:gt({deviceId:e.id,sessionId:a,runnerPid:n,port:t.port,xctestrunPath:t.xctestrunPath,jsonPath:t.jsonPath})}}function Yt(e){let t={pid:e,exitCode:null};return{child:t,wait:new Promise(n=>{let r=setInterval(()=>{v(e)||(clearInterval(r),t.exitCode=-1,n({stdout:``,stderr:``,exitCode:-1}))},1e3);r.unref?.()})}}async function Xt(e){let t=await Zt(e.logPath)??$t(e.error);return t?new a(t.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${t.hint}`:t.hint,runnerFailureReason:t.reason},e.error):e.error}async function Zt(e){if(!e)return;let t=await rn(e,65536);if(t)return Qt(t)}function Qt(e){let t=e.toLowerCase();if(en(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(tn(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function $t(e){if(nn(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function en(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function tn(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function nn(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function rn(e,t){let n;try{let r=await Tt.stat(e),i=Math.max(0,r.size-t),a=r.size-i;if(a<=0)return;n=await Tt.open(e,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}function an(){let e=new AbortController,t=!1,n={stdout:``,stderr:``};return{wake:e.signal,observe:(r,i)=>{if(t)return;let a=n[r]+i;if(a.includes(`AGENT_DEVICE_RUNNER_LISTENER_READY`)){t=!0,n.stdout=``,n.stderr=``,e.abort();return}n[r]=a.slice(-33)},finish:()=>{t=!0,n.stdout=``,n.stderr=``,e.abort()}}}function on(e){let t=an(),n=Fe(`xcodebuild`,[`test-without-building`,`-only-testing`,`AgentDeviceRunnerUITests/RunnerTests/testCommand`,`-parallel-testing-enabled`,`NO`,`-test-timeouts-enabled`,`NO`,`-collect-test-diagnostics`,`never`,Ge(e.device),`1`,`-destination-timeout`,`20`,`-xctestrun`,e.xctestrunPath,`-derivedDataPath`,e.derivedPath,`-destination`,We(e.device)],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(e.port)},detached:!0,signal:e.signal}),r=(n,r)=>{t.observe(n,r),Ze(r,e.logPath,e.traceLogPath,e.verbose)};return n.child.stdout?.on(`data`,e=>r(`stdout`,e)),n.child.stderr?.on(`data`,e=>r(`stderr`,e)),n.wait.then(t.finish,t.finish),{...n,startupRetryWake:t.wake}}const M=new Map,sn=new Map,N=new Map,cn=1e4;function P(e,t){return je(sn,e,t)}async function F(e,t){return z(e.id),await P(e.id,async()=>{let n=M.get(e.id);if(n){un(n,t.expectedRunnerSessionId);let r=await pn(e,n);if(r)return r}return await ot(e.id,async()=>await ln(e,t))})}async function ln(e,t){let n={},r=y(t),a=qn(t.runnerLeaseContext,e.id);_({level:`debug`,phase:`ios_runner_session_startup`,data:{deviceId:e.id,logicalLeaseContext:a}});let o=await H(n,`adopt_detached_runner`,async()=>await Gt(e,{startupTimeoutMs:t.startupTimeoutMs,expectedRunnerSessionId:t.expectedRunnerSessionId}));if(o)return o.startupTimings=n,o.logicalLeaseContext=a,M.set(e.id,o),o;dn(t.expectedRunnerSessionId),await H(n,`cleanup_stale_xcodebuild`,async()=>{await at(e,pt,a)}),await H(n,`ensure_booted`,async()=>{await wn(e)}),await H(n,`verify_developer_mode`,async()=>{await En(e)}),t.cleanStaleBundles?await H(n,`cleanup_stale_bundles`,async()=>{await mn(e)}):(n.cleanup_stale_bundles=0,_({level:`debug`,phase:`ios_runner_startup_cleanup_stale_bundles_skipped`}));let s=await H(n,`ensure_xctestrun`,async()=>await _t(e,{...t,signal:r}));n.build_xctestrun=s.buildMs;let c=await H(n,`allocate_port`,async()=>await $e()),{xctestrunPath:l,jsonPath:u}=await H(n,`prepare_xctestrun_env`,async()=>await Dt(s.xctestrunPath,{AGENT_DEVICE_RUNNER_PORT:String(c)},`session-${e.id}-${dt()}-${c}`,{iosXctestEnvDir:t.iosXctestEnvDir})),d=await H(n,`simulator_set_redirect`,async()=>await et(e)),f;try{s.buildMs>0&&Me({type:`command`,status:`progress`,message:`Starting XCTest runner...`}),f=await H(n,`launch_xcodebuild`,()=>on({device:e,port:c,xctestrunPath:l,derivedPath:s.derived,signal:r,logPath:t.logPath,traceLogPath:t.traceLogPath,verbose:t.verbose}))}catch(e){throw await d?.release(),e}let p=Ht(e.id,c),m=gt({deviceId:e.id,sessionId:p,runnerPid:f.child.pid,port:c,xctestrunPath:l,jsonPath:u}),h={sessionId:p,device:e,deviceId:e.id,port:c,xctestrunPath:l,xctestrunArtifact:s,jsonPath:u,testPromise:f.wait,child:f.child,ready:!1,startupRetryWake:f.startupRetryWake,startupTimeoutMs:Ut(t.startupTimeoutMs),startupTimings:n,logicalLeaseContext:a,simulatorSetRedirect:d??void 0,lease:m,speculative:t.speculative===!0};if(r?.aborted)throw await st(h,{graceful:!1,waitTimeoutMs:E,leaseLockHeld:!0}),i();try{C(m)}catch(t){throw await R(e.id,h,{graceful:!1,waitTimeoutMs:E,leaseLockHeld:!0}),t}return M.set(e.id,h),h}function un(e,t){if(t!==void 0&&e.sessionId!==t)throw fn()}function dn(e){if(e!==void 0)throw fn()}function fn(){return new a(`COMMAND_FAILED`,`Apple runner session ownership changed before command dispatch`,{reason:`runner_session_ownership_changed`})}async function pn(e,t){if(!w(t.child.pid))return await H({},`stop_stale_session`,async()=>{await R(e.id,t,{graceful:!1,waitTimeoutMs:E})}),null;let n=t.xctestrunArtifact;if(n?.cache===`external`)return _({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,cache:n.cache,logicalLeaseContext:t.logicalLeaseContext}}),t;let r=Ue(e,Ve(e));return n?.derived===r?(_({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,logicalLeaseContext:t.logicalLeaseContext}}),t):(_({level:`debug`,phase:`ios_runner_session_artifact_stale`,data:{deviceId:e.id,sessionId:t.sessionId,currentDerived:n?.derived,expectedDerived:r}}),await H({},`stop_stale_artifact_session`,async()=>{await R(e.id,t)}),null)}async function mn(e){e.kind===`simulator`&&await Promise.allSettled(qe.map(async t=>{let n=await hn(e,t);!n||gn(n)}))}async function hn(e,t){try{return await Pe(Le(e,[`uninstall`,e.id,t]),{allowFailure:!0,timeoutMs:cn})}catch(n){_({level:`warn`,phase:`ios_runner_startup_cleanup_stale_bundle_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:cn,error:n instanceof Error?n.message:String(n)}});return}}function gn(e){if(e.exitCode===0)return!0;let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`not installed`)||t.includes(`found nothing`)||t.includes(`no such file`)||t.includes(`invalid device`)||t.includes(`could not find`)}function I(e){let t=M.get(e);return t?{sessionId:t.sessionId,alive:w(t.child.pid),ready:t.ready}:null}async function L(e,t){await P(e.deviceId,async()=>{M.get(e.deviceId)===e&&(_({level:`warn`,phase:`ios_runner_session_invalidated`,data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await R(e.deviceId,e,{graceful:!1,waitTimeoutMs:E}))})}async function R(e,t,n={}){let r=t??M.get(e);r&&(await st(r,n),M.get(e)===r&&M.delete(e))}function _n(e){z(e);let t=vn();if(t<=0||!M.has(e))return;let n=setTimeout(()=>{N.delete(e),_({level:`info`,phase:`ios_runner_idle_stop`,data:{deviceId:e,idleMs:t}}),B(e).catch(t=>{_({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e,error:t instanceof Error?t.message:String(t)}})})},t);n.unref?.(),N.set(e,n),_({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e,idleMs:t}})}function z(e){let t=N.get(e);t&&(clearTimeout(t),N.delete(e))}function vn(e=process.env){let t=e.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS?.trim();if(t){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.floor(e)}return 3e5}function yn(e,t){e.speculative&&!zt(t)&&(e.speculative=!1)}async function bn(e){return await P(e,async()=>{let t=M.get(e);return t?.speculative?(_({level:`debug`,phase:`ios_runner_speculative_released`,data:{deviceId:e,sessionId:t.sessionId,ready:t.ready}}),await B(e),!0):!1})}async function B(e){z(e),await P(e,async()=>{await ot(e,async()=>{await R(e,void 0,{leaseLockHeld:!0}),await ht(e)})})}async function xn(){let e=Array.from(M.values());await ft(e);for(let t of e)M.get(t.deviceId)===t&&M.delete(t.deviceId)}async function Sn(){if(!Wt())return 0;let e=0;for(let[t,n]of M)if(n.device.kind===`simulator`&&!n.simulatorSetRedirect&&!(!n.lease||!w(n.child.pid))){try{C(ut(n.lease))}catch{continue}M.delete(t),z(t),e+=1,_({level:`info`,phase:`ios_runner_session_detached`,data:{deviceId:t,sessionId:n.sessionId,runnerPid:n.child.pid,port:n.port}})}return e}async function Cn(){await xn();let e=Array.from(M.keys());await Promise.allSettled(e.map(async e=>{await B(e)})),await rt()}function wn(e){return e.kind===`simulator`?e.booted?(_({level:`debug`,phase:`ios_runner_startup_ensure_booted_skipped`,data:{deviceId:e.id}}),Promise.resolve()):Tn(e):Promise.resolve()}async function Tn(e){await Pe(Le(e,[`bootstatus`,e.id,`-b`]),{timeoutMs:Ye})}async function En(e){if(!c(e)||e.kind!==`device`)return;let t=await g(`DevToolsSecurity`,[`-status`],{allowFailure:!0,timeoutMs:2e3}),n=`${t.stdout}\n${t.stderr}`;if(/developer mode is currently disabled/i.test(n))throw new a(`COMMAND_FAILED`,`Developer mode is disabled for Apple development tools`,{hint:"Run `sudo DevToolsSecurity -enable`, then retry the iOS runner. UI test runners start suspended until Xcode/testmanagerd can attach.",devToolsSecurityStatus:n.trim()})}function Dn(e){if(!s(e.platform))throw new a(`UNSUPPORTED_PLATFORM`,`Unsupported platform for iOS runner: ${e.platform}`);if(e.kind!==`simulator`&&e.kind!==`device`)throw new a(`UNSUPPORTED_OPERATION`,`Unsupported iOS device kind for runner: ${e.kind}`)}async function V(e,t,n,r,i,a){Kn(t,n.command);let o=x(n),s=A(o),c=Je.fromTimeoutMs(i),l=Hn(t,o);l.action===`run`?await jn({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,signal:a,decision:l}):Mn(o,t,l);let u;try{u=await An({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,timeoutMs:i,signal:a,readOnlyCommand:s})}catch(e){throw kn(e,t,l)}try{let e=await Nn(u,t,r),n=Vn(e);return n?(t.lastHealthyMutation=void 0,await L(t,n)):Vt(o)&&(t.lastHealthyMutation={atMs:Date.now(),appBundleId:o.appBundleId}),e}catch(e){let n=lt(e);throw n?(t.lastHealthyMutation=void 0,await L(t,n),e):On(e)?e:kn(e,t,l)}}function On(e){return e instanceof a&&e.details?.runner!==void 0}function kn(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,Wn(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function An(e){let{device:t,session:n,runnerCommand:r,logPath:i,deadline:o,timeoutMs:s,signal:c,readOnlyCommand:l}=e,u=o.remainingMs();if(u<=0)throw new a(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:s});let d=l?{command:r.command,commandId:r.commandId,readOnly:!0,sessionReady:n.ready,timeoutMs:u}:{command:r.command,commandId:r.commandId};return await Ie(`ios_runner_command_send`,async()=>l?await vt(t,n.port,r,i,u,n,c):await Xe(t,n.port,r,u,c),d)}async function jn(e){let{device:t,session:n,runnerCommand:r,logPath:i,deadline:a,signal:o,decision:s}=e,c=n.ready?Math.min(1e3,a.remainingMs()):Math.min(Gn(n),a.remainingMs());try{await Nn(await Ie(`ios_runner_readiness_preflight`,async()=>await vt(t,n.port,x({command:`uptime`}),i,c,n,o),{command:r.command,commandId:r.commandId,reason:s.reason,lastHealthyMutationAgeMs:s.lastHealthyMutationAgeMs,sessionReady:n.ready,timeoutMs:c}),n,i)}catch(e){throw Un(e)}}function Mn(e,t,n){_({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:n.reason,lastHealthyMutationAgeMs:n.reason===`recent_healthy_mutation`?n.lastHealthyMutationAgeMs:void 0,sessionReady:t.ready}})}async function Nn(e,t,n){let r=Pn(await e.text());if(!r.ok)throw await Xt({error:Fn(r,n),logPath:n});return t.ready=!0,zn(r)}function Pn(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{throw new a(`COMMAND_FAILED`,`Invalid runner response`,{text:e})}}function Fn(e,t){let n=In(e.error?.code),r=typeof e.error?.message==`string`?e.error.message:void 0,i=typeof e.error?.hint==`string`?e.error.hint:void 0;return new a(Rn(n),r??`Runner error`,{runner:e,runnerErrorCode:n,retriable:n===`RUNNER_BUSY`||void 0,xcodebuild:{exitCode:1,stdout:``,stderr:``},hint:i,logPath:t})}function In(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}const Ln=new Set([`RUNNER_BUSY`,u]);function Rn(e){return e!==void 0&&Ln.has(e)?`COMMAND_FAILED`:e?n(e):`COMMAND_FAILED`}function zn(e){if(!e.data||typeof e.data!=`object`||Array.isArray(e.data))return{};let t=e.data;return Bn(t),t}function Bn(e){let t=e.gestureFallback;typeof t==`string`&&t.length!==0&&_({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function Vn(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function Hn(e,t){let n=A(t);if(Bt(t))return{action:`skip`,reason:`preflight_exempt_command`};if(!e.ready)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(zt(t))return{action:`skip`,reason:`readiness_probe_command`};if(!Vt(t))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function Un(e){return Wn(e,{runnerReadinessPreflightFailed:!0})}function Wn(e,t){let n=e instanceof a?e:new a(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new a(n.code,n.message,{...n.details??{},...t},n.cause??e)}function Gn(e){return e.startupTimeoutMs??45e3}async function H(e,t,n){let r=Date.now();try{return await n()}finally{let n=Date.now()-r;e[t]=n,_({level:`debug`,phase:`ios_runner_startup_${t}`,durationMs:n})}}function Kn(e,t){if(e.startupTimingsReported||!e.startupTimings)return;e.startupTimingsReported=!0;let n=Object.values(e.startupTimings).reduce((e,t)=>e+t,0);_({level:`info`,phase:`ios_runner_session_startup_timings`,durationMs:n,data:{command:t,sessionId:e.sessionId,ready:e.ready,logicalLeaseContext:e.logicalLeaseContext,timings:e.startupTimings}})}function qn(e,t){if(!e)return;let n={leaseId:U(e.leaseId),clientId:U(e.clientId),tenantId:U(e.tenantId),runId:U(e.runId),leaseProvider:U(e.leaseProvider),deviceKey:U(e.deviceKey)??t},r=Object.entries(n).filter(([,e])=>e!==void 0);return r.length>0?Object.fromEntries(r):void 0}function U(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}async function Jn(e){let{device:t,session:n,command:r,transportError:i,options:a,signal:o,invalidationReason:s}=e;return await Yn(await $n(t,n,r,i,a,o),{command:r,session:n,transportError:i,invalidationReason:s,invalidateSession:e.invalidateSession})}async function Yn(e,t){if(!e)return await Qn(t,`status_recovery_unavailable`);if(e.type===`recovered`)return Xn(e,t);if(e.type===`skipInvalidation`)throw Zn(e,t);return await Qn(t,e.reason,e.lifecycleState,e.error)}function Xn(e,t){return K({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.data}function Zn(e,t){return K({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.error}async function Qn(e,t,n,r){throw K({command:e.command,session:e.session,transportError:e.transportError,decision:`retained`,reason:t,lifecycleState:n}),await e.invalidateSession(e.session,e.invalidationReason),r??e.transportError}async function $n(e,t,n,r,i,a){if(n.command===`status`||!n.commandId?.trim())return;let o=G(r),s;try{s=await V(e,t,{command:`status`,statusCommandId:n.commandId},i.logPath,3e3,a)}catch(e){return _({level:`debug`,phase:`ios_runner_command_status_recovery_failed`,data:{command:n.command,commandId:n.commandId,error:e instanceof Error?e.message:String(e),...o}}),{type:`retainInvalidation`,reason:`status_probe_failed`}}let c=typeof s.lifecycleState==`string`?s.lifecycleState:``;return _({level:`debug`,phase:`ios_runner_command_status_recovery`,data:{command:n.command,commandId:n.commandId,lifecycleState:c,...o}}),er(s,c,n,r,i)}function er(e,t,n,r,i){return t===`completed`?tr(e,n,r,i):t===`failed`?{type:`skipInvalidation`,reason:`runner_reported_failure`,lifecycleState:t,error:nr(e,n,r,i)}:t===`accepted`||t===`started`?{type:`skipInvalidation`,reason:`command_still_in_flight`,lifecycleState:t,error:rr(t,n,r,i)}:{type:`retainInvalidation`,reason:t?`unknown_lifecycle_state`:`missing_lifecycle_state`,lifecycleState:t,error:new a(`COMMAND_FAILED`,`Runner command "${n.command}" lost its transport response and lifecycle status was ${t?`"${t}"`:`missing`}, so agent-device invalidated the runner session instead of replaying the command.`,{command:n.command,commandId:n.commandId,lifecycleState:t,recovery:`lifecycle_state_not_recoverable`,hint:fr(n.command),logPath:i.logPath,transportError:r.message},r)}}function tr(e,t,n,r){let i=ir(e.lifecycleResponseJson);if(i)return{type:`recovered`,data:i,reason:`completed_with_retained_response`,lifecycleState:`completed`};if(A(t))return{type:`skipInvalidation`,error:n,reason:`read_only_completed_without_retained_response`,lifecycleState:`completed`};let o=G(n);return{type:`skipInvalidation`,reason:`completed_without_retained_response`,lifecycleState:`completed`,error:new a(`COMMAND_FAILED`,`Runner command "${t.command}" completed after the transport response was lost, but no recoverable response was retained.`,{command:t.command,commandId:t.commandId,lifecycleState:`completed`,recovery:`completed_without_retained_response`,...o,hint:or(t.command,o),logPath:r.logPath,transportError:n.message},n)}}function nr(e,t,r,i){let o=typeof e.lifecycleErrorCode==`string`?e.lifecycleErrorCode:void 0,s=typeof e.lifecycleErrorMessage==`string`?e.lifecycleErrorMessage:`Runner command failed`,c=typeof e.lifecycleErrorHint==`string`?e.lifecycleErrorHint:void 0,l=G(r);return new a(n(o),s,{command:t.command,commandId:t.commandId,lifecycleState:`failed`,recovery:`runner_reported_failure`,...l,hint:c??sr(t.command,l),logPath:i.logPath,transportError:r.message},r)}function rr(e,t,n,r){if(A(t))return n;let i=G(n);return new a(`COMMAND_FAILED`,`Runner command "${t.command}" is still ${e} after the transport response was lost.`,{command:t.command,commandId:t.commandId,lifecycleState:e,recovery:`command_still_in_flight`,...i,hint:cr(t.command,e,i),logPath:r.logPath,transportError:n.message},n)}function ir(e){if(typeof e!=`string`||e.trim().length===0)return;let t=ar(e);if(t.ok)return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:{}}function ar(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{}}function or(e,t){return`${W(t)}The runner is still reachable and reports "${e}" already completed, so agent-device kept the session open and will not replay it. Run snapshot -i to inspect the current UI, then continue from that observed state.`}function sr(e,t){return`${W(t)}The runner is still reachable and reports "${e}" failed after the transport response was lost, so agent-device kept the session open and did not replay it. Run snapshot -i to inspect the current UI and retry with a selector visible in that snapshot.`}function cr(e,t,n){return`${W(n)}The runner is still reachable and reports "${e}" is ${t}, so agent-device kept the session open and will not replay it. Wait briefly, run snapshot -i to inspect the current UI, then continue from that observed state.`}function W(e){return e.readinessPreflightSkipped===!0?`This hot command skipped the uptime preflight because the runner had just completed a healthy interaction; status recovery confirmed the runner still observed it. `:``}function lr(e,t){let n=e.details?.[t];return typeof n==`boolean`?n:void 0}function ur(e,t){let n=e.details?.[t];return typeof n==`string`?n:void 0}function dr(e,t){let n=e.details?.[t];return typeof n==`number`?n:void 0}function G(e){let t={},n=lr(e,`runnerReadinessPreflightSkipped`);n!==void 0&&(t.readinessPreflightSkipped=n);let r=ur(e,`runnerReadinessPreflightSkipReason`);r!==void 0&&(t.readinessPreflightSkipReason=r);let i=dr(e,`runnerReadinessPreflightSkippedAgeMs`);return i!==void 0&&(t.readinessPreflightSkippedAgeMs=i),t}function fr(e){return`The runner did not confirm that "${e}" reached a safe terminal state, so agent-device kept the conservative invalidation path. Run snapshot -i before retrying if the UI may have changed.`}function K(e){let{command:t,session:n,transportError:r,decision:i,reason:a,lifecycleState:o}=e;_({level:i===`retained`?`warn`:`debug`,phase:`ios_runner_command_invalidation_decision`,data:{command:t.command,commandId:t.commandId,decision:i,reason:a,lifecycleState:o,runnerReachable:o!==void 0,sessionId:n.sessionId,transportError:r.message}})}const q=new Map;function pr(e,t){let n=e.requestId?.trim();if(n)return`request:${n}`;let r=t.commandId?.trim();if(r)return`command:${r}`}function mr(e){if(!e)return;let t=J(e);t.touchedSession=!0,Y(e,t)}function hr(e){return e?q.get(e)?.touchedSession===!0:!1}function gr(e){if(!e)return!0;let t=J(e);return t.recycles>=1?(Y(e,t),!1):(Y(e,t),!0)}function _r(e){if(!e)return;let t=J(e);t.recycles+=1,Y(e,t)}function vr(e,t){return _({level:`warn`,phase:`ios_runner_recycle_budget_exhausted`,data:{command:e.command,commandId:e.commandId,requestId:t.requestId,maxRecycles:1}}),new a(`COMMAND_FAILED`,`iOS runner was already restarted during this request and "${e.command}" still failed, so agent-device stopped instead of paying for another runner boot.`,{command:e.command,commandId:e.commandId,recovery:`runner_recycle_budget_exhausted`,hint:"Check the runner log for the underlying failure before retrying — a provisioning or code-signing error there means the runner cannot install on this device, and no retry will help. If the runner is healthy, the current screen is likely too heavy or animating for accessibility capture: the app session is preserved, so run `screenshot` for visual truth and interact by coordinates, or navigate to another screen.",logPath:t.logPath})}function J(e){return yr(),q.get(e)??{touchedSession:!1,recycles:0,lastAtMs:Date.now()}}function Y(e,t){t.lastAtMs=Date.now(),q.delete(e),q.set(e,t)}function yr(){let e=Date.now()-6e5;for(let[t,n]of q)n.lastAtMs<e&&q.delete(t);for(;q.size>512;){let e=q.keys().next().value;if(e===void 0)break;q.delete(e)}}async function br(e,t){b(t.requestId);let n=y(t),r=x({command:`uptime`}),i;for(let a=1;a<=2;a+=1){let o=await xr({device:e,command:r,options:t,signal:n,attempt:a,recoveryReason:i});if(o.kind===`prepared`)return o.result;i=o.recoveryReason}throw new a(`COMMAND_FAILED`,`iOS runner prepare failed`)}async function xr(e){let{device:t,command:n,options:r,signal:i,attempt:a,recoveryReason:o}=e,s=Date.now(),c=await F(t,{...r,cleanStaleBundles:a>1||r.cleanStaleBundles,...Or(r,`runner_session`)}),l=Date.now()-s;try{return{kind:`prepared`,result:Pr(t,await Dr(t,c,n,r,i,l,{recoveryReason:o}))}}catch(e){return await Sr({device:t,session:c,command:n,options:r,signal:i,attempt:a,error:e})}}async function Sr(e){let{device:n,session:i,command:a,options:o,signal:s,attempt:c,error:l}=e,u=r(l,`COMMAND_FAILED`);if(t(u))throw await X(i,`prepare_runner_request_canceled`),l;if(c===1&&Ar(u,i))return{kind:`prepared`,result:await Cr({device:n,session:i,command:a,options:o,signal:s,error:u})};if(!wr(u))throw l;let d=u.message||`runner_health_failed`;if(c>=2)throw await X(i,`prepare_runner_health_failed`),l;return b(o.requestId),await L(i,`prepare_runner_health_retry`),_({level:`warn`,phase:`ios_runner_prepare_health_retry`,data:{command:a.command,commandId:a.commandId,sessionId:i.sessionId,attempt:c,maxAttempts:2,reason:d}}),{kind:`retry`,recoveryReason:d}}async function Cr(e){let{device:t,session:n,command:r,options:i,signal:a,error:o}=e,s=o.message||`runner_health_failed`;await L(n,`prepare_cached_runner_health_failed`),await yt(n.xctestrunArtifact,s);let c=Date.now(),l=await F(t,{...i,cleanStaleBundles:!0,forceRunnerXctestrunRebuild:!0,...Or(i,`runner_rebuild`)}),u=Date.now()-c;try{let e=await Dr(t,l,r,i,a,u,{recoveryReason:s});return _({level:`info`,phase:`ios_runner_prepare_bad_cache_recovered`,data:{command:r.command,commandId:r.commandId,sessionId:l.sessionId,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,reason:s}}),Pr(t,e)}catch(e){await X(l,`prepare_rebuilt_runner_health_failed`);let n=Mr(e,l,s);throw Fr(t,{cache:l.xctestrunArtifact?.cache,artifact:l.xctestrunArtifact?.artifact,buildMs:l.xctestrunArtifact?.buildMs,connectMs:u,healthCheckMs:0,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,failureReason:n.message}),n}}async function X(e,t){try{await L(e,t)}catch{}}function wr(e){return t(e)?!1:S(e)||Qe(e)||jr(e)}async function Tr(e,n,i){b(i.requestId);let a=y(i),o=pr(i,n),s,c=!1;try{if(!I(e.id)?.alive&&hr(o)){if(!gr(o))throw vr(n,i);c=!0}s=await F(e,i),un(s,i.expectedRunnerSessionId),yn(s,n),c&&_r(o),mr(o);let t=s.ready?tt:Gn(s);return await V(e,s,n,i.logPath,t,a)}catch(o){if(i.expectedRunnerSessionId!==void 0)throw o;let c=r(o,`COMMAND_FAILED`);if(s&&!s.ready&&t(c))throw await X(s,`runner_startup_request_canceled`),o;if(ct(c)&&s)return b(i.requestId),await Er({device:e,session:s,command:n,options:i,signal:a,restartReason:`runner_connect_failed_before_command_send`});if(s&&Lr(c))return b(i.requestId),await Er({device:e,session:s,command:n,options:i,signal:a,restartReason:`runner_readiness_preflight_failed_before_command_send`,recoveredDiagnosticPhase:`ios_runner_readiness_preflight_recovered`});if(s&&S(c))return await Jn({device:e,session:s,command:n,transportError:c,options:i,signal:a,invalidationReason:`transport_error_after_command_send`,invalidateSession:L});throw o}}async function Er(e){let{device:t,command:n,options:i,signal:a,restartReason:o}=e,s=pr(i,n);if(!gr(s))throw vr(n,i);await L(e.session,o);let c=await F(t,{...i,cleanStaleBundles:!0}).catch(t=>{throw Z(t,e)});_r(s);try{let r=await V(t,c,n,i.logPath,Ye,a);return e.recoveredDiagnosticPhase&&_({level:`debug`,phase:e.recoveredDiagnosticPhase,data:{command:n.command,commandId:n.commandId,recovery:`session_restarted`,sessionId:c.sessionId}}),r}catch(o){let s=r(o,`COMMAND_FAILED`);if(S(s))try{return await Jn({device:t,session:c,command:n,transportError:s,options:i,signal:a,invalidationReason:`transport_error_after_retry_command_send`,invalidateSession:L})}catch(t){throw Z(t,e,c)}throw Z(o,e,c)}}function Z(e,t,n){return e instanceof a?new a(e.code,e.message,{...e.details??{},runnerRestarted:!0,runnerRestartReason:t.restartReason,runnerRestartCommand:t.command.command,...t.command.commandId?{runnerRestartCommandId:t.command.commandId}:{},runnerInvalidatedSessionId:t.session.sessionId,...n?{runnerRestartSessionId:n.sessionId}:{},...e.details?.logPath===void 0&&t.options.logPath?{logPath:t.options.logPath}:{}},e.cause??e):e}async function Dr(e,t,n,r,i,a,o){let s=Date.now(),c=kr(r.prepareDeadline,r.healthTimeoutMs,`runner_health`);return Nr(await V(e,t,n,r.logPath,c,i),t,a,Date.now()-s,o)}function Or(e,t){if(!e.prepareDeadline)return{};let n=kr(e.prepareDeadline,e.buildTimeoutMs,t);return{buildTimeoutMs:n,startupTimeoutMs:n}}function kr(e,t,n){if(!e)return t??45e3;let r=Math.floor(e.remainingMs());if(r<=0)throw new a(`COMMAND_FAILED`,`prepare ios-runner timed out`,{phase:n,reason:`prepare_deadline_expired`});return r}function Ar(e,t){let n=t.xctestrunArtifact;return!n||n.cache===`miss`?!1:wr(e)}function jr(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)||t.includes(`deadline`)}function Mr(e,t,n){let i=r(e,`COMMAND_FAILED`);return new a(i.code,`artifact restored but runner did not connect`,{...i.details??{},restoredFailureReason:n,xctestrunPath:t.xctestrunArtifact?.xctestrunPath,artifact:t.xctestrunArtifact?.artifact,cache:t.xctestrunArtifact?.cache,reason:i.message},i)}function Nr(e,t,n,r,i){let a=t.xctestrunArtifact,o={...i?.recoveryReason?{recoveryReason:i.recoveryReason}:{},...i?.failureReason?{failureReason:i.failureReason}:{}};return a?{runner:e,cache:a.cache,artifact:a.artifact,buildMs:a.buildMs,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),xctestrunPath:a.xctestrunPath,...o}:{runner:e,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),...o}}function Pr(e,t){return Fr(e,t),t}function Fr(e,t){_({level:t.failureReason?`warn`:`info`,phase:`apple_runner_prepare`,data:{platform:e.platform,target:e.target,deviceId:e.id,cache:t.cache,artifact:t.artifact,buildMs:t.buildMs,connectMs:t.connectMs,healthCheckMs:t.healthCheckMs,timingContainment:t.buildMs===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},xctestrunPath:t.xctestrunPath,recoveryReason:t.recoveryReason,failureReason:t.failureReason}})}function Ir(e){return e.details?.runnerReadinessPreflightFailed===!0}function Lr(e){return Ir(e)&&(S(e)||Rr(e))}function Rr(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)}async function zr(e,t,n={}){Dn(e),b(n.requestId);let r=x(t),i=Q(e,n);return A(r)?Be(()=>(b(n.requestId),i.runCommand(e,r,n)),{shouldRetry:e=>(b(n.requestId),S(e))}):i.runCommand(e,r,n)}async function Br(e,t={}){if(c(e))try{await zr(e,{command:`targetReset`},t)}catch(t){_({level:`warn`,phase:`ios_runner_target_reset_failed`,data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}}),await B(e.id)}}function Vr(e,t={}){if(c(e))return Ur({device:e,options:t,failurePhase:`ios_runner_cache_prewarm_failed`,task:async t=>{await _t(e,t)}})}function Hr(e,t={}){if(!c(e))return;let n=Q(e,t).prewarm;if(!n){_({level:`debug`,phase:`ios_runner_session_prewarm_unavailable`,data:{deviceId:e.id}});return}return Ur({device:e,options:t,failurePhase:`ios_runner_session_prewarm_failed`,task:async t=>{await n(e,t)}})}function Ur(e){let{device:t,options:n,failurePhase:r,task:i}=e,{propagateError:a=!1,...o}=n;return i(o).catch(e=>{if(_({level:`warn`,phase:r,data:{deviceId:t.id,error:e instanceof Error?e.message:String(e)}}),a)throw e})}async function Wr(e,t){Dn(e),b(t.requestId);let n=x({command:`uptime`}),r=Q(e,t);if(r.prepare)return await r.prepare(e,t);let i=Date.now();return{runner:await r.runCommand(e,n,t),connectMs:0,healthCheckMs:Math.max(0,Date.now()-i)}}function Q(e,t){return Ae(e,qr,void 0,{requestId:t.requestId})}function Gr(e,t={}){return c(e)?Q(e,t).hasLiveSession(e):!1}async function Kr(e,t={}){if(!c(e))return!1;let n=Q(e,t).releaseSpeculativeSession;return n?await n(e):!1}const qr=Oe(Tr,{prepare:br,hasLiveSession:e=>{let t=I(e.id);return t!==null&&t.alive&&t.ready},releaseSpeculativeSession:async e=>await bn(e.id),prewarm:async(e,t)=>{let{healthCheck:n,...r}=t;if(n===!1){await F(e,{...r,speculative:!0});return}await br(e,{...r,speculative:!0,healthTimeoutMs:tt})}});function Jr(e){return He(e),{runAppleRunnerCommand:zr,notifyIosRunnerAppRelaunched:Br,hasLiveIosRunnerSession:Gr,releaseSpeculativeIosRunnerSessionFor:Kr,prewarmAppleRunnerCache:Vr,prewarmIosRunnerSession:Hr,prepareIosRunner:Wr,resolveRunnerAppBundleId:Ke,hasCachedAppleRunnerArtifact:bt,detachIosSimulatorRunnerSessionsForShutdown:Sn,getRunnerSessionSnapshot:I,scheduleIosRunnerIdleStop:_n,stopIosRunnerSession:B,stopAllIosRunnerSessions:Cn,runApplePressSeries:ke,cleanupRunnerLeasesForOwner:it,readStaleRunnerLease:mt,verifyLeaseRunnerPidIdentity:T,runnerLeaseCleanupAdapter:pt,applyXctestRunnerAppIconFromDerivedPath:nt}}const Yr={runCmdStreaming:oe,runCmdSync:se,runCmdBackground:ae,requireExecSuccess:ce,emitDiagnostic:f,withDiagnosticTimer:d,retryWithPolicy:ue,isEnvTruthy:fe,deadlineFromTimeoutMs:(e,t)=>de.fromTimeoutMs(e,t),isProcessAlive:te,isProcessGroupAlive:ee,readProcessStartTime:h,readProcessCommand:ie,signalPidsBestEffort:re,signalProcessGroupBestEffort:m,findProjectRoot:pe,readVersion:me,acquireProcessLock:le,withKeyedLock:ve,publishFileSync:p,classifyOwnerLiveness:ne,createTtlMemo:he,parseBooleanLiteral:l,isRecord:o,resolveIosSimulatorDeviceSetPath:Se,emitRequestProgress:xe,getRequestSignal:be,isRequestCanceled:ye,classifyBootFailure:ge,bootFailureHint:_e,runAppleToolCommand:Ce,runXcrun:we,readApplePlistJson:Te,buildSimctlArgsForDevice:De,resolveIosPhysicalDeviceControl:Ee,visitXmlPlistEntries:xt,leaseOwnerStateDir:St,hasDeviceClaimAuthority:e=>Ct()?.(e)??!1};var Xr=e({applyXctestRunnerAppIconFromDerivedPath:()=>hi,cleanupRunnerLeasesForOwner:()=>fi,detachIosSimulatorRunnerSessionsForShutdown:()=>oi,getRunnerSessionSnapshot:()=>si,hasCachedAppleRunnerArtifact:()=>ai,hasLiveIosRunnerSession:()=>$r,notifyIosRunnerAppRelaunched:()=>Qr,prepareIosRunner:()=>ri,prewarmAppleRunnerCache:()=>ti,prewarmIosRunnerSession:()=>ni,readStaleRunnerLease:()=>pi,releaseSpeculativeIosRunnerSessionFor:()=>ei,resolveRunnerAppBundleId:()=>ii,runApplePressSeries:()=>di,runAppleRunnerCommand:()=>Zr,scheduleIosRunnerIdleStop:()=>ci,stopAllIosRunnerSessions:()=>ui,stopIosRunnerSession:()=>li,verifyLeaseRunnerPidIdentity:()=>mi});const $=Jr(Yr),Zr=$.runAppleRunnerCommand,Qr=$.notifyIosRunnerAppRelaunched,$r=$.hasLiveIosRunnerSession,ei=$.releaseSpeculativeIosRunnerSessionFor,ti=$.prewarmAppleRunnerCache,ni=$.prewarmIosRunnerSession,ri=$.prepareIosRunner,ii=$.resolveRunnerAppBundleId,ai=$.hasCachedAppleRunnerArtifact,oi=$.detachIosSimulatorRunnerSessionsForShutdown,si=$.getRunnerSessionSnapshot,ci=$.scheduleIosRunnerIdleStop,li=$.stopIosRunnerSession,ui=$.stopAllIosRunnerSessions,di=$.runApplePressSeries,fi=$.cleanupRunnerLeasesForOwner,pi=$.readStaleRunnerLease,mi=$.verifyLeaseRunnerPidIdentity,hi=$.applyXctestRunnerAppIconFromDerivedPath;export{ui as _,$r as a,ti as c,ei as d,ii as f,ci as g,Xr as h,ai as i,ni as l,Zr as m,oi as n,Qr as o,di as p,si as r,ri as s,hi as t,pi as u,li as v,mi as y};
1
+ import{r as e}from"./rolldown-runtime.js";import{A as t,C as n,T as r,w as i}from"./sdk-contracts.js";import{g as a}from"./sdk-batch-runner.js";import{c as o,l as s}from"./sdk-device.js";import{o as c}from"./sdk-remote-config.js";import{c as l,r as u}from"./diagnostics.js";import{C as d,O as f,S as p,m,p as h,t as ee,x as g,y as te}from"./owner-identity.js";import{a as ne,f as re,l as ie,p as ae,r as oe}from"./exec.js";import{t as se}from"./file.js";import"./diagnostics2.js";import"./command.js";import{i as ce,n as le,r as ue}from"./retry.js";import{n as de,r as fe}from"./version.js";import{t as pe}from"./ttl-memo.js";import"./process.js";import{n as me,t as he}from"./boot-diagnostics.js";import{t as ge}from"./keyed-lock.js";import{i as _e,r as ve}from"./request-cancel.js";import{t as ye}from"./request.js";import{r as be}from"./device-isolation.js";import{a as xe,o as Se,r as Ce}from"./tool-provider.js";import{t as we}from"./physical-device-control.js";import{t as Te}from"./simctl.js";import{a as Ee,i as De,o as Oe}from"./runner.js";import{A as _,B as ke,F as Ae,G as je,H as Me,Q as Ne,T as Pe,U as Fe,W as v,Z as Ie,_ as Le,c as Re,d as ze,i as y,o as Be,q as Ve,s as He,t as Ue,u as We,w as b,x as Ge,y as Ke}from"./runner-cache-metadata.js";import{a as qe}from"./apple-runner-platform.js";import{A as x,C as Je,E as Ye,F as S,I as Xe,L as Ze,M as C,N as Qe,O as w,P as $e,S as et,T as tt,_ as T,a as E,b as nt,c as rt,d as it,f as at,g as ot,h as D,i as st,j as ct,k as lt,l as ut,m as dt,n as ft,o as pt,p as mt,r as ht,t as O,u as gt,v as _t,w as vt,x as yt,y as bt}from"./runner-disposal.js";import{t as xt}from"./plist-xml.js";import{n as St,t as Ct}from"./runner-owner-state.js";import k from"node:path";import wt from"node:fs";import Tt from"node:fs/promises";const Et={PreferredScreenCaptureFormat:`screenshots`,SystemAttachmentLifetime:`keepNever`,UserAttachmentLifetime:`keepNever`};async function Dt(e,t,n,r={}){let i=r.iosXctestEnvDir?.trim(),a=i?k.resolve(i):k.dirname(e);wt.mkdirSync(a,{recursive:!0});let o=n.replaceAll(/[^a-zA-Z0-9._-]/g,`_`),s=k.join(a,`AgentDeviceRunner.env.${o}.json`),c=k.join(a,`AgentDeviceRunner.env.${o}.xctestrun`),l=await Ot(e);return Mt(l,e=>At(e,t)),jt(l),await kt(l,s,c),{xctestrunPath:c,jsonPath:s}}async function Ot(e){let t=await v(`plutil`,[`-convert`,`json`,`-o`,`-`,e],{allowFailure:!0});if(t.exitCode!==0||!t.stdout.trim())throw new n(`COMMAND_FAILED`,`Failed to read xctestrun plist`,{xctestrunPath:e,stderr:t.stderr});try{let e=JSON.parse(t.stdout);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Root must be an object`);return e}catch(t){throw new n(`COMMAND_FAILED`,`Failed to parse xctestrun JSON`,{xctestrunPath:e,error:String(t)})}}async function kt(e,t,n){wt.writeFileSync(t,JSON.stringify(e,null,2)),ke(await v(`plutil`,[`-convert`,`xml1`,`-o`,n,t],{allowFailure:!0}),`Failed to write xctestrun plist`,{tmpXctestrunPath:n})}function At(e,t){e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}}function jt(e){Mt(e,e=>Object.assign(e,Et),{requireTestBundlePath:!0})}function Mt(e,t,n={}){let r=e.TestConfigurations;if(Array.isArray(r))for(let e of r)!e||typeof e!=`object`||Nt(e.TestTargets,t,n);for(let n of Object.values(e)){let e=Pt(n,{requireTestBundlePath:!0});e&&t(e)}}function Nt(e,t,n){if(Array.isArray(e))for(let r of e){let e=Pt(r,n);e&&t(e)}}function Pt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return t.requireTestBundlePath&&!n.TestBundlePath?null:n}const Ft={tap:`preflightSkippableTouchMutation`,mouseClick:`default`,longPress:`preflightSkippableTouchMutation`,drag:`preflightSkippableTouchMutation`,remotePress:`default`,type:`default`,swipe:`preflightSkippableTouchMutation`,scroll:`preflightSkippableTouchMutation`,desktopScroll:`preflightSkippableTouchMutation`,findText:`readOnly`,querySelector:`readOnly`,readText:`readOnly`,snapshot:`readOnly`,screenshot:`readOnly`,back:`default`,backInApp:`default`,backSystem:`default`,home:`default`,rotate:`default`,gesture:`preflightSkippableTouchMutation`,gestureViewport:`readOnly`,appSwitcher:`default`,keyboardDismiss:`default`,keyboardReturn:`default`,alert:`alertAction`,sequence:`preflightSkippableTouchMutation`,recordStart:`default`,recordStop:`default`,status:`readOnlyReadinessProbe`,uptime:`readOnlyReadinessProbe`,activate:`readinessPreflightExemptMutation`,terminate:`readinessPreflightExemptMutation`,targetReset:`readinessPreflightExemptMutation`,shutdown:`default`},A={readOnly:!1,readinessProbe:!1,readinessPreflightExempt:!1,readinessPreflightSkipEligibleAfterHealthyMutation:!1},It={...A,readinessPreflightExempt:!0},j={...A,readOnly:!0},Lt={...j,readinessProbe:!0},Rt={...A,readinessPreflightSkipEligibleAfterHealthyMutation:!0};function M(e){return N(e).readOnly}function zt(e){return N(e).readinessProbe}function Bt(e){return N(e).readinessPreflightExempt}function Vt(e){return N(e).readinessPreflightSkipEligibleAfterHealthyMutation}function N(e){switch(Ft[e.command]){case`default`:return A;case`readinessPreflightExemptMutation`:return It;case`readOnly`:return j;case`alertAction`:return(e.action??`get`).toLowerCase()===`get`?j:A;case`readOnlyReadinessProbe`:return Lt;case`preflightSkippableTouchMutation`:return Rt}}function Ht(e,t){return`${e}:${t}:${Date.now()}`}function Ut(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function Wt(e=process.env){return Ae(e.AGENT_DEVICE_IOS_RUNNER_DETACH??``)!==!1}async function Gt(e,t){if(e.kind!==`simulator`||!Wt()||Me(e.simulatorSetPath))return null;let n=mt(e.id);if(!n)return null;let r=t=>(b({level:`debug`,phase:`ios_runner_lease_adoption_skipped`,data:{deviceId:e.id,runnerPid:n.runnerPid,port:n.port,reason:t}}),null);if(t.expectedRunnerSessionId!==void 0&&n.sessionId!==t.expectedRunnerSessionId)return r(`session_identity_mismatch`);let i=n.runnerPid;if(!i)return r(`runner_pid_missing`);if(!_(i))return r(`runner_process_dead`);if(!D(n,i))return r(`runner_pid_recycled`);let a=qt(e,t.budget);if(!a)return r(`expected_derived_unresolved`);if(!n.xctestrunPath.startsWith(`${a}${k.sep}`))return r(`artifact_fingerprint_mismatch`);if(!await Kt(e,n.port))return r(`probe_failed`);if(!_(i)||!D(n,i))return r(`runner_pid_recycled`);let o=Jt(e,n,i,a,t);try{T(o.lease)}catch{return null}return b({level:`info`,phase:`ios_runner_lease_adopted`,data:{deviceId:e.id,sessionId:o.sessionId,runnerPid:i,port:n.port,previousOwnerPid:n.ownerPid}}),o}async function Kt(e,t){try{let n=await Ye(e,t,S({command:`uptime`}),500);return JSON.parse(await n.text())?.ok===!0}catch{return!1}}function qt(e,n){try{return We(e,He(e,void 0,n))}catch(e){if(t(e))throw e;return null}}function Jt(e,t,n,r,i){let a=t.sessionId,o={xctestrunPath:t.xctestrunPath,derived:r,cache:`exact`,artifact:`valid`,buildMs:0,xctestrunPathSource:`manifest`,reason:`adopted_from_lease`},{child:s,wait:c}=Yt(n);return{sessionId:a,device:e,deviceId:e.id,port:t.port,xctestrunPath:t.xctestrunPath,xctestrunArtifact:o,jsonPath:t.jsonPath,testPromise:c,child:s,ready:!0,startupTimeoutMs:Ut(Be(i.budget,`runner_session_adoption`)),lease:gt({deviceId:e.id,sessionId:a,runnerPid:n,port:t.port,xctestrunPath:t.xctestrunPath,jsonPath:t.jsonPath})}}function Yt(e){let t={pid:e,exitCode:null};return{child:t,wait:new Promise(n=>{let r=setInterval(()=>{_(e)||(clearInterval(r),t.exitCode=-1,n({stdout:``,stderr:``,exitCode:-1}))},1e3);r.unref?.()})}}async function Xt(e){let t=await Zt(e.logPath)??$t(e.error);return t?new n(t.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${t.hint}`:t.hint,runnerFailureReason:t.reason},e.error):e.error}async function Zt(e){if(!e)return;let t=await rn(e,65536);if(t)return Qt(t)}function Qt(e){let t=e.toLowerCase();if(en(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(tn(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function $t(e){if(nn(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function en(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function tn(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function nn(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function rn(e,t){let n;try{let r=await Tt.stat(e),i=Math.max(0,r.size-t),a=r.size-i;if(a<=0)return;n=await Tt.open(e,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}function an(){let e=new AbortController,t=!1,n={stdout:``,stderr:``};return{wake:e.signal,observe:(r,i)=>{if(t)return;let a=n[r]+i;if(a.includes(`AGENT_DEVICE_RUNNER_LISTENER_READY`)){t=!0,n.stdout=``,n.stderr=``,e.abort();return}n[r]=a.slice(-33)},finish:()=>{t=!0,n.stdout=``,n.stderr=``,e.abort()}}}function on(e){let t=an(),n=je(`xcodebuild`,[`test-without-building`,`-only-testing`,`AgentDeviceRunnerUITests/RunnerTests/testCommand`,`-parallel-testing-enabled`,`NO`,`-test-timeouts-enabled`,`NO`,`-collect-test-diagnostics`,`never`,ze(e.device),`1`,`-destination-timeout`,`20`,`-xctestrun`,e.xctestrunPath,`-derivedDataPath`,e.derivedPath,`-destination`,qe(e.device)],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(e.port)},detached:!0,signal:e.signal}),r=(n,r)=>{t.observe(n,r),Ze(r,e.logPath,e.traceLogPath,e.verbose)};return n.child.stdout?.on(`data`,e=>r(`stdout`,e)),n.child.stderr?.on(`data`,e=>r(`stderr`,e)),n.wait.then(t.finish,t.finish),{...n,startupRetryWake:t.wake}}const P=new Map,sn=new Map,F=new Map,cn=1e4;function I(e,t){return Ne(sn,e,t)}async function L(e,t){return V(e.id),await I(e.id,async()=>{let n=y(t.startupTimeoutMs,C(t)),r=P.get(e.id);if(r){un(r,t.expectedRunnerSessionId);let i=await pn(e,r,n);if(i)return i}return await ot(e.id,async()=>await ln(e,t,n))})}async function ln(e,t,n){let i={},a=n.signal,o=Gn(t.runnerLeaseContext,e.id);b({level:`debug`,phase:`ios_runner_session_startup`,data:{deviceId:e.id,logicalLeaseContext:o}});let s=await W(i,`adopt_detached_runner`,async()=>await Gt(e,{budget:n,expectedRunnerSessionId:t.expectedRunnerSessionId}));if(s)return s.startupTimings=i,s.logicalLeaseContext=o,P.set(e.id,s),s;dn(t.expectedRunnerSessionId),await W(i,`cleanup_stale_xcodebuild`,async()=>{await at(e,pt,o)}),await W(i,`ensure_booted`,async()=>{await wn(e)}),await W(i,`verify_developer_mode`,async()=>{await En(e)}),t.cleanStaleBundles?await W(i,`cleanup_stale_bundles`,async()=>{await mn(e)}):(i.cleanup_stale_bundles=0,b({level:`debug`,phase:`ios_runner_startup_cleanup_stale_bundles_skipped`}));let c=Be(n,`runner_session_startup`),l=await W(i,`ensure_xctestrun`,async()=>await _t(e,{...t,budget:y(t.buildTimeoutMs,a)}));i.build_xctestrun=l.buildMs;let u=await W(i,`allocate_port`,async()=>await Xe()),{xctestrunPath:d,jsonPath:f}=await W(i,`prepare_xctestrun_env`,async()=>await Dt(l.xctestrunPath,{AGENT_DEVICE_RUNNER_PORT:String(u)},`session-${e.id}-${dt()}-${u}`,{iosXctestEnvDir:t.iosXctestEnvDir})),p=await W(i,`simulator_set_redirect`,async()=>await et(e)),m;try{l.buildMs>0&&Pe({type:`command`,status:`progress`,message:`Starting XCTest runner...`}),m=await W(i,`launch_xcodebuild`,()=>on({device:e,port:u,xctestrunPath:d,derivedPath:l.derived,signal:a,logPath:t.logPath,traceLogPath:t.traceLogPath,verbose:t.verbose}))}catch(e){throw await p?.release(),e}let h=Ht(e.id,u),ee=gt({deviceId:e.id,sessionId:h,runnerPid:m.child.pid,port:u,xctestrunPath:d,jsonPath:f}),g={sessionId:h,device:e,deviceId:e.id,port:u,xctestrunPath:d,xctestrunArtifact:l,jsonPath:f,testPromise:m.wait,child:m.child,ready:!1,startupRetryWake:m.startupRetryWake,startupTimeoutMs:Ut(c),startupTimings:i,logicalLeaseContext:o,simulatorSetRedirect:p??void 0,lease:ee,speculative:t.speculative===!0};if(a?.aborted)throw await st(g,{graceful:!1,waitTimeoutMs:O,leaseLockHeld:!0}),r();try{T(ee)}catch(t){throw await B(e.id,g,{graceful:!1,waitTimeoutMs:O,leaseLockHeld:!0}),t}return P.set(e.id,g),g}function un(e,t){if(t!==void 0&&e.sessionId!==t)throw fn()}function dn(e){if(e!==void 0)throw fn()}function fn(){return new n(`COMMAND_FAILED`,`Apple runner session ownership changed before command dispatch`,{reason:`runner_session_ownership_changed`})}async function pn(e,t,n){if(!E(t.child.pid))return await W({},`stop_stale_session`,async()=>{await B(e.id,t,{graceful:!1,waitTimeoutMs:O})}),null;let r=t.xctestrunArtifact;if(r?.cache===`external`)return b({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,cache:r.cache,logicalLeaseContext:t.logicalLeaseContext}}),t;let i=We(e,He(e,void 0,n));return r?.derived===i?(b({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,logicalLeaseContext:t.logicalLeaseContext}}),t):(b({level:`debug`,phase:`ios_runner_session_artifact_stale`,data:{deviceId:e.id,sessionId:t.sessionId,currentDerived:r?.derived,expectedDerived:i}}),await W({},`stop_stale_artifact_session`,async()=>{await B(e.id,t)}),null)}async function mn(e){e.kind===`simulator`&&await Promise.allSettled(Ue.map(async t=>{let n=await hn(e,t);!n||gn(n)}))}async function hn(e,t){try{return await Ve(Ge(e,[`uninstall`,e.id,t]),{allowFailure:!0,timeoutMs:cn})}catch(n){b({level:`warn`,phase:`ios_runner_startup_cleanup_stale_bundle_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:cn,error:n instanceof Error?n.message:String(n)}});return}}function gn(e){if(e.exitCode===0)return!0;let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`not installed`)||t.includes(`found nothing`)||t.includes(`no such file`)||t.includes(`invalid device`)||t.includes(`could not find`)}function R(e){let t=P.get(e);return t?{sessionId:t.sessionId,alive:E(t.child.pid),ready:t.ready}:null}async function z(e,t){await I(e.deviceId,async()=>{P.get(e.deviceId)===e&&(b({level:`warn`,phase:`ios_runner_session_invalidated`,data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await B(e.deviceId,e,{graceful:!1,waitTimeoutMs:O}))})}async function B(e,t,n={}){let r=t??P.get(e);r&&(await st(r,n),P.get(e)===r&&P.delete(e))}function _n(e){V(e);let t=vn();if(t<=0||!P.has(e))return;let n=setTimeout(()=>{F.delete(e),b({level:`info`,phase:`ios_runner_idle_stop`,data:{deviceId:e,idleMs:t}}),H(e).catch(t=>{b({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e,error:t instanceof Error?t.message:String(t)}})})},t);n.unref?.(),F.set(e,n),b({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e,idleMs:t}})}function V(e){let t=F.get(e);t&&(clearTimeout(t),F.delete(e))}function vn(e=process.env){let t=e.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS?.trim();if(t){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.floor(e)}return 3e5}function yn(e,t){e.speculative&&!zt(t)&&(e.speculative=!1)}async function bn(e){return await I(e,async()=>{let t=P.get(e);return t?.speculative?(b({level:`debug`,phase:`ios_runner_speculative_released`,data:{deviceId:e,sessionId:t.sessionId,ready:t.ready}}),await H(e),!0):!1})}async function H(e){V(e),await I(e,async()=>{await ot(e,async()=>{await B(e,void 0,{leaseLockHeld:!0}),await ht(e)})})}async function xn(){let e=Array.from(P.values());await ft(e);for(let t of e)P.get(t.deviceId)===t&&P.delete(t.deviceId)}async function Sn(){if(!Wt())return 0;let e=0;for(let[t,n]of P)if(n.device.kind===`simulator`&&!n.simulatorSetRedirect&&!(!n.lease||!E(n.child.pid))){try{T(ut(n.lease))}catch{continue}P.delete(t),V(t),e+=1,b({level:`info`,phase:`ios_runner_session_detached`,data:{deviceId:t,sessionId:n.sessionId,runnerPid:n.child.pid,port:n.port}})}return e}async function Cn(){await xn();let e=Array.from(P.keys());await Promise.allSettled(e.map(async e=>{await H(e)})),await rt()}function wn(e){return e.kind===`simulator`?e.booted?(b({level:`debug`,phase:`ios_runner_startup_ensure_booted_skipped`,data:{deviceId:e.id}}),Promise.resolve()):Tn(e):Promise.resolve()}async function Tn(e){await Ve(Ge(e,[`bootstatus`,e.id,`-b`]),{timeoutMs:Je})}async function En(e){if(!s(e)||e.kind!==`device`)return;let t=await v(`DevToolsSecurity`,[`-status`],{allowFailure:!0,timeoutMs:2e3}),r=`${t.stdout}\n${t.stderr}`;if(/developer mode is currently disabled/i.test(r))throw new n(`COMMAND_FAILED`,`Developer mode is disabled for Apple development tools`,{hint:"Run `sudo DevToolsSecurity -enable`, then retry the iOS runner. UI test runners start suspended until Xcode/testmanagerd can attach.",devToolsSecurityStatus:r.trim()})}function Dn(e){if(!o(e.platform))throw new n(`UNSUPPORTED_PLATFORM`,`Unsupported platform for iOS runner: ${e.platform}`);if(e.kind!==`simulator`&&e.kind!==`device`)throw new n(`UNSUPPORTED_OPERATION`,`Unsupported iOS device kind for runner: ${e.kind}`)}async function U(e,t,n,r,i,a){Wn(t,n.command);let o=S(n),s=M(o),c=Le.fromTimeoutMs(i),l=Bn(t,o);l.action===`run`?await jn({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,signal:a,decision:l}):Mn(o,t,l);let u;try{u=await An({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,timeoutMs:i,signal:a,readOnlyCommand:s})}catch(e){throw kn(e,t,l)}try{let e=await Nn(u,t,r),n=zn(e);return n?(t.lastHealthyMutation=void 0,await z(t,n)):Vt(o)&&(t.lastHealthyMutation={atMs:Date.now(),appBundleId:o.appBundleId}),e}catch(e){let n=ct(e);throw n?(t.lastHealthyMutation=void 0,await z(t,n),e):On(e)?e:kn(e,t,l)}}function On(e){return e instanceof n&&e.details?.runner!==void 0}function kn(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,Hn(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function An(e){let{device:t,session:r,runnerCommand:i,logPath:a,deadline:o,timeoutMs:s,signal:c,readOnlyCommand:l}=e,u=o.remainingMs();if(u<=0)throw new n(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:s});let d=l?{command:i.command,commandId:i.commandId,readOnly:!0,sessionReady:r.ready,timeoutMs:u}:{command:i.command,commandId:i.commandId};return await Ie(`ios_runner_command_send`,async()=>l?await vt(t,r.port,i,a,u,r,c):await Ye(t,r.port,i,u,c),d)}async function jn(e){let{device:t,session:n,runnerCommand:r,logPath:i,deadline:a,signal:o,decision:s}=e,c=n.ready?Math.min(1e3,a.remainingMs()):Math.min(Un(n),a.remainingMs());try{await Nn(await Ie(`ios_runner_readiness_preflight`,async()=>await vt(t,n.port,S({command:`uptime`}),i,c,n,o),{command:r.command,commandId:r.commandId,reason:s.reason,lastHealthyMutationAgeMs:s.lastHealthyMutationAgeMs,sessionReady:n.ready,timeoutMs:c}),n,i)}catch(e){throw Vn(e)}}function Mn(e,t,n){b({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:n.reason,lastHealthyMutationAgeMs:n.reason===`recent_healthy_mutation`?n.lastHealthyMutationAgeMs:void 0,sessionReady:t.ready}})}async function Nn(e,t,n){let r=Pn(await e.text());if(!r.ok)throw await Xt({error:Fn(r,n),logPath:n});return t.ready=!0,Ln(r)}function Pn(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{throw new n(`COMMAND_FAILED`,`Invalid runner response`,{text:e})}}function Fn(e,t){let r=In(e.error?.code),i=typeof e.error?.message==`string`?e.error.message:void 0,a=typeof e.error?.hint==`string`?e.error.hint:void 0,o=lt(r);return new n(o.code,i??`Runner error`,{runner:e,...o.details,xcodebuild:{exitCode:1,stdout:``,stderr:``},hint:a,logPath:t})}function In(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Ln(e){if(!e.data||typeof e.data!=`object`||Array.isArray(e.data))return{};let t=e.data;return Rn(t),t}function Rn(e){let t=e.gestureFallback;typeof t==`string`&&t.length!==0&&b({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function zn(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function Bn(e,t){let n=M(t);if(Bt(t))return{action:`skip`,reason:`preflight_exempt_command`};if(!e.ready)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(zt(t))return{action:`skip`,reason:`readiness_probe_command`};if(!Vt(t))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function Vn(e){return Hn(e,{runnerReadinessPreflightFailed:!0})}function Hn(e,t){let r=e instanceof n?e:new n(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new n(r.code,r.message,{...r.details??{},...t},r.cause??e)}function Un(e){return e.startupTimeoutMs??45e3}async function W(e,t,n){let r=Date.now();try{return await n()}finally{let n=Date.now()-r;e[t]=n,b({level:`debug`,phase:`ios_runner_startup_${t}`,durationMs:n})}}function Wn(e,t){if(e.startupTimingsReported||!e.startupTimings)return;e.startupTimingsReported=!0;let n=Object.values(e.startupTimings).reduce((e,t)=>e+t,0);b({level:`info`,phase:`ios_runner_session_startup_timings`,durationMs:n,data:{command:t,sessionId:e.sessionId,ready:e.ready,logicalLeaseContext:e.logicalLeaseContext,timings:e.startupTimings}})}function Gn(e,t){if(!e)return;let n={leaseId:G(e.leaseId),clientId:G(e.clientId),tenantId:G(e.tenantId),runId:G(e.runId),leaseProvider:G(e.leaseProvider),deviceKey:G(e.deviceKey)??t},r=Object.entries(n).filter(([,e])=>e!==void 0);return r.length>0?Object.fromEntries(r):void 0}function G(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}async function Kn(e){let{device:t,session:n,command:r,transportError:i,options:a,signal:o,invalidationReason:s}=e;return await qn(await Zn(t,n,r,i,a,o),{command:r,session:n,transportError:i,invalidationReason:s,invalidateSession:e.invalidateSession})}async function qn(e,t){if(!e)return await Xn(t,`status_recovery_unavailable`);if(e.type===`recovered`)return Jn(e,t);if(e.type===`skipInvalidation`)throw Yn(e,t);return await Xn(t,e.reason,e.lifecycleState,e.error)}function Jn(e,t){return J({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.data}function Yn(e,t){return J({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.error}async function Xn(e,t,n,r){throw J({command:e.command,session:e.session,transportError:e.transportError,decision:`retained`,reason:t,lifecycleState:n}),await e.invalidateSession(e.session,e.invalidationReason),r??e.transportError}async function Zn(e,t,n,r,i,a){if(n.command===`status`||!n.commandId?.trim())return;let o=q(r),s;try{s=await U(e,t,{command:`status`,statusCommandId:n.commandId},i.logPath,3e3,a)}catch(e){return b({level:`debug`,phase:`ios_runner_command_status_recovery_failed`,data:{command:n.command,commandId:n.commandId,error:e instanceof Error?e.message:String(e),...o}}),{type:`retainInvalidation`,reason:`status_probe_failed`}}let c=typeof s.lifecycleState==`string`?s.lifecycleState:``;return b({level:`debug`,phase:`ios_runner_command_status_recovery`,data:{command:n.command,commandId:n.commandId,lifecycleState:c,...o}}),Qn(s,c,n,r,i)}function Qn(e,t,r,i,a){return t===`completed`?$n(e,r,i,a):t===`failed`?{type:`skipInvalidation`,reason:`runner_reported_failure`,lifecycleState:t,error:er(e,r,i,a)}:t===`accepted`||t===`started`?{type:`skipInvalidation`,reason:`command_still_in_flight`,lifecycleState:t,error:tr(t,r,i,a)}:{type:`retainInvalidation`,reason:t?`unknown_lifecycle_state`:`missing_lifecycle_state`,lifecycleState:t,error:new n(`COMMAND_FAILED`,`Runner command "${r.command}" lost its transport response and lifecycle status was ${t?`"${t}"`:`missing`}, so agent-device invalidated the runner session instead of replaying the command.`,{command:r.command,commandId:r.commandId,lifecycleState:t,recovery:`lifecycle_state_not_recoverable`,hint:ur(r.command),logPath:a.logPath,transportError:i.message},i)}}function $n(e,t,r,i){let a=nr(e.lifecycleResponseJson);if(a)return{type:`recovered`,data:a,reason:`completed_with_retained_response`,lifecycleState:`completed`};if(M(t))return{type:`skipInvalidation`,error:r,reason:`read_only_completed_without_retained_response`,lifecycleState:`completed`};let o=q(r);return{type:`skipInvalidation`,reason:`completed_without_retained_response`,lifecycleState:`completed`,error:new n(`COMMAND_FAILED`,`Runner command "${t.command}" completed after the transport response was lost, but no recoverable response was retained.`,{command:t.command,commandId:t.commandId,lifecycleState:`completed`,recovery:`completed_without_retained_response`,...o,hint:ir(t.command,o),logPath:i.logPath,transportError:r.message},r)}}function er(e,t,r,i){let a=typeof e.lifecycleErrorCode==`string`?e.lifecycleErrorCode:void 0,o=typeof e.lifecycleErrorMessage==`string`?e.lifecycleErrorMessage:`Runner command failed`,s=typeof e.lifecycleErrorHint==`string`?e.lifecycleErrorHint:void 0,c=q(r),l=lt(a);return new n(l.code,o,{command:t.command,commandId:t.commandId,lifecycleState:`failed`,recovery:`runner_reported_failure`,...l.details,...c,hint:s??ar(t.command,c),logPath:i.logPath,transportError:r.message},r)}function tr(e,t,r,i){if(M(t))return r;let a=q(r);return new n(`COMMAND_FAILED`,`Runner command "${t.command}" is still ${e} after the transport response was lost.`,{command:t.command,commandId:t.commandId,lifecycleState:e,recovery:`command_still_in_flight`,...a,hint:or(t.command,e,a),logPath:i.logPath,transportError:r.message},r)}function nr(e){if(typeof e!=`string`||e.trim().length===0)return;let t=rr(e);if(t.ok)return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:{}}function rr(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{}}function ir(e,t){return`${K(t)}The runner is still reachable and reports "${e}" already completed, so agent-device kept the session open and will not replay it. Run snapshot -i to inspect the current UI, then continue from that observed state.`}function ar(e,t){return`${K(t)}The runner is still reachable and reports "${e}" failed after the transport response was lost, so agent-device kept the session open and did not replay it. Run snapshot -i to inspect the current UI and retry with a selector visible in that snapshot.`}function or(e,t,n){return`${K(n)}The runner is still reachable and reports "${e}" is ${t}, so agent-device kept the session open and will not replay it. Wait briefly, run snapshot -i to inspect the current UI, then continue from that observed state.`}function K(e){return e.readinessPreflightSkipped===!0?`This hot command skipped the uptime preflight because the runner had just completed a healthy interaction; status recovery confirmed the runner still observed it. `:``}function sr(e,t){let n=e.details?.[t];return typeof n==`boolean`?n:void 0}function cr(e,t){let n=e.details?.[t];return typeof n==`string`?n:void 0}function lr(e,t){let n=e.details?.[t];return typeof n==`number`?n:void 0}function q(e){let t={},n=sr(e,`runnerReadinessPreflightSkipped`);n!==void 0&&(t.readinessPreflightSkipped=n);let r=cr(e,`runnerReadinessPreflightSkipReason`);r!==void 0&&(t.readinessPreflightSkipReason=r);let i=lr(e,`runnerReadinessPreflightSkippedAgeMs`);return i!==void 0&&(t.readinessPreflightSkippedAgeMs=i),t}function ur(e){return`The runner did not confirm that "${e}" reached a safe terminal state, so agent-device kept the conservative invalidation path. Run snapshot -i before retrying if the UI may have changed.`}function J(e){let{command:t,session:n,transportError:r,decision:i,reason:a,lifecycleState:o}=e;b({level:i===`retained`?`warn`:`debug`,phase:`ios_runner_command_invalidation_decision`,data:{command:t.command,commandId:t.commandId,decision:i,reason:a,lifecycleState:o,runnerReachable:o!==void 0,sessionId:n.sessionId,transportError:r.message}})}const Y=new Map;function dr(e,t){let n=e.requestId?.trim();if(n)return`request:${n}`;let r=t.commandId?.trim();if(r)return`command:${r}`}function fr(e){if(!e)return;let t=_r(e);t.touchedSession=!0,X(e,t)}function pr(e){return e?Y.get(e)?.touchedSession===!0:!1}function mr(e){if(!e)return!0;let t=_r(e);return t.recycles>=1?(X(e,t),!1):(X(e,t),!0)}function hr(e){if(!e)return;let t=_r(e);t.recycles+=1,X(e,t)}function gr(e,t){return b({level:`warn`,phase:`ios_runner_recycle_budget_exhausted`,data:{command:e.command,commandId:e.commandId,requestId:t.requestId,maxRecycles:1}}),new n(`COMMAND_FAILED`,`iOS runner was already restarted during this request and "${e.command}" still failed, so agent-device stopped instead of paying for another runner boot.`,{command:e.command,commandId:e.commandId,recovery:`runner_recycle_budget_exhausted`,hint:"Check the runner log for the underlying failure before retrying — a provisioning or code-signing error there means the runner cannot install on this device, and no retry will help. If the runner is healthy, the current screen is likely too heavy or animating for accessibility capture: the app session is preserved, so run `screenshot` for visual truth and interact by coordinates, or navigate to another screen.",logPath:t.logPath})}function _r(e){return vr(),Y.get(e)??{touchedSession:!1,recycles:0,lastAtMs:Date.now()}}function X(e,t){t.lastAtMs=Date.now(),Y.delete(e),Y.set(e,t)}function vr(){let e=Date.now()-6e5;for(let[t,n]of Y)n.lastAtMs<e&&Y.delete(t);for(;Y.size>512;){let e=Y.keys().next().value;if(e===void 0)break;Y.delete(e)}}async function yr(e,t){w(t.requestId);let r=C(t),i=S({command:`uptime`}),a;for(let n=1;n<=2;n+=1){let o=await br({device:e,command:i,options:t,signal:r,attempt:n,recoveryReason:a});if(o.kind===`prepared`)return o.result;a=o.recoveryReason}throw new n(`COMMAND_FAILED`,`iOS runner prepare failed`)}async function br(e){let{device:t,command:n,options:r,signal:i,attempt:a,recoveryReason:o}=e,s=Date.now(),c=await L(t,{...r,cleanStaleBundles:a>1||r.cleanStaleBundles,...Or(r,`runner_session`)}),l=Date.now()-s;try{return{kind:`prepared`,result:Pr(t,await Dr(t,c,n,r,i,l,{recoveryReason:o}))}}catch(e){return await xr({device:t,session:c,command:n,options:r,signal:i,attempt:a,error:e})}}async function xr(e){let{device:n,session:r,command:a,options:o,signal:s,attempt:c,error:l}=e,u=i(l,`COMMAND_FAILED`);if(t(u))throw await Z(r,`prepare_runner_request_canceled`),l;if(c===1&&Ar(u,r))return{kind:`prepared`,result:await Sr({device:n,session:r,command:a,options:o,signal:s,error:u})};if(!Cr(u))throw l;let d=u.message||`runner_health_failed`;if(c>=2)throw await Z(r,`prepare_runner_health_failed`),l;return w(o.requestId),await z(r,`prepare_runner_health_retry`),b({level:`warn`,phase:`ios_runner_prepare_health_retry`,data:{command:a.command,commandId:a.commandId,sessionId:r.sessionId,attempt:c,maxAttempts:2,reason:d}}),{kind:`retry`,recoveryReason:d}}async function Sr(e){let{device:t,session:n,command:r,options:i,signal:a,error:o}=e,s=o.message||`runner_health_failed`;await z(n,`prepare_cached_runner_health_failed`),await yt(n.xctestrunArtifact,s);let c=Date.now(),l=await L(t,{...i,cleanStaleBundles:!0,forceRunnerXctestrunRebuild:!0,...Or(i,`runner_rebuild`)}),u=Date.now()-c;try{let e=await Dr(t,l,r,i,a,u,{recoveryReason:s});return b({level:`info`,phase:`ios_runner_prepare_bad_cache_recovered`,data:{command:r.command,commandId:r.commandId,sessionId:l.sessionId,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,reason:s}}),Pr(t,e)}catch(e){await Z(l,`prepare_rebuilt_runner_health_failed`);let n=Mr(e,l,s);throw Fr(t,{cache:l.xctestrunArtifact?.cache,artifact:l.xctestrunArtifact?.artifact,buildMs:l.xctestrunArtifact?.buildMs,connectMs:u,healthCheckMs:0,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,failureReason:n.message}),n}}async function Z(e,t){try{await z(e,t)}catch{}}function Cr(e){return t(e)?!1:x(e)||$e(e)||jr(e)}async function wr(e,n,r){w(r.requestId);let a=C(r),o=dr(r,n),s,c=!1;try{if(!R(e.id)?.alive&&pr(o)){if(!mr(o))throw gr(n,r);c=!0}s=await L(e,r),un(s,r.expectedRunnerSessionId),yn(s,n),c&&hr(o),fr(o);let t=s.ready?tt:Un(s);return await U(e,s,n,r.logPath,t,a)}catch(o){if(r.expectedRunnerSessionId!==void 0)throw o;let c=i(o,`COMMAND_FAILED`);if(s&&!s.ready&&t(c))throw await Z(s,`runner_startup_request_canceled`),o;if(Qe(c)&&s)return w(r.requestId),await Tr({device:e,session:s,command:n,options:r,signal:a,restartReason:`runner_connect_failed_before_command_send`});if(s&&Lr(c))return w(r.requestId),await Tr({device:e,session:s,command:n,options:r,signal:a,restartReason:`runner_readiness_preflight_failed_before_command_send`,recoveredDiagnosticPhase:`ios_runner_readiness_preflight_recovered`});if(s&&x(c))return await Kn({device:e,session:s,command:n,transportError:c,options:r,signal:a,invalidationReason:`transport_error_after_command_send`,invalidateSession:z});throw o}}async function Tr(e){let{device:t,command:n,options:r,signal:a,restartReason:o}=e,s=dr(r,n);if(!mr(s))throw gr(n,r);await z(e.session,o);let c=await L(t,{...r,cleanStaleBundles:!0}).catch(t=>{throw Er(t,e)});hr(s);try{let i=await U(t,c,n,r.logPath,Je,a);return e.recoveredDiagnosticPhase&&b({level:`debug`,phase:e.recoveredDiagnosticPhase,data:{command:n.command,commandId:n.commandId,recovery:`session_restarted`,sessionId:c.sessionId}}),i}catch(o){let s=i(o,`COMMAND_FAILED`);if(x(s))try{return await Kn({device:t,session:c,command:n,transportError:s,options:r,signal:a,invalidationReason:`transport_error_after_retry_command_send`,invalidateSession:z})}catch(t){throw Er(t,e,c)}throw Er(o,e,c)}}function Er(e,t,r){return e instanceof n?new n(e.code,e.message,{...e.details??{},runnerRestarted:!0,runnerRestartReason:t.restartReason,runnerRestartCommand:t.command.command,...t.command.commandId?{runnerRestartCommandId:t.command.commandId}:{},runnerInvalidatedSessionId:t.session.sessionId,...r?{runnerRestartSessionId:r.sessionId}:{},...e.details?.logPath===void 0&&t.options.logPath?{logPath:t.options.logPath}:{}},e.cause??e):e}async function Dr(e,t,n,r,i,a,o){let s=Date.now(),c=kr(r.prepareDeadline,r.healthTimeoutMs,`runner_health`);return Nr(await U(e,t,n,r.logPath,c,i),t,a,Date.now()-s,o)}function Or(e,t){if(!e.prepareDeadline)return{};let n=kr(e.prepareDeadline,e.buildTimeoutMs,t);return{buildTimeoutMs:n,startupTimeoutMs:n}}function kr(e,t,r){if(!e)return t??45e3;let i=Math.floor(e.remainingMs());if(i<=0)throw new n(`COMMAND_FAILED`,`prepare ios-runner timed out`,{phase:r,reason:`prepare_deadline_expired`});return i}function Ar(e,t){let n=t.xctestrunArtifact;return!n||n.cache===`miss`?!1:Cr(e)}function jr(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)||t.includes(`deadline`)}function Mr(e,t,r){let a=i(e,`COMMAND_FAILED`);return new n(a.code,`artifact restored but runner did not connect`,{...a.details??{},restoredFailureReason:r,xctestrunPath:t.xctestrunArtifact?.xctestrunPath,artifact:t.xctestrunArtifact?.artifact,cache:t.xctestrunArtifact?.cache,reason:a.message},a)}function Nr(e,t,n,r,i){let a=t.xctestrunArtifact,o={...i?.recoveryReason?{recoveryReason:i.recoveryReason}:{},...i?.failureReason?{failureReason:i.failureReason}:{}};return a?{runner:e,cache:a.cache,artifact:a.artifact,buildMs:a.buildMs,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),xctestrunPath:a.xctestrunPath,...o}:{runner:e,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),...o}}function Pr(e,t){return Fr(e,t),t}function Fr(e,t){b({level:t.failureReason?`warn`:`info`,phase:`apple_runner_prepare`,data:{platform:e.platform,target:e.target,deviceId:e.id,cache:t.cache,artifact:t.artifact,buildMs:t.buildMs,connectMs:t.connectMs,healthCheckMs:t.healthCheckMs,timingContainment:t.buildMs===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},xctestrunPath:t.xctestrunPath,recoveryReason:t.recoveryReason,failureReason:t.failureReason}})}function Ir(e){return e.details?.runnerReadinessPreflightFailed===!0}function Lr(e){return Ir(e)&&(x(e)||Rr(e))}function Rr(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)}async function zr(e,t,n={}){Dn(e),w(n.requestId);let r=S(t),i=Q(e,n);return M(r)?Fe(()=>(w(n.requestId),i.runCommand(e,r,n)),{shouldRetry:e=>(w(n.requestId),x(e))}):i.runCommand(e,r,n)}async function Br(e,t={}){if(s(e))try{await zr(e,{command:`targetReset`},t)}catch(t){b({level:`warn`,phase:`ios_runner_target_reset_failed`,data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}}),await H(e.id)}}function Vr(e,t={}){if(s(e))return Ur({device:e,options:t,failurePhase:`ios_runner_cache_prewarm_failed`,task:async t=>{await _t(e,{...t,budget:y(t.buildTimeoutMs,t.signal)})}})}function Hr(e,t={}){if(!s(e))return;let n=Q(e,t).prewarm;if(!n){b({level:`debug`,phase:`ios_runner_session_prewarm_unavailable`,data:{deviceId:e.id}});return}return Ur({device:e,options:t,failurePhase:`ios_runner_session_prewarm_failed`,task:async t=>{await n(e,t)}})}function Ur(e){let{device:t,options:n,failurePhase:r,task:i}=e,{propagateError:a=!1,...o}=n;return i(o).catch(e=>{if(b({level:`warn`,phase:r,data:{deviceId:t.id,error:e instanceof Error?e.message:String(e)}}),a)throw e})}async function Wr(e,t){Dn(e),w(t.requestId);let n=S({command:`uptime`}),r=Q(e,t);if(r.prepare)return await r.prepare(e,t);let i=Date.now();return{runner:await r.runCommand(e,n,t),connectMs:0,healthCheckMs:Math.max(0,Date.now()-i)}}function Q(e,t){return Oe(e,qr,void 0,{requestId:t.requestId})}function Gr(e,t={}){return s(e)?Q(e,t).hasLiveSession(e):!1}async function Kr(e,t={}){if(!s(e))return!1;let n=Q(e,t).releaseSpeculativeSession;return n?await n(e):!1}const qr=Ee(wr,{prepare:yr,hasLiveSession:e=>{let t=R(e.id);return t!==null&&t.alive&&t.ready},releaseSpeculativeSession:async e=>await bn(e.id),prewarm:async(e,t)=>{let{healthCheck:n,...r}=t;if(n===!1){await L(e,{...r,speculative:!0});return}await yr(e,{...r,speculative:!0,healthTimeoutMs:tt})}});function Jr(e){return Ke(e),{runAppleRunnerCommand:zr,notifyIosRunnerAppRelaunched:Br,hasLiveIosRunnerSession:Gr,releaseSpeculativeIosRunnerSessionFor:Kr,prewarmAppleRunnerCache:Vr,prewarmIosRunnerSession:Hr,prepareIosRunner:Wr,resolveRunnerAppBundleId:Re,hasCachedAppleRunnerArtifact:bt,detachIosSimulatorRunnerSessionsForShutdown:Sn,getRunnerSessionSnapshot:R,scheduleIosRunnerIdleStop:_n,stopIosRunnerSession:H,stopAllIosRunnerSessions:Cn,runApplePressSeries:De,cleanupRunnerLeasesForOwner:it,readStaleRunnerLease:mt,verifyLeaseRunnerPidIdentity:D,runnerLeaseCleanupAdapter:pt,applyXctestRunnerAppIconFromDerivedPath:nt}}const Yr={runCmdStreaming:re,runCmdSync:ae,runCmdBackground:ie,requireExecSuccess:ne,isCommandTimeoutError:oe,emitDiagnostic:u,withDiagnosticTimer:l,retryWithPolicy:ce,isEnvTruthy:ue,deadlineFromTimeoutMs:(e,t)=>le.fromTimeoutMs(e,t),isProcessAlive:h,isProcessGroupAlive:m,readProcessStartTime:g,readProcessCommand:te,signalPidsBestEffort:p,signalProcessGroupBestEffort:d,findProjectRoot:de,readVersion:fe,acquireProcessLock:se,withKeyedLock:ge,publishFileSync:f,classifyOwnerLiveness:ee,createTtlMemo:pe,parseBooleanLiteral:c,isRecord:a,resolveIosSimulatorDeviceSetPath:be,emitRequestProgress:ye,getRequestSignal:ve,isRequestCanceled:_e,classifyBootFailure:me,bootFailureHint:he,runAppleToolCommand:xe,runXcrun:Se,readApplePlistJson:Ce,buildSimctlArgsForDevice:Te,resolveIosPhysicalDeviceControl:we,visitXmlPlistEntries:xt,leaseOwnerStateDir:St,hasDeviceClaimAuthority:e=>Ct()?.(e)??!1};var Xr=e({applyXctestRunnerAppIconFromDerivedPath:()=>hi,cleanupRunnerLeasesForOwner:()=>fi,detachIosSimulatorRunnerSessionsForShutdown:()=>oi,getRunnerSessionSnapshot:()=>si,hasCachedAppleRunnerArtifact:()=>ai,hasLiveIosRunnerSession:()=>$r,notifyIosRunnerAppRelaunched:()=>Qr,prepareIosRunner:()=>ri,prewarmAppleRunnerCache:()=>ti,prewarmIosRunnerSession:()=>ni,readStaleRunnerLease:()=>pi,releaseSpeculativeIosRunnerSessionFor:()=>ei,resolveRunnerAppBundleId:()=>ii,runApplePressSeries:()=>di,runAppleRunnerCommand:()=>Zr,scheduleIosRunnerIdleStop:()=>ci,stopAllIosRunnerSessions:()=>ui,stopIosRunnerSession:()=>li,verifyLeaseRunnerPidIdentity:()=>mi});const $=Jr(Yr),Zr=$.runAppleRunnerCommand,Qr=$.notifyIosRunnerAppRelaunched,$r=$.hasLiveIosRunnerSession,ei=$.releaseSpeculativeIosRunnerSessionFor,ti=$.prewarmAppleRunnerCache,ni=$.prewarmIosRunnerSession,ri=$.prepareIosRunner,ii=$.resolveRunnerAppBundleId,ai=$.hasCachedAppleRunnerArtifact,oi=$.detachIosSimulatorRunnerSessionsForShutdown,si=$.getRunnerSessionSnapshot,ci=$.scheduleIosRunnerIdleStop,li=$.stopIosRunnerSession,ui=$.stopAllIosRunnerSessions,di=$.runApplePressSeries,fi=$.cleanupRunnerLeasesForOwner,pi=$.readStaleRunnerLease,mi=$.verifyLeaseRunnerPidIdentity,hi=$.applyXctestRunnerAppIconFromDerivedPath;export{ui as _,$r as a,ti as c,ei as d,ii as f,ci as g,Xr as h,ai as i,ni as l,Zr as m,oi as n,Qr as o,di as p,si as r,ri as s,hi as t,pi as u,li as v,mi as y};