agent-device 0.21.6 → 0.21.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.6.apk → agent-device-android-ime-helper-0.21.7.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.7.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.6.manifest.json → agent-device-android-ime-helper-0.21.7.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.6.apk → agent-device-android-snapshot-helper-0.21.7.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.7.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.6.manifest.json → agent-device-android-snapshot-helper-0.21.7.manifest.json} +6 -6
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +4 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +1 -2
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +25 -12
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +56 -1
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -1
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +36 -108
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +241 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +29 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +46 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +85 -26
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +134 -117
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +1 -3
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +25 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +1 -1
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +3 -0
  23. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotCoordinateSpace.swift +197 -0
  24. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +30 -4
  25. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +0 -81
  26. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationInvariant.swift +1 -9
  27. package/dist/src/absence-observation-errors.js +1 -1
  28. package/dist/src/adapter.js +1 -1
  29. package/dist/src/adb-executor.js +2 -2
  30. package/dist/src/adb-failure.js +1 -1
  31. package/dist/src/adb-transport.js +1 -1
  32. package/dist/src/adb.js +1 -1
  33. package/dist/src/agent-browser-lifecycle.js +1 -1
  34. package/dist/src/agent-browser-process-record.js +1 -1
  35. package/dist/src/agent-browser-provider.js +1 -1
  36. package/dist/src/agent-browser-tool.js +1 -1
  37. package/dist/src/agent-device-client.js +2 -2
  38. package/dist/src/ai-sdk.js +1 -1
  39. package/dist/src/alert-runtime.js +1 -1
  40. package/dist/src/android-adb.d.ts +29 -2
  41. package/dist/src/android-adb.js +1 -1
  42. package/dist/src/android-input-ownership.js +1 -1
  43. package/dist/src/android.js +1 -1
  44. package/dist/src/app-catalog.js +1 -1
  45. package/dist/src/app-deployment-resolution.js +1 -1
  46. package/dist/src/app-helpers.js +1 -1
  47. package/dist/src/app-inventory.js +1 -1
  48. package/dist/src/app-launch.js +2 -2
  49. package/dist/src/app-lifecycle.js +2 -2
  50. package/dist/src/app-lifecycle2.js +2 -2
  51. package/dist/src/app-log-files.js +1 -1
  52. package/dist/src/app-log-runtime2.js +3 -3
  53. package/dist/src/app-resolution.js +2 -2
  54. package/dist/src/app-state.js +1 -1
  55. package/dist/src/apple-runner-platform.js +1 -1
  56. package/dist/src/application-lifecycle-interaction.js +1 -1
  57. package/dist/src/archive.js +1 -1
  58. package/dist/src/artifact-download.js +1 -1
  59. package/dist/src/auth-session.js +1 -1
  60. package/dist/src/auth.js +1 -1
  61. package/dist/src/back-mode.js +1 -1
  62. package/dist/src/backend-snapshot-options.js +1 -1
  63. package/dist/src/boot-diagnostics.js +1 -1
  64. package/dist/src/capture-disclosure.js +1 -0
  65. package/dist/src/capture.js +1 -1
  66. package/dist/src/cli-config.js +1 -1
  67. package/dist/src/cli-help.js +15 -2
  68. package/dist/src/cli-output.js +1 -1
  69. package/dist/src/cli.js +4 -4
  70. package/dist/src/click-button.js +1 -1
  71. package/dist/src/client-metro.js +1 -1
  72. package/dist/src/client-types.d.ts +32 -2
  73. package/dist/src/clipboard-shell-response.js +1 -0
  74. package/dist/src/command-schema.js +1 -1
  75. package/dist/src/command-tools.js +4 -2
  76. package/dist/src/command.js +1 -1
  77. package/dist/src/config.js +1 -1
  78. package/dist/src/connection-runtime.js +1 -1
  79. package/dist/src/connection.js +1 -1
  80. package/dist/src/contracts.d.ts +1 -1
  81. package/dist/src/contracts.js +1 -1
  82. package/dist/src/daemon-client-lifecycle.js +1 -1
  83. package/dist/src/daemon.js +1 -1
  84. package/dist/src/debug-symbols-facade.js +1 -1
  85. package/dist/src/device-boot.js +1 -1
  86. package/dist/src/device-claim-inspection.js +1 -1
  87. package/dist/src/device-claim-rule.js +2 -1
  88. package/dist/src/device-input-state.d.ts +4 -4
  89. package/dist/src/device-inventory-context.js +1 -1
  90. package/dist/src/device-rotation.js +1 -1
  91. package/dist/src/device-selection-resolver.js +1 -1
  92. package/dist/src/device-session.js +1 -1
  93. package/dist/src/device-shell.js +1 -0
  94. package/dist/src/device.js +1 -1
  95. package/dist/src/device2.js +1 -1
  96. package/dist/src/devicectl.js +1 -0
  97. package/dist/src/diagnostics.js +1 -1
  98. package/dist/src/dispatch-resolve.js +1 -1
  99. package/dist/src/display-inventory.js +1 -0
  100. package/dist/src/doctor-facade.js +1 -1
  101. package/dist/src/doctor2.js +1 -1
  102. package/dist/src/durable-resource.js +1 -1
  103. package/dist/src/engine-eval-script.js +1 -1
  104. package/dist/src/error.js +1 -1
  105. package/dist/src/exec.js +1 -1
  106. package/dist/src/file.js +1 -1
  107. package/dist/src/find.js +1 -1
  108. package/dist/src/finders.js +1 -1
  109. package/dist/src/format.js +2 -1
  110. package/dist/src/generic.js +1 -1
  111. package/dist/src/gesture-admission.js +1 -1
  112. package/dist/src/gesture-plan.js +1 -1
  113. package/dist/src/gesture-runtime.js +1 -1
  114. package/dist/src/harmonyos.js +1 -1
  115. package/dist/src/hdc.js +1 -1
  116. package/dist/src/helper.js +1 -1
  117. package/dist/src/human-control-contract.js +1 -1
  118. package/dist/src/human-control.js +1 -1
  119. package/dist/src/index.d.ts +1 -1
  120. package/dist/src/index.js +1 -1
  121. package/dist/src/input-actions.js +1 -1
  122. package/dist/src/input-actions2.js +1 -1
  123. package/dist/src/install-artifact-facade.js +1 -1
  124. package/dist/src/install-source-network-transport.js +1 -1
  125. package/dist/src/install-source2.js +1 -1
  126. package/dist/src/interaction-positionals.js +1 -1
  127. package/dist/src/interaction-ref-policy.js +1 -1
  128. package/dist/src/interaction.js +1 -1
  129. package/dist/src/interaction2.js +1 -1
  130. package/dist/src/interactor-operation-catalog.js +1 -1
  131. package/dist/src/interactor.js +5 -5
  132. package/dist/src/interactor2.js +1 -1
  133. package/dist/src/interactors.js +1 -1
  134. package/dist/src/internal/bin.js +1 -1
  135. package/dist/src/internal/daemon.js +2 -2
  136. package/dist/src/internal/png-worker.d.ts +4 -1
  137. package/dist/src/internal/png-worker.js +1 -1
  138. package/dist/src/internal/run-script-http-child.js +1 -1
  139. package/dist/src/inventory.js +4 -4
  140. package/dist/src/inventory2.js +1 -1
  141. package/dist/src/inventory3.js +2 -2
  142. package/dist/src/inventory5.js +1 -1
  143. package/dist/src/ios-snapshot-acquisition.js +1 -1
  144. package/dist/src/ios-snapshot-runtime.js +1 -1
  145. package/dist/src/ios-target-activation.js +1 -0
  146. package/dist/src/lease-context.js +1 -1
  147. package/dist/src/lease-scope.js +1 -1
  148. package/dist/src/lease.js +1 -1
  149. package/dist/src/limrun-download-file.js +1 -0
  150. package/dist/src/limrun-runtime-dependencies.js +1 -1
  151. package/dist/src/limrun.d.ts +10 -4
  152. package/dist/src/linux.js +1 -1
  153. package/dist/src/local-interactor-operation-set.js +1 -1
  154. package/dist/src/location-coordinates.js +1 -1
  155. package/dist/src/managed-device-scope.js +1 -1
  156. package/dist/src/mechanics.js +16 -16
  157. package/dist/src/mobile-snapshot-semantics.js +1 -1
  158. package/dist/src/multitouch-support.js +1 -1
  159. package/dist/src/observation.js +2 -2
  160. package/dist/src/output-common.js +5 -2
  161. package/dist/src/parameterized-recorded-fill.js +1 -1
  162. package/dist/src/perf-facade.js +2 -2
  163. package/dist/src/perf-runtime-operation-builder.js +1 -1
  164. package/dist/src/perf-runtime-plan.js +1 -1
  165. package/dist/src/perf.js +1 -1
  166. package/dist/src/physical-device-control.js +1 -1
  167. package/dist/src/platform-request-scope.js +1 -1
  168. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  169. package/dist/src/platform-runtime-host.js +1 -1
  170. package/dist/src/platform-runtime-managed-owner.js +1 -1
  171. package/dist/src/platform-runtime-open-target.js +1 -1
  172. package/dist/src/platform-runtime-operation-host.js +4 -4
  173. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  174. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  175. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  176. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  177. package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -1
  178. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  179. package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
  180. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  181. package/dist/src/platform-runtime-unavailable.js +1 -1
  182. package/dist/src/platform-runtime.js +1 -1
  183. package/dist/src/platform-runtime2.js +1 -1
  184. package/dist/src/png-crop-bytes.js +1 -1
  185. package/dist/src/png-transcode.js +1 -0
  186. package/dist/src/png-worker-client.js +1 -0
  187. package/dist/src/png.js +1 -1
  188. package/dist/src/prepare-kind.js +1 -1
  189. package/dist/src/provider-session-ownership.js +1 -1
  190. package/dist/src/provider-webdriver.js +1 -1
  191. package/dist/src/proxy.js +1 -1
  192. package/dist/src/quality-warnings.js +1 -1
  193. package/dist/src/react-native.js +1 -1
  194. package/dist/src/record-runtime.js +1 -1
  195. package/dist/src/record-trace.js +1 -1
  196. package/dist/src/rect-center.js +1 -1
  197. package/dist/src/register-builtins.js +1 -1
  198. package/dist/src/registry.js +35 -35
  199. package/dist/src/remote-config2.js +1 -1
  200. package/dist/src/replay-divergence.js +1 -1
  201. package/dist/src/replay.js +2 -2
  202. package/dist/src/reporting.js +1 -1
  203. package/dist/src/request-admission.js +1 -1
  204. package/dist/src/request-cancel.js +1 -1
  205. package/dist/src/request-runtime-binding.js +1 -1
  206. package/dist/src/result-serialization.js +1 -1
  207. package/dist/src/retry.js +1 -1
  208. package/dist/src/runner-cache-metadata.js +2 -2
  209. package/dist/src/runner-client.js +1 -1
  210. package/dist/src/runner-disposal.js +1 -1
  211. package/dist/src/runner-operations-facade.js +1 -1
  212. package/dist/src/runner-presentation.js +1 -1
  213. package/dist/src/runner.js +1 -1
  214. package/dist/src/runtime-transport-hints.js +1 -1
  215. package/dist/src/runtime.js +3 -3
  216. package/dist/src/runtime10.js +1 -1
  217. package/dist/src/runtime2.js +4 -4
  218. package/dist/src/runtime3.js +1 -1
  219. package/dist/src/runtime4.js +5 -5
  220. package/dist/src/runtime5.js +1 -1
  221. package/dist/src/runtime6.js +1 -1
  222. package/dist/src/runtime7.js +1 -1
  223. package/dist/src/runtime8.js +1 -1
  224. package/dist/src/runtime9.js +1 -1
  225. package/dist/src/screen-recording-admission-ledger.js +1 -0
  226. package/dist/src/screen-recording-completion.js +1 -1
  227. package/dist/src/screen-recording-options.js +1 -1
  228. package/dist/src/screen-recording-resource-recovery.js +1 -1
  229. package/dist/src/screen-recording-transport.js +1 -0
  230. package/dist/src/screenshot-density.js +1 -1
  231. package/dist/src/screenshot-runtime.js +1 -1
  232. package/dist/src/screenshot.js +1 -1
  233. package/dist/src/screenshot3.js +1 -1
  234. package/dist/src/script.js +1 -1
  235. package/dist/src/scroll-command.js +1 -1
  236. package/dist/src/scroll-gesture.js +1 -1
  237. package/dist/src/sdk-batch-runner.js +2 -2
  238. package/dist/src/sdk-batch.js +2 -2
  239. package/dist/src/sdk-contracts.d.ts +76 -1
  240. package/dist/src/sdk-contracts.js +1 -1
  241. package/dist/src/sdk-device.js +1 -1
  242. package/dist/src/sdk-finders.d.ts +1 -1
  243. package/dist/src/sdk-finders.js +1 -1
  244. package/dist/src/sdk-io.js +1 -1
  245. package/dist/src/sdk-remote-config.js +1 -1
  246. package/dist/src/sdk-selectors.d.ts +18 -1
  247. package/dist/src/sdk-selectors.js +1 -1
  248. package/dist/src/selection.js +0 -0
  249. package/dist/src/selector-runtime.js +1 -1
  250. package/dist/src/selectors.js +1 -1
  251. package/dist/src/semantic-index.js +1 -1
  252. package/dist/src/server.js +1 -1
  253. package/dist/src/session-allocation.js +1 -1
  254. package/dist/src/session-observation.js +1 -1
  255. package/dist/src/session-routing.js +1 -1
  256. package/dist/src/session-runtime-admission.js +1 -1
  257. package/dist/src/session-snapshot.js +1 -1
  258. package/dist/src/session-store.js +3 -3
  259. package/dist/src/session2.js +4 -5
  260. package/dist/src/settings.js +1 -1
  261. package/dist/src/simctl-facade.js +1 -1
  262. package/dist/src/simctl.js +1 -1
  263. package/dist/src/simulator-boot.js +1 -1
  264. package/dist/src/simulator.js +1 -1
  265. package/dist/src/snapshot-capture-annotations.js +1 -1
  266. package/dist/src/snapshot-diagnostics.js +1 -1
  267. package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
  268. package/dist/src/snapshot-runtime-binding.js +1 -1
  269. package/dist/src/snapshot-runtime.js +1 -1
  270. package/dist/src/snapshot-state.js +1 -1
  271. package/dist/src/snapshot.js +1 -1
  272. package/dist/src/snapshot2.js +1 -1
  273. package/dist/src/snapshot3.js +1 -1
  274. package/dist/src/snapshot4.js +1 -1
  275. package/dist/src/src.js +1 -1
  276. package/dist/src/src4.js +1 -1
  277. package/dist/src/src7.js +1 -1
  278. package/dist/src/src8.js +1 -1
  279. package/dist/src/stop-sequence.js +1 -1
  280. package/dist/src/string-enum.js +1 -1
  281. package/dist/src/takeover.js +1 -1
  282. package/dist/src/text-entry-focus.js +1 -1
  283. package/dist/src/tool-provider.js +1 -1
  284. package/dist/src/tool-provider2.js +1 -1
  285. package/dist/src/touch-runtime.js +1 -1
  286. package/dist/src/transport.js +1 -1
  287. package/dist/src/tree.js +1 -1
  288. package/dist/src/tv-remote.js +1 -1
  289. package/dist/src/type-text-runtime.js +1 -1
  290. package/dist/src/verified-file.js +1 -1
  291. package/dist/src/video.js +1 -1
  292. package/dist/src/viewport.js +1 -1
  293. package/dist/src/web.js +1 -1
  294. package/dist/src/web2.js +1 -1
  295. package/dist/src/webdriver-source.js +1 -1
  296. package/dist/src/window-state.js +1 -1
  297. package/package.json +2 -1
  298. package/server.json +2 -2
  299. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.6.apk.sha256 +0 -1
  300. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.6.apk.sha256 +0 -1
  301. package/dist/src/session-target-evidence.js +0 -1
  302. package/dist/src/vars.js +0 -2
@@ -1 +1,2 @@
1
- import{C as e,T as t,o as n,w as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./sdk-batch-runner.js";import{p as a}from"./android-input-ownership.js";import{c as o,l as s,o as c,v as l}from"./sdk-device.js";import{d as u,l as d,n as f,r as p}from"./lease-scope.js";import{Mr as m,Sr as h,Tr as ee,Wt as te,Xt as ne,Yt as re,tr as ie,zr as g}from"./sdk-batch.js";import{a as ae,n as oe,r as se}from"./script.js";import"./session-store.js";import{r as ce}from"./format.js";import{r as _}from"./diagnostics.js";import"./diagnostics2.js";import{r as le}from"./command.js";import{n as v}from"./runtime-transport-hints.js";import{_ as ue,a as de,c as fe,d as y,f as b,g as pe,h as me,i as he,l as ge,m as _e,n as x,o as ve,p as ye,r as be,s as S,u as xe,v as Se}from"./human-control-contract.js";import{n as Ce,t as we,u as Te}from"./provider-session-ownership.js";import{i as Ee}from"./request-runtime-binding.js";import{r as De}from"./application-lifecycle-runtime.js";import{a as Oe,c as C,l as ke,n as Ae,o as je,r as Me,t as Ne}from"./device-claim-inspection.js";import{b as Pe,c as Fe,g as Ie,i as Le,p as Re,x as w}from"./perf-runtime-plan.js";import{n as ze,r as Be,t as Ve}from"./lease-context.js";import{d as He,g as Ue,u as We}from"./screenshot-runtime.js";import{a as Ge,c as Ke,d as T,l as qe,n as Je,o as Ye,r as Xe,u as E}from"./src8.js";import{n as Ze,t as Qe}from"./compatibility-policy.js";import{o as $e}from"./screen-recording-resource-recovery.js";import D from"node:path";import"node:fs";import et,{createHash as tt}from"node:crypto";import nt from"node:os";import O from"node:fs/promises";function rt(t,n){if(n?.replayBackend&&n.replayBackend!==`maestro`)throw new e(`INVALID_ARGS`,`Unsupported replay backend "${n.replayBackend}".`);return{...oe(t),metadata:se(t)}}function it(e,t){return k(e,t)?t:`${e}:${t}`}function k(e,t){return t.startsWith(`${e}:`)}function at(e,t){return!e.partitioned||k(e.tenant,t)}var ot=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},st=class{entriesByLeaseId=new Map;retain(e,t){let n={wanted:t,released:!1},r=this.entriesByLeaseId.get(e)??new Set;return r.add(n),this.entriesByLeaseId.set(e,r),{leaseId:e,release:()=>this.releasePass(e,r,n)}}forget(e){let t=this.entriesByLeaseId.get(e);if(t){for(let e of t)e.released=!0;this.entriesByLeaseId.delete(e)}}isDeferred(e){let t=this.entriesByLeaseId.get(e);if(!t)return!1;for(let e of t)e.wanted()||t.delete(e);return t.size>0||(this.entriesByLeaseId.delete(e),!1)}releasePass(e,t,n){return!n.released&&(n.released=!0,t.delete(n),t.size===0&&this.entriesByLeaseId.delete(e),n.wanted())}},ct=class{holdsByDevice=new Map;mutations=new ot;inFlightWork=new st;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=ge(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new we({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=ye(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=fe(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=b(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw xe(i);return S(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=pe(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);ve(n,e),S(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}retainLeaseWork(e,t){let n=this.inFlightWork.retain(e.leaseId,t);return{leaseId:n.leaseId,release:()=>{let t=n.release();return t&&this.refreshProtectedLease(e.leaseId,this.now()),t}}}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),this.inFlightWork.forget(t.leaseId),{released:!0,lease:t}):{released:!1}}getLease(e){let t=pe(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return ve(n,e),S(n,e),{...n}}assertLeaseAdmission(e){let t=_e(e);this.cleanupExpiredLeases(),S(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?y(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>x(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=he(n),o=de(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=y(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),y(l.hold.scope)!==c))throw new e(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...t.kind===`lease`?{ownerLeaseId:t.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(t,n,r,i){let a=this.holdsByDevice.get(t),{id:o}=n.hold;try{if(await this.mutations.wait(t,i),i?.throwIfAborted(),a.get(o)!==n)throw new e(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return n.hold={...n.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(t,s),x(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=he(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=y(r.hold.scope);return this.deleteHumanControlHold(i,n),x(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=y(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw be(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=y(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(t){let n=this.getActiveLease(t);if(!n.deviceKey)throw new e(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...n,deviceKey:n.deviceKey}}resolveHumanControlScope(t,n){if(t.kind===`host`){if(!n.scope)throw new e(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return n.scope}if(n.scope)throw new e(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(t.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(t,n){if(t.kind===`host`)return;let r=this.requireHumanControlLease(t.leaseId);if(n.ownerLeaseId!==r.leaseId||y(r)!==y(n.hold.scope))throw new e(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=y(e);return t!==void 0&&this.holdsByDevice.has(t)}isLeaseProtected(e,t){return e.expiresAt>t||this.hasHumanControl(e)||this.inFlightWork.isDeferred(e.leaseId)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){this.refreshProtectedLease(this.deviceBindings.get(e),t)}refreshProtectedLease(e,t){let n=e?this.leases.get(e):void 0;n&&this.refreshLease(n,n.expiresAt-n.heartbeatAt,Math.max(t,n.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(this.isLeaseProtected(n,e))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=me(e);if(!t)return;let n=this.leases.get(t);if(!n||this.isLeaseProtected(n,this.now()))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(t){if(t!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let n=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(n<this.maxActiveSimulatorLeases))throw new e(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:n,maxActiveLeases:this.maxActiveSimulatorLeases,backend:t,hint:`Retry after releasing another simulator lease.`})}getActiveLease(t){let n=this.leases.get(t);if(n)return n;throw new e(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(b(e),e.leaseId);let t=y(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(b(e));let n=y(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=y({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw xe(r)}};function lt(t){let n=Se(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=ue(r);if(r&&!i)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n!==`tenant`)return t;if(!i)throw new e(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=t.session||`default`;return k(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:it(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function ut(t,n,r,i={}){if(He(t.command))return;let a=ze(t);pt(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&dt(t,i.providerAppCatalog))return;if(t.command===`human_control`&&!o&&!a.leaseId)throw new e(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(t.command!==`human_control`&&!o&&t.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;mt(a,o);let s=Be(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(p(s)?3e5:void 0)};n.assertLeaseAdmission(d(s));let l=n.heartbeatLease(d(c));return We(t)&&n.assertHumanControlAdmission(l),l}function dt(e,t){let n=Ue(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function ft(e){He(e.command)||pt(e,ze(e))}function pt(t,n){if(t.command!==`open`)return;let r=f(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function mt(e,t){t&&(A(`leaseId`,e.leaseId,t.leaseId),A(`tenantId`,e.tenantId,t.tenantId),A(`runId`,e.runId,t.runId),A(`leaseProvider`,e.leaseProvider,t.leaseProvider),A(`clientId`,e.clientId,t.clientId),A(`deviceKey`,e.deviceKey,t.deviceKey))}function A(t,n,r){if(!(!n||!r||n===r))throw new e(`UNAUTHORIZED`,`Lease does not match session owner (${t})`,{reason:`LEASE_SESSION_MISMATCH`,field:t})}async function ht(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),_({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return _({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function gt(e){ft(e)}async function _t(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(_({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{_({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await Pe(t.deviceClaim).catch(e=>{_({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function vt(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=ut(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function yt(e){return Ve(e.req,e.req.internal?.admittedLease)??e.existingLease}async function bt(e){let t=e.session.lease;if(!t)return;let n=u({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=Ce(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return _({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const xt=[`platform`,`target`],St=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function Ct(e){return c({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function wt(e){return Ct(e)||Dt(e,xt)}function Tt(e){return wt(e)||Dt(e,St)}function Et(e){return typeof e==`string`&&e.trim().length>0}function Dt(e,t){return e?t.some(t=>Et(e[t])):!1}function Ot(e){return{appleSimulatorAppTarget:kt(e)}}function kt(e){return e&&!i(e)?e:void 0}function At(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return tt(`sha256`).update(ie(t),`utf8`).digest(`hex`)}function jt(e,t,n){return new Bt(Nt(Mt(t.resolve(e))),n).parse()}function Mt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Nt(t){let n=[],r=0;for(;r<t.length;){let i=t.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Pt(i);if(!o)throw new e(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);n.push(o.value),r+=o.length}return n}function Pt(e){return Ft(e)??It(e)??Lt(e)??Rt(e)??zt(e)}function Ft(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function It(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Lt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Rt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function zt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Bt=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let t=this.parseOr();if(this.peek())throw new e(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return t}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let t=this.peek();if(!t)throw new e(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(t.type===`boolean`)return this.index+=1,t.value;if(t.type===`paren`&&t.value===`(`){this.index+=1;let t=this.parseOr();if(!this.consumeParen(`)`))throw new e(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return t}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new e(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let t=this.peek();if(t?.type!==`operator`||t.value!==`==`&&t.value!==`!=`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,t}consumeStringLiteral(){let t=this.peek();if(t?.type!==`string`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,t.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Vt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Ht(e,t){return{...N(e,t),source:e.source}}function j(t,n,r){if(t===void 0)return;let i=r??Ge[n]??{},a=Ye(i),o;if(typeof t==`number`)o=t;else{let r=t.trim();if(r===``)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);return o}function Ut(e,t,n,r){return j(e===void 0?t:n.resolve(String(e)),r)}function M(e){if(e?.aborted)throw t()}async function Wt(t,n){if(t.include.kind===`commands`)return{kind:`program`,source:t.source,config:{},commands:t.include.commands};if(!n.loadProgram)throw new e(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return M(n.signal),n.signal?await n.loadProgram(t.include.path,t.source.path,n.signal):await n.loadProgram(t.include.path,t.source.path)}function Gt(e,t){if(e.include.kind===`file`)return D.resolve(t?D.dirname(t):process.cwd(),e.include.path)}function Kt(e){return e===void 0?void 0:D.resolve(e)}function qt(t,n){let r=Gt(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Jt(t,n,r,i){let a=t.include.kind===`file`?Kt(n.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Yt(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:jt(e.true,t,n.platform)}function Xt(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function N(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>N(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,N(n,t)])):e}async function Zt(e,t){M(t.signal);let n=Kt(e.source.path),r={options:t,context:Ke(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Qt(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Qt(e,t,n,r,i){M(i.options.signal);let a=ln(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await en(s,a,o,e.source.path??r,i));return n}finally{s()}}async function $t(e,t,n,r,i){let a=[];for(let o of e)a.push(...await en(o,t,n,r,i));return a}async function en(e,t,n,r,i){M(i.options.signal);let a=un(e,r);switch(a.kind){case`runFlow`:{let e=nn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await tn(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[P(a,t,n,o)]}case`repeat`:return[P(a,t,n,await $t(a.commands,t,n,r,i))];case`retry`:return[P(a,t,n,await $t(a.commands,t,n,r,i))];default:return[sn(a,t,n)]}}async function tn(e,t,n,r,i){let a=an(e,i.context),o=qt(a,i.activeIncludePaths),s=await Wt(a,i.options);M(i.options.signal);let c=Jt(a,s,o,i.activeIncludePaths),l=ln(t,e.env),u=i.context.enter(e.env);try{return await Qt(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function nn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:rn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function rn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return on(t.context.resolveDeferred(e))?`opaque`:jt(e,t.context,t.options.platform)?void 0:`omit`}function an(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function on(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function sn(e,t,n){return T({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function P(e,t,n,r){return T({kind:`opaque`,command:cn(e),source:e.source,scopes:t,body:r,appId:n})}function cn(e){switch(e.kind){case`runFlow`:return T({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return T({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function ln(e,t){return t===void 0?e:[...e,t]}function un(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function dn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await Zt(e,t),a=fn(t.runtimeHints),o=T({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=At(o);return pn({...o,digest:s})}function fn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function pn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))pn(t);return Object.freeze(e)}function mn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function hn(t,n={}){let r=mn(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function gn(t,n){if(!Number.isInteger(n)||n<0||n>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${n} is out of range for a ${t.total}-step plan.`);return n}const _n=`maestro-test-failure`;function F(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:_n})}function vn(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===_n}const yn=new Set([``,`false`,`0`,`null`,`undefined`]);function bn(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!yn.has(e)}async function xn(e,t){M(t.options.signal);try{return await Pn(e,t.context,async()=>await Sn(e,t))}catch(t){throw R(t,e)}}async function Sn(e,t){if(e.kind===`command`)return await Cn(e.command,e.appId,t);await kn(e,t)}async function Cn(e,t,n){if(e.kind===`evalScript`)return await En(e,n);let r=Ht(e,n.context);try{return await Dn(r,t,n)}catch(e){if(M(n.options.signal),Tn(r)&&vn(e)){n.warnings.push(wn(r,e)),n.skipped+=1;return}throw Fn(e,r)}}function wn(t,n){let r=`${t.source.path?`${t.source.path}:`:``}line ${t.source.line}`,i=n instanceof e?n.message:String(n);return`Optional Maestro ${t.kind} skipped at ${r}: ${i}`}function Tn(e){return`optional`in e&&e.optional===!0}async function En(t,n){let{evaluateMaestroEvalScript:r}=await import(`./engine-eval-script.js`);if(n.options.trustedScripts===!1)throw new e(`UNAUTHORIZED`,`Maestro evalScript is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`);let i=await r(t.script,n.context.values);n.context.replaceOutput(i),n.executed+=1}async function Dn(e,t,n){switch(e.kind){case`assertVisible`:await L({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await L({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!bn(e.condition))throw F(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await L(Nn(e),j(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await On(e,t,n)}}async function On(e,t,n){let r=T({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return M(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function kn(e,t){let n=Ht(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await jn(n.when,t)){t.skipped+=1;return}t.executed+=1,await I(e.body,t);return;case`repeat`:{let r=Ut(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)M(t.options.signal),await I(e.body,t);return}case`retry`:{let r=Math.min(Ut(n.maxRetries,1,t.context,`retry.maxRetries`),Ze.control.retryMaxRetries);t.executed+=1,await An(e.body,r,t);return}}}async function I(e,t){for(let n of e)await xn(n,t)}async function An(t,n,r){let i;for(let e=0;e<=n;e+=1){M(r.options.signal);try{await I(t,r);return}catch(e){if(M(r.options.signal),!vn(Ln(e)))throw e;i=R(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function jn(e,t){if(!Yt(e,t.context,t.options))return!1;for(let n of Xt(e))if(M(t.options.signal),!(await Mn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function L(e,t,n){if(!(await Mn(e,t,n)).matched)throw F(`Maestro ${e.kind} condition did not match.`)}async function Mn(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return M(n.options.signal),n.context.recordObservation(i),i}function Nn(t){if(t.visible)return{kind:`visible`,selector:t.visible};if(t.notVisible)return{kind:`notVisible`,selector:t.notVisible};throw new e(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Pn(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function R(e,t){if(In(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Rn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Fn(e,t){return{kind:`maestroPlanStepFailure`,error:Rn(e,t),source:t.source,command:t}}function In(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Ln(e){return In(e)?e.error:e}function Rn(t,n){if(!(t instanceof e)||!n||/\bline \d+\b/.test(t.message))return t;let r=n.source.path?`${n.source.path}:`:``;return new e(t.code,`${t.message} (${r}line ${n.source.line})`,t.details)}async function zn(t,n,r={}){M(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${t.total}-step plan.`);let a={plan:t,port:n,options:r,context:Ke(r.defaults,r.env?{...r.env}:{}),timing:Qe,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Bn(t.steps[e],e,a)}catch(e){throw Ln(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Bn(e,t,n){M(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};z(()=>n.options.observer?.commandStarted?.(s));try{let t=await xn(e,n);M(n.options.signal),z(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Vn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=R(t,e);throw z(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Vn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Vn(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function z(e){try{e?.()}catch{}}async function Hn(e,t,n={}){let r=Un(e,n);return await zn(e,t,{...n,startIndex:r})}function Un(e,t){return t.from!==void 0||t.planDigest!==void 0?hn(e,{from:t.from,planDigest:t.planDigest}):gn(e,t.startIndex??0)}function Wn(e){return Vt(e)?{command:e.kind,...e.kind===`runFlow`?V(e.label??e.includePath):{}}:{command:e.kind,...Gn(e)}}function Gn(e){return`label`in e&&e.label?V(e.label):Kn(e)?V($n(e.target)):qn(e)?Jn(e):e.kind===`inputText`?V(`<text>`):Yn(e)}function Kn(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function qn(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Jn(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return V(B(e.target));case`extendedWaitUntil`:return V(B(e.visible??e.notVisible));case`scrollUntilVisible`:return V(B(e.element))}}function Yn(e){return Xn(e)?Zn(e):e.kind===`swipe`?Qn(e):e.kind===`runFlow`?V(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?V(String(e.condition)):{}}function Xn(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Zn(e){switch(e.kind){case`openLink`:return V(e.link);case`takeScreenshot`:return V(e.path);case`runScript`:return V(e.file);case`pressKey`:return V(e.key)}}function Qn(e){return V(e.gesture.kind===`coordinates`?`${er(e.gesture.start)} to ${er(e.gesture.end)}`:e.gesture.direction)}function $n(e){return e.space===`target`?B(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function B(e){return e?.id??e?.text}function er(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function V(e){return e?{value:e}:{}}const tr=new Set(String.raw`^$\.*+?()[]{}|`);function nr(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function rr(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(tr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!tr.has(i))return;t+=i,n+=1}return t}function ir(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(g(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>ee(e,n)?e:null);return r?g(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function ar(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function or(e,t){let n=[t.id===void 0?void 0:cr(e.identifier,t.id),t.text===void 0?void 0:lr(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function sr(e){return e.matches.filter(t=>ir(t,e.visibility,e.platform))}function cr(e,t){let n=e??``;return E(n)===E(t)||nr(n,t)}function lr(e,t){return[e.label,qe(e),e.identifier].filter(e=>!!e).some(e=>cr(e,t))}function ur(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function dr(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function fr(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=mr(a.rect,e.rect);n===void 0||!pr(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function pr(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function mr(e,t){if(!(!hr(e)||!hr(t)))return Math.fround(Math.hypot(H(e.x,e.width)-H(t.x,t.width),H(e.y,e.height)-H(t.y,t.height)))}function hr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function H(e,t){return e+Math.trunc(t/2)}function gr(t,n={},r={}){let i=h(t.nodes,n);n.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=e=>e.parentIndex===void 0?void 0:i.nodeByIndex.get(e.parentIndex)??t.nodes[e.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(e,r)=>{let i=c.get(e);i||(i=new WeakMap,c.set(e,i));let a=i.get(r);if(a)return a;n.onPositionComputed?.(e,r);let o=fr(t.nodes,e,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new e(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),n.onSelectorComputed?.(i);try{let e=_r(t,i,l,u,m,p),n={matches:e,indexed:xr(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function _r(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=dr(m)?e.nodes.filter(e=>or(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>yr(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>vr(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of br(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function vr(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function yr(e,t){for(let n of e)if(t.has(n))return!0;return!1}function br(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function xr(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Cr(e)[wr(t)];return r?[r]:[]}function Sr(e,t){return t===void 0?e[0]:Cr(e)[wr(t)]}function Cr(e){return[...e].sort((e,t)=>{let n=U(e.rect?.y),r=U(t.rect?.y);return n===r?U(e.rect?.x)-U(t.rect?.x):n-r})}function U(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function wr(t){let n=typeof t==`number`?t:Number(t.trim());if(!Number.isSafeInteger(n)||n<0)throw new e(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return n}const Tr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Er(e,t){let n=Tr[t];if(n.kind===`divergence`)return n;let r=a(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function W(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Dr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Dr(e){return e===!0?2:+(e===!1)}function Or(e,t,n,r={}){let i=Er(e,n),a=Ar(e,i,r),o=kr(t,a),s=sr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:jr(s,t,n,a.visibility,i)}}function kr(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Ar(e,t,n={}){return gr(e,n,t?{orderUnindexed:e=>W(e,t)}:{})}function jr(e,t,n,r,i){let a=n!==`ios`||!Fr(t)?e:e.filter(n=>{if(Rr(n))return!0;let i=e.filter(e=>e!==n&&Ir(n,e,t));return!i.some(e=>Rr(e)&&ar(n,e,r))&&!i.some(e=>ar(e,n,r))});return t.index===void 0&&i?W(a,i):a}function Mr(e,t){let n=t===void 0?e.find(G):Nr(e,t);return!n||!G(n)?null:{node:n,rect:n.rect}}function Nr(e,t){return Sr(e,t)}function Pr(e){return G(e)?e.rect:void 0}function G(e){return g(e.rect)}function Fr(e){return e.id!==void 0||e.text!==void 0}function Ir(e,t,n){if(n.id!==void 0&&K(e.identifier)!==K(t.identifier))return!1;if(n.text!==void 0){let n=Lr(e),r=new Set(Lr(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Lr(e){return[e.label,e.value,e.identifier].map(K).filter(e=>e!==void 0)}function K(e){if(e)return E(e)||void 0}function Rr(e){let t=m(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const zr=Symbol(`maestroFlowProgram`),Br=Symbol(`maestroFailureCommand`),Vr=Symbol(`maestroFailurePlan`);function Hr(e,t){let n=Xe(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Kr(n),[zr]:n}}async function Ur(e,t,n){let r;try{let i=Je(D.dirname(e.sourcePath),n.readSource),a=await dn(e[zr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=hn(a,{from:n.from,planDigest:n.planDigest}),s=await Hn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,trustedScripts:n.trustedScripts,observer:Gr(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Wr(e,t){let n=Jr(e[Br]),r=e[Vr].platform;return!n||r!==`android`&&r!==`ios`?[]:Or(t,n.selector,r).ranked.map(e=>({node:e,basis:Yr(n.selector,e)}))}function Gr(e,t,n){return{commandStarted:e=>t?.actionStarted?.(q(e)),commandCompleted:e=>t?.actionCompleted?.({...q(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=mn(e,{from:r.stepIndex,planDigest:e.digest}),a={...q(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:Vt(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Br]:r.command,[Vr]:e};n(a),t?.actionFailed?.(a)}}}function q(e){let t=Wn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Kr(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(qr)}function qr(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function Jr(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function Yr(e,t){return e.id!==void 0||e.text!==void 0&&or({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const Xr=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function Zr(t,n){let r=t.files[n];if(r===void 0)throw new e(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:t.entry});return r}function Qr(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=Zr(t,n);if(ce(n,e.flags?.replayBackend)===`maestro`){let t=Hr(r,n);return{flags:e.flags??{},options:$r(t.appTarget,e.flags?.platform)}}let i=rt(r,e.flags),a=ei(i.actions);if(!a.appTarget)return;let o=ti(e.flags,i.actions),s=o.platform??i.metadata.platform;return{flags:s&&o.platform===void 0?{...o,platform:s}:o,options:s===`ios`?ri(a.appTarget):void 0}}catch{return}}function $r(e,t){return t===`ios`?ri(e)??{}:{}}function ei(e){let t=ae(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ni(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function ti(e,t){let n=ei(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ni(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function ri(e){let t=kt(e);return t?{appleSimulatorAppTarget:t}:void 0}const ii={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},J=new Map;async function ai(e){let t=await O.mkdtemp(D.join(nt.tmpdir(),`agent-device-materialized-`));try{let n=await li(e.installablePath,D.join(t,`installable`)),r=e.archivePath?await li(e.archivePath,D.join(t,`archive`)):void 0,i=et.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{ci(i)},a);return J.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await O.rm(t,{recursive:!0,force:!0}),e}}async function oi(e,t){await Y(e,Te(J,e,t,ii))}async function si(e){let t=Array.from(J.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await Y(e,t)}))}async function ci(e){let t=J.get(e);if(t)try{await Y(e,t)}catch{}}async function Y(e,t){clearTimeout(t.timer),J.delete(e),await O.rm(t.rootPath,{recursive:!0,force:!0})}async function li(e,t){let n=await O.stat(e);await O.mkdir(t,{recursive:!0});let r=D.join(t,D.basename(e));return n.isDirectory()?(await O.cp(e,r,{recursive:!0}),r):(await O.copyFile(e,r),r)}function ui(e){return e.device.platform===`web`}function di(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function fi(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await Re({session:t,sessionName:n,sessionStore:r,resourcePath:Ie.resolvePath(r.resolveSessionDir(n))})}async function pi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Le({...e,session:t,intent:`disposal`})}async function mi(e,t){await t.stopSnapshotHelper(e.device)}async function hi(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>di(r)})}async function gi(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function _i(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return _({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function vi(t){let{session:n,sessionName:r,sessionStore:i}=t;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[{step:`recording`,run:()=>yi({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>fi({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>bi({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>pi({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>mi(n,a)},{step:`web_browser`,run:()=>hi({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>si(r)});let s=_i({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await gi(o)});if(s)throw s}async function yi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await $e({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function bi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Fe({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function xi(e){return s(e)&&e.kind===`simulator`}function Si(e){return e.platform===`android`&&e.kind===`emulator`}const Ci=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function X(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Z(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Q(e){return De(Z(e))}function $(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return v(t)}}function wi(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function Ti(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return wi(t)}}function Ei(t,r,i){if(t===void 0)return i;if(!n(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(i&&t!==i)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${r}" is bound to ${i}.`);return t}function Di(e){if(n(e))return e}function Oi(e,t){return{platform:t,metroHost:v(e?.metroHost),metroPort:wi(e?.metroPort),bundleUrl:v(e?.bundleUrl),launchUrl:v(e?.launchUrl)}}function ki(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Ai(e){if(Si(e))return`10.0.2.2`;if(xi(e))return`127.0.0.1`}function ji(e,t){if(!e||v(e.metroHost)||v(e.bundleUrl)||e.metroPort===void 0)return e;let n=Ai(t);return n?{...e,metroHost:n}:e}function Mi(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!Ci.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ci.join(`, `)}.`);return{platform:Ei(a.platform,r,i),metroHost:$(a.metroHost,`metroHost`),metroPort:Ti(a.metroPort),bundleUrl:$(a.bundleUrl,`bundleUrl`),launchUrl:$(a.launchUrl,`launchUrl`)}}function Ni(e,t,n){if(n){if(X(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Pi(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?l(r):void 0,s=Di(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Fi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Di(l(i)):e.platform,o=n.getRuntimeHints(r),s=Mi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Pi(n,r,i,a);return{runtime:i?ji(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&X(s)>0?s:void 0;return{runtime:i?ji(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ii(e){return Fi(e).runtime}function Li(e){try{return{ok:!0,data:Fi(e)}}catch(e){let t=r(e);return Ee(t.code,t.message,t.details)}}async function Ri(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!zi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Z(t)})}function zi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Q(e.previousRuntime)&&!Q(e.runtime)}function Bi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&ne(i.owner,n)?te(i.fence):null;if(!a)return{status:`binding-invalid`};let o=C(w(t)),s=Me(ke(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!Hi(c.stateDir,r)||!ne(je(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function Vi(e){let t=C(w(e));return Oe(ke(t))}function Hi(e,t){return D.resolve(e)===D.resolve(t)}const Ui=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function Wi(e){return Ui.has(e)}function Gi(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=l(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=o(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${le(i)}`,`${a} ${le(e.id)}`,...n===`release`||Ae(t.classification)?[`--stale`]:[]].join(` `)}function Ki(t,n){if(n.classification===`allocator-held`)return Ji(t,n);let r=n.claim,i=Gi(t,n,Ne(n.classification)?`release`:`status`),a=l(r?{platform:r.device.family,appleOs:r.device.appleOs}:t);return new e(`DEVICE_IN_USE`,r?`${a} device ${t.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${t.name} has an ownership claim that could not be verified.`,{reason:ta(n.classification),classification:n.classification,deviceKey:n.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:Ne(n.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function qi(e,t){return ea(Ki(e,t))}function Ji(t,n){let r=n.allocatorClaim,i=l({platform:r.device.family,appleOs:r.device.appleOs}),a=Gi(t,n);return new e(`DEVICE_IN_USE`,`${i} device ${t.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:n.classification,deviceKey:n.deviceKey,owner:{kind:`allocator`,stateDir:r.stateDir,allocator:r.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function Yi(t,n){return new e(`COMMAND_FAILED`,`${l(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:re(n),deviceKey:C(w(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function Xi(t,n,r){return new e(`COMMAND_FAILED`,`${l(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:re(n),deviceKey:C(w(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function Zi(t,n){return new e(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:re(n),deviceKey:C(w(t)),retriable:!1})}function Qi(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:Zi(e,t)};case`missing`:return{admitted:!1,error:Yi(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:Xi(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:Ki(e,n.conflict)}}}function $i(e,t,n){let r=Qi(e,t,n);return r.admitted?void 0:ea(r.error)}function ea(e){let{hint:t,retriable:n,...r}=e.details??{};return Ee(e.code,e.message,r,{hint:t,retriable:n})}function ta(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function na(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{rr as $,si as A,Ar as B,fi as C,ui as D,vi as E,Xr as F,Nr as G,Or as H,Zr as I,Er as J,Pr as K,Wr as L,$r as M,ti as N,di as O,Qr as P,ir as Q,Ur as R,_i as S,mi as T,jr as U,kr as V,Mr as W,ur as X,gr as Y,sr as Z,zi as _,Ki as a,Tt as at,bi as b,Bi as c,gt as ct,Q as d,bt as dt,F as et,Ri as f,yt as ft,Ni as g,Z as h,at as ht,Qi as i,Ct as it,ai as j,oi as k,Oi as l,_t as lt,Ii as m,ct as mt,$i as n,Ot as nt,Wi as o,Et as ot,ki as p,lt as pt,W as q,qi as r,wt as rt,Vi as s,vt as st,na as t,j as tt,X as u,ht as ut,Di as v,pi as w,yi as x,Li as y,Hr as z};
1
+ import{D as e,F as t,L as n,O as r,W as i,_ as a,b as o,c as s,k as c,m as l,o as u,u as d}from"./sdk-contracts.js";import"./capture.js";import{O as f,f as p,r as m,t as h}from"./sdk-batch-runner.js";import{a as g,n as _,t as v}from"./snapshot-diagnostics.js";import{f as y,p as b}from"./android-input-ownership.js";import{f as x,l as S,s as C,u as w,v as ee,x as te,y as T}from"./sdk-device.js";import{d as ne,l as E,n as re,r as ie}from"./lease-scope.js";import{Bn as ae,Br as D,Cr as oe,Er as se,Gn as ce,Gt as le,Hn as ue,Hr as de,Ln as fe,Lr as pe,Nr as me,T as he,Wr as ge,Xt as _e,Zt as ve,fn as ye,gn as be,hn as xe,ir as Se,mn as Ce,nr as we,pn as Te,rn as Ee,rr as De,wr as Oe,zn as ke}from"./sdk-batch.js";import{i as Ae}from"./back-mode.js";import{u as je}from"./scroll-gesture.js";import{a as Me,b as Ne,f as Pe,g as O,n as Fe,p as Ie,r as Le,w as Re,y as ze}from"./script.js";import{a as Be}from"./session-store.js";import{L as Ve,S as He,T as Ue,b as We,w as Ge,x as Ke}from"./session-snapshot.js";import{a as qe,c as Je,i as Ye,l as Xe,n as Ze,o as Qe,r as $e,s as et,t as tt,u as nt}from"./format.js";import{A as rt,j as it}from"./parameterized-recorded-fill.js";import{E as at,F as ot,N as st,O as ct,P as lt,j as ut,w as dt}from"./runtime.js";import{n as ft}from"./success-text.js";import{d as pt,i as mt,u as ht}from"./absence-observation-errors.js";import{a as gt}from"./device.js";import{o as _t,r as k}from"./diagnostics.js";import{p as vt}from"./exec.js";import{t as yt}from"./timeouts.js";import"./diagnostics2.js";import{n as bt,r as xt}from"./output-path.js";import"./command.js";import{a as St,n as Ct,t as wt}from"./replay-divergence.js";import{s as Tt}from"./device-shell.js";import{n as Et}from"./retry.js";import{t as Dt}from"./session-paths.js";import{n as A}from"./runtime-transport-hints.js";import{r as j}from"./rect-center.js";import{o as Ot}from"./android-system-chrome.js";import{_ as kt,a as At,c as jt,d as M,f as Mt,g as Nt,h as Pt,i as Ft,l as It,m as Lt,n as Rt,o as zt,p as Bt,r as Vt,s as Ht,u as Ut,v as Wt}from"./human-control-contract.js";import{a as Gt,c as Kt,i as qt,n as Jt,o as Yt,r as N}from"./request-cancel.js";import{t as Xt}from"./request.js";import{n as Zt,t as Qt,u as $t}from"./provider-session-ownership.js";import{r as en}from"./application-lifecycle-runtime.js";import{a as tn,c as P,l as nn,n as rn,o as an,r as on,t as sn}from"./device-claim-inspection.js";import{b as cn,c as ln,g as un,i as dn,p as fn,x as pn}from"./perf-runtime-plan.js";import{n as mn,r as hn,t as gn}from"./lease-context.js";import{d as _n,g as vn,u as yn}from"./screenshot-runtime.js";import{n as bn,r as xn}from"./device-isolation.js";import{n as Sn}from"./device-inventory-context.js";import{n as Cn}from"./dispatch-resolve.js";import{t as wn}from"./touch-reference-frame.js";import{n as Tn}from"./screen-recording-admission-ledger.js";import{a as En,c as Dn,d as F,l as On,n as kn,o as An,r as jn,u as Mn}from"./src8.js";import{i as Nn,n as I,r as Pn,t as Fn}from"./compatibility-policy.js";import{o as In}from"./quality-warnings.js";import{t as Ln}from"./png-worker-client.js";import{t as Rn}from"./semantic-index.js";import{o as zn}from"./screen-recording-resource-recovery.js";import L from"node:path";import R,{promises as Bn}from"node:fs";import Vn,{createHash as Hn}from"node:crypto";import Un from"node:os";import z from"node:fs/promises";import{fileURLToPath as Wn}from"node:url";import{setTimeout as Gn}from"node:timers/promises";import Kn from"node:vm";function qn(e,t){return Jn(e,t)?t:`${e}:${t}`}function Jn(e,t){return t.startsWith(`${e}:`)}function Yn(e,t){return!e.partitioned||Jn(e.tenant,t)}var Xn=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},Zn=class{entriesByLeaseId=new Map;retain(e,t){let n={wanted:t,released:!1},r=this.entriesByLeaseId.get(e)??new Set;return r.add(n),this.entriesByLeaseId.set(e,r),{leaseId:e,release:()=>this.releasePass(e,r,n)}}forget(e){let t=this.entriesByLeaseId.get(e);if(t){for(let e of t)e.released=!0;this.entriesByLeaseId.delete(e)}}isDeferred(e){let t=this.entriesByLeaseId.get(e);if(!t)return!1;for(let e of t)e.wanted()||t.delete(e);return t.size>0||(this.entriesByLeaseId.delete(e),!1)}releasePass(e,t,n){return!n.released&&(n.released=!0,t.delete(n),t.size===0&&this.entriesByLeaseId.delete(e),n.wanted())}},Qn=class{holdsByDevice=new Map;mutations=new Xn;inFlightWork=new Zn;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=It(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new Qt({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=Bt(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=jt(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=Mt(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw Ut(i);return Ht(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=Nt(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);zt(n,e),Ht(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}retainLeaseWork(e,t){let n=this.inFlightWork.retain(e.leaseId,t);return{leaseId:n.leaseId,release:()=>{let t=n.release();return t&&this.refreshProtectedLease(e.leaseId,this.now()),t}}}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),this.inFlightWork.forget(t.leaseId),{released:!0,lease:t}):{released:!1}}getLease(e){let t=Nt(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return zt(n,e),Ht(n,e),{...n}}assertLeaseAdmission(e){let t=Lt(e);this.cleanupExpiredLeases(),Ht(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?M(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>Rt(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=Ft(n),o=At(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=M(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),M(l.hold.scope)!==c))throw new e(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...t.kind===`lease`?{ownerLeaseId:t.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(t,n,r,i){let a=this.holdsByDevice.get(t),{id:o}=n.hold;try{if(await this.mutations.wait(t,i),i?.throwIfAborted(),a.get(o)!==n)throw new e(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return n.hold={...n.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(t,s),Rt(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=Ft(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=M(r.hold.scope);return this.deleteHumanControlHold(i,n),Rt(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=M(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw Vt(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=M(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(t){let n=this.getActiveLease(t);if(!n.deviceKey)throw new e(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...n,deviceKey:n.deviceKey}}resolveHumanControlScope(t,n){if(t.kind===`host`){if(!n.scope)throw new e(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return n.scope}if(n.scope)throw new e(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(t.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(t,n){if(t.kind===`host`)return;let r=this.requireHumanControlLease(t.leaseId);if(n.ownerLeaseId!==r.leaseId||M(r)!==M(n.hold.scope))throw new e(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=M(e);return t!==void 0&&this.holdsByDevice.has(t)}isLeaseProtected(e,t){return e.expiresAt>t||this.hasHumanControl(e)||this.inFlightWork.isDeferred(e.leaseId)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){this.refreshProtectedLease(this.deviceBindings.get(e),t)}refreshProtectedLease(e,t){let n=e?this.leases.get(e):void 0;n&&this.refreshLease(n,n.expiresAt-n.heartbeatAt,Math.max(t,n.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(this.isLeaseProtected(n,e))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=Pt(e);if(!t)return;let n=this.leases.get(t);if(!n||this.isLeaseProtected(n,this.now()))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(t){if(t!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let n=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(n<this.maxActiveSimulatorLeases))throw new e(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:n,maxActiveLeases:this.maxActiveSimulatorLeases,backend:t,hint:`Retry after releasing another simulator lease.`})}getActiveLease(t){let n=this.leases.get(t);if(n)return n;throw new e(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(Mt(e),e.leaseId);let t=M(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(Mt(e));let n=M(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=M({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw Ut(r)}};function $n(t){let n=Wt(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=kt(r);if(r&&!i)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n!==`tenant`)return t;if(!i)throw new e(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=t.session||`default`;return Jn(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:qn(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function er(t,n,r,i={}){if(_n(t.command))return;let a=mn(t);rr(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&tr(t,i.providerAppCatalog))return;if(t.command===`human_control`&&!o&&!a.leaseId)throw new e(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(t.command!==`human_control`&&!o&&t.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;ir(a,o);let s=hn(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(ie(s)?3e5:void 0)};n.assertLeaseAdmission(E(s));let l=n.heartbeatLease(E(c));return yn(t)&&n.assertHumanControlAdmission(l),l}function tr(e,t){let n=vn(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function nr(e){_n(e.command)||rr(e,mn(e))}function rr(t,n){if(t.command!==`open`)return;let r=re(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function ir(e,t){t&&(B(`leaseId`,e.leaseId,t.leaseId),B(`tenantId`,e.tenantId,t.tenantId),B(`runId`,e.runId,t.runId),B(`leaseProvider`,e.leaseProvider,t.leaseProvider),B(`clientId`,e.clientId,t.clientId),B(`deviceKey`,e.deviceKey,t.deviceKey))}function B(t,n,r){if(!(!n||!r||n===r))throw new e(`UNAUTHORIZED`,`Lease does not match session owner (${t})`,{reason:`LEASE_SESSION_MISMATCH`,field:t})}async function ar(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),k({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return k({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function or(e){nr(e)}async function sr(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(k({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{k({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await cn(t.deviceClaim).catch(e=>{k({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function cr(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=er(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function lr(e){return gn(e.req,e.req.internal?.admittedLease)??e.existingLease}async function ur(e){let t=e.session.lease;if(!t)return;let n=ne({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=Zt(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return k({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const dr=[`platform`,`target`],fr=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function pr(e){return C({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function mr(e){return pr(e)||_r(e,dr)}function hr(e){return mr(e)||_r(e,fr)}function gr(e){return typeof e==`string`&&e.trim().length>0}function _r(e,t){return e?t.some(t=>gr(e[t])):!1}function vr(e){return{appleSimulatorAppTarget:yr(e)}}function yr(e){return e&&!m(e)?e:void 0}function br(){return Tn({displayName:`audio probe`})}function xr(){return Tn({displayName:`perf capture`})}function Sr(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return Hn(`sha256`).update(we(t),`utf8`).digest(`hex`)}function Cr(e,t,n){return new Mr(Tr(wr(t.resolve(e))),n).parse()}function wr(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Tr(t){let n=[],r=0;for(;r<t.length;){let i=t.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Er(i);if(!o)throw new e(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);n.push(o.value),r+=o.length}return n}function Er(e){return Dr(e)??Or(e)??kr(e)??Ar(e)??jr(e)}function Dr(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Or(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function kr(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Ar(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function jr(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Mr=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let t=this.parseOr();if(this.peek())throw new e(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return t}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let t=this.peek();if(!t)throw new e(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(t.type===`boolean`)return this.index+=1,t.value;if(t.type===`paren`&&t.value===`(`){this.index+=1;let t=this.parseOr();if(!this.consumeParen(`)`))throw new e(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return t}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new e(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let t=this.peek();if(t?.type!==`operator`||t.value!==`==`&&t.value!==`!=`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,t}consumeStringLiteral(){let t=this.peek();if(t?.type!==`string`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,t.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Nr(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Pr(e,t){return{...Ur(e,t),source:e.source}}function V(t,n,r){if(t===void 0)return;let i=r??En[n]??{},a=An(i),o;if(typeof t==`number`)o=t;else{let r=t.trim();if(r===``)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);return o}function Fr(e,t,n,r){return V(e===void 0?t:n.resolve(String(e)),r)}function H(e){if(e?.aborted)throw c()}async function Ir(t,n){if(t.include.kind===`commands`)return{kind:`program`,source:t.source,config:{},commands:t.include.commands};if(!n.loadProgram)throw new e(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return H(n.signal),n.signal?await n.loadProgram(t.include.path,t.source.path,n.signal):await n.loadProgram(t.include.path,t.source.path)}function Lr(e,t){if(e.include.kind===`file`)return L.resolve(t?L.dirname(t):process.cwd(),e.include.path)}function Rr(e){return e===void 0?void 0:L.resolve(e)}function zr(t,n){let r=Lr(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Br(t,n,r,i){let a=t.include.kind===`file`?Rr(n.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Vr(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:Cr(e.true,t,n.platform)}function Hr(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function Ur(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>Ur(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Ur(n,t)])):e}async function Wr(e,t){H(t.signal);let n=Rr(e.source.path),r={options:t,context:Dn(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Gr(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Gr(e,t,n,r,i){H(i.options.signal);let a=ni(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await qr(s,a,o,e.source.path??r,i));return n}finally{s()}}async function Kr(e,t,n,r,i){let a=[];for(let o of e)a.push(...await qr(o,t,n,r,i));return a}async function qr(e,t,n,r,i){H(i.options.signal);let a=ri(e,r);switch(a.kind){case`runFlow`:{let e=Yr(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await Jr(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[ei(a,t,n,o)]}case`repeat`:return[ei(a,t,n,await Kr(a.commands,t,n,r,i))];case`retry`:return[ei(a,t,n,await Kr(a.commands,t,n,r,i))];default:return[$r(a,t,n)]}}async function Jr(e,t,n,r,i){let a=Zr(e,i.context),o=zr(a,i.activeIncludePaths),s=await Ir(a,i.options);H(i.options.signal);let c=Br(a,s,o,i.activeIncludePaths),l=ni(t,e.env),u=i.context.enter(e.env);try{return await Gr(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function Yr(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:Xr(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function Xr(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return Qr(t.context.resolveDeferred(e))?`opaque`:Cr(e,t.context,t.options.platform)?void 0:`omit`}function Zr(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function Qr(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function $r(e,t,n){return F({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function ei(e,t,n,r){return F({kind:`opaque`,command:ti(e),source:e.source,scopes:t,body:r,appId:n})}function ti(e){switch(e.kind){case`runFlow`:return F({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return F({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function ni(e,t){return t===void 0?e:[...e,t]}function ri(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function ii(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await Wr(e,t),a=ai(t.runtimeHints),o=F({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=Sr(o);return oi({...o,digest:s})}function ai(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function oi(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))oi(t);return Object.freeze(e)}function si(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function ci(t,n={}){let r=si(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function li(t,n){if(!Number.isInteger(n)||n<0||n>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${n} is out of range for a ${t.total}-step plan.`);return n}const ui=`maestro-test-failure`;function di(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:ui})}function fi(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===ui}const pi=new Set([``,`false`,`0`,`null`,`undefined`]);function mi(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!pi.has(e)}async function hi(e,t){H(t.options.signal);try{return await Ai(e,t.context,async()=>await gi(e,t))}catch(t){throw ji(t,e)}}async function gi(e,t){if(e.kind===`command`)return await _i(e.command,e.appId,t);await Ci(e,t)}async function _i(e,t,n){if(e.kind===`evalScript`)return await bi(e,n);let r=Pr(e,n.context);try{return await xi(r,t,n)}catch(e){if(H(n.options.signal),yi(r)&&fi(e)){n.warnings.push(vi(r,e)),n.skipped+=1;return}throw Mi(e,r)}}function vi(t,n){let r=`${t.source.path?`${t.source.path}:`:``}line ${t.source.line}`,i=n instanceof e?n.message:String(n);return`Optional Maestro ${t.kind} skipped at ${r}: ${i}`}function yi(e){return`optional`in e&&e.optional===!0}async function bi(t,n){let{evaluateMaestroEvalScript:r}=await import(`./engine-eval-script.js`);if(n.options.trustedScripts===!1)throw new e(`UNAUTHORIZED`,`Maestro evalScript is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`);let i=await r(t.script,n.context.values);n.context.replaceOutput(i),n.executed+=1}async function xi(e,t,n){switch(e.kind){case`assertVisible`:await Di({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await Di({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!mi(e.condition))throw di(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await Di(ki(e),V(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await Si(e,t,n)}}async function Si(e,t,n){let r=F({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return H(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function Ci(e,t){let n=Pr(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await Ei(n.when,t)){t.skipped+=1;return}t.executed+=1,await wi(e.body,t);return;case`repeat`:{let r=Fr(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)H(t.options.signal),await wi(e.body,t);return}case`retry`:{let r=Math.min(Fr(n.maxRetries,1,t.context,`retry.maxRetries`),I.control.retryMaxRetries);t.executed+=1,await Ti(e.body,r,t);return}}}async function wi(e,t){for(let n of e)await hi(n,t)}async function Ti(t,n,r){let i;for(let e=0;e<=n;e+=1){H(r.options.signal);try{await wi(t,r);return}catch(e){if(H(r.options.signal),!fi(Pi(e)))throw e;i=ji(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function Ei(e,t){if(!Vr(e,t.context,t.options))return!1;for(let n of Hr(e))if(H(t.options.signal),!(await Oi(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function Di(e,t,n){if(!(await Oi(e,t,n)).matched)throw di(`Maestro ${e.kind} condition did not match.`)}async function Oi(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return H(n.options.signal),n.context.recordObservation(i),i}function ki(t){if(t.visible)return{kind:`visible`,selector:t.visible};if(t.notVisible)return{kind:`notVisible`,selector:t.notVisible};throw new e(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Ai(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function ji(e,t){if(Ni(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Fi(e,t?.command),source:n,...t?{command:t.command}:{}}}function Mi(e,t){return{kind:`maestroPlanStepFailure`,error:Fi(e,t),source:t.source,command:t}}function Ni(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Pi(e){return Ni(e)?e.error:e}function Fi(t,n){if(!(t instanceof e)||!n||/\bline \d+\b/.test(t.message))return t;let r=n.source.path?`${n.source.path}:`:``;return new e(t.code,`${t.message} (${r}line ${n.source.line})`,t.details)}async function Ii(t,n,r={}){H(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${t.total}-step plan.`);let a={plan:t,port:n,options:r,context:Dn(r.defaults,r.env?{...r.env}:{}),timing:Fn,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Li(t.steps[e],e,a)}catch(e){throw Pi(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Li(e,t,n){H(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};zi(()=>n.options.observer?.commandStarted?.(s));try{let t=await hi(e,n);H(n.options.signal),zi(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Ri(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=ji(t,e);throw zi(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Ri(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Ri(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function zi(e){try{e?.()}catch{}}async function Bi(e,t,n={}){let r=Vi(e,n);return await Ii(e,t,{...n,startIndex:r})}function Vi(e,t){return t.from!==void 0||t.planDigest!==void 0?ci(e,{from:t.from,planDigest:t.planDigest}):li(e,t.startIndex??0)}function Hi(e){return Nr(e)?{command:e.kind,...e.kind===`runFlow`?U(e.label??e.includePath):{}}:{command:e.kind,...Ui(e)}}function Ui(e){return`label`in e&&e.label?U(e.label):Wi(e)?U(Zi(e.target)):Gi(e)?Ki(e):e.kind===`inputText`?U(`<text>`):qi(e)}function Wi(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function Gi(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Ki(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return U(Qi(e.target));case`extendedWaitUntil`:return U(Qi(e.visible??e.notVisible));case`scrollUntilVisible`:return U(Qi(e.element))}}function qi(e){return Ji(e)?Yi(e):e.kind===`swipe`?Xi(e):e.kind===`runFlow`?U(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?U(String(e.condition)):{}}function Ji(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Yi(e){switch(e.kind){case`openLink`:return U(e.link);case`takeScreenshot`:return U(e.path);case`runScript`:return U(e.file);case`pressKey`:return U(e.key)}}function Xi(e){return U(e.gesture.kind===`coordinates`?`${$i(e.gesture.start)} to ${$i(e.gesture.end)}`:e.gesture.direction)}function Zi(e){return e.space===`target`?Qi(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function Qi(e){return e?.id??e?.text}function $i(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function U(e){return e?{value:e}:{}}const ea=new Set(String.raw`^$\.*+?()[]{}|`);function ta(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function na(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(ea.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!ea.has(i))return;t+=i,n+=1}return t}function ra(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(D(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>se(e,n)?e:null);return r?D(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function ia(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function aa(e,t){let n=[t.id===void 0?void 0:sa(e.identifier,t.id),t.text===void 0?void 0:ca(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function oa(e){return e.matches.filter(t=>ra(t,e.visibility,e.platform))}function sa(e,t){let n=e??``;return Mn(n)===Mn(t)||ta(n,t)}function ca(e,t){return[e.label,On(e),e.identifier].filter(e=>!!e).some(e=>sa(e,t))}function la(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function ua(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function da(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=pa(a.rect,e.rect);n===void 0||!fa(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function fa(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function pa(e,t){if(!(!ma(e)||!ma(t)))return Math.fround(Math.hypot(ha(e.x,e.width)-ha(t.x,t.width),ha(e.y,e.height)-ha(t.y,t.height)))}function ma(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function ha(e,t){return e+Math.trunc(t/2)}function ga(t,n={},r={}){let i=oe(t.nodes,n);n.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=e=>e.parentIndex===void 0?void 0:i.nodeByIndex.get(e.parentIndex)??t.nodes[e.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(e,r)=>{let i=c.get(e);i||(i=new WeakMap,c.set(e,i));let a=i.get(r);if(a)return a;n.onPositionComputed?.(e,r);let o=da(t.nodes,e,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new e(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),n.onSelectorComputed?.(i);try{let e=_a(t,i,l,u,m,p),n={matches:e,indexed:xa(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function _a(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=ua(m)?e.nodes.filter(e=>aa(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>ya(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>va(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of ba(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function va(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function ya(e,t){for(let n of e)if(t.has(n))return!0;return!1}function ba(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function xa(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Ca(e)[Ta(t)];return r?[r]:[]}function Sa(e,t){return t===void 0?e[0]:Ca(e)[Ta(t)]}function Ca(e){return[...e].sort((e,t)=>{let n=wa(e.rect?.y),r=wa(t.rect?.y);return n===r?wa(e.rect?.x)-wa(t.rect?.x):n-r})}function wa(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function Ta(t){let n=typeof t==`number`?t:Number(t.trim());if(!Number.isSafeInteger(n)||n<0)throw new e(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return n}const Ea={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Da(e,t){let n=Ea[t];if(n.kind===`divergence`)return n;let r=b(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function Oa(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:ka(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function ka(e){return e===!0?2:+(e===!1)}function Aa(e,t,n,r={}){let i=Da(e,n),a=Ma(e,i,r),o=ja(t,a),s=oa({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:Na(s,t,n,a.visibility,i)}}function ja(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Ma(e,t,n={}){return ga(e,n,t?{orderUnindexed:e=>Oa(e,t)}:{})}function Na(e,t,n,r,i){let a=n!==`ios`||!Ra(t)?e:e.filter(n=>{if(Ha(n))return!0;let i=e.filter(e=>e!==n&&za(n,e,t));return!i.some(e=>Ha(e)&&ia(n,e,r))&&!i.some(e=>ia(e,n,r))});return t.index===void 0&&i?Oa(a,i):a}function Pa(e,t){let n=t===void 0?e.find(La):Fa(e,t);return!n||!La(n)?null:{node:n,rect:n.rect}}function Fa(e,t){return Sa(e,t)}function Ia(e){return La(e)?e.rect:void 0}function La(e){return D(e.rect)}function Ra(e){return e.id!==void 0||e.text!==void 0}function za(e,t,n){if(n.id!==void 0&&Va(e.identifier)!==Va(t.identifier))return!1;if(n.text!==void 0){let n=Ba(e),r=new Set(Ba(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Ba(e){return[e.label,e.value,e.identifier].map(Va).filter(e=>e!==void 0)}function Va(e){if(e)return Mn(e)||void 0}function Ha(e){let t=me(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Ua=Symbol(`maestroFlowProgram`),Wa=Symbol(`maestroFailureCommand`),Ga=Symbol(`maestroFailurePlan`);function Ka(e,t){let n=jn(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Za(n),[Ua]:n}}async function qa(e,t,n){let r;try{let i=kn(L.dirname(e.sourcePath),n.readSource),a=await ii(e[Ua],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=ci(a,{from:n.from,planDigest:n.planDigest}),s=await Bi(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,trustedScripts:n.trustedScripts,observer:Ya(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Ja(e,t){let n=$a(e[Wa]),r=e[Ga].platform;return!n||r!==`android`&&r!==`ios`?[]:Aa(t,n.selector,r).ranked.map(e=>({node:e,basis:eo(n.selector,e)}))}function Ya(e,t,n){return{commandStarted:e=>t?.actionStarted?.(Xa(e)),commandCompleted:e=>t?.actionCompleted?.({...Xa(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=si(e,{from:r.stepIndex,planDigest:e.digest}),a={...Xa(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:Nr(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Wa]:r.command,[Ga]:e};n(a),t?.actionFailed?.(a)}}}function Xa(e){let t=Hi(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Za(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(Qa)}function Qa(e){return!!(e?.trim()&&!e.includes(`$`)&&!m(e))}function $a(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function eo(e,t){return e.id!==void 0||e.text!==void 0&&aa({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}function W(e,t){return F({appId:e.appId,env:e.env,generation:e.generation,invalidateObservation:e.invalidateObservation,source:t?.source,cachedObservation:e.cachedObservation,signal:e.signal})}function to(e){return F({env:e.env,generation:e.generation,cachedObservation:e.cachedObservation,signal:e.signal})}async function no(e,t){let n=so(await t.observe({condition:e.condition,timeoutMs:e.timeoutMs},to(e)),e.generation),r={kind:`selector`,selector:e.condition.selector,visible:n.visible,candidateCount:n.candidateCount,...n.ref?{ref:n.ref}:{}};return{generation:e.generation,matched:ro(e.condition,n),candidateCount:n.candidateCount,evidence:r}}function ro(e,t){return e.kind===`visible`?t.matched&&t.visible:!t.matched||!t.visible}async function io(e,t,n,r){let i=so(await r.resolveTarget({selector:e,...t},W(n,n.command)),n.generation);if(!i.matched||!i.visible||!i.rect)throw di(`Maestro target did not resolve to a visible element.`,{selector:e,candidateCount:i.candidateCount});return{kind:`selector`,selector:e,query:{selector:e,...t},...i,rect:i.rect}}function ao(e){let t={kind:`selector`,selector:e.selector,visible:e.visible,candidateCount:e.candidateCount,...e.ref?{ref:e.ref}:{}};return{generation:e.generation,matched:e.matched&&e.visible,candidateCount:e.candidateCount,evidence:t}}function oo(e){if(!e||typeof e!=`object`)return!1;let t=e;return[`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`&&Number.isFinite(t[e]))}function so(e,t){return co(e,t),lo(e),uo(e),fo(e),e}function co(t,n){if(t.generation!==n)throw new e(`COMMAND_FAILED`,`Maestro target evidence generation ${t.generation} does not match ${n}.`)}function lo(t){if(!Number.isInteger(t.candidateCount)||t.candidateCount<0)throw new e(`COMMAND_FAILED`,`Maestro target evidence has an invalid candidate count.`)}function uo(t){if(t.rect!==void 0&&!oo(t.rect)||t.viewport!==void 0&&!oo(t.viewport))throw new e(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function fo(t){if(t.surfaceSignature!==void 0&&typeof t.surfaceSignature!=`string`)throw new e(`COMMAND_FAILED`,`Maestro target evidence has an invalid surface signature.`)}function po(e,t,n,r,i,a={}){let o=mo(e,t,n,i,a);if(!o)return;let{start:s,end:c}=yo(o,n);return{gesture:{from:s,to:c,durationMs:r},viewport:o}}function mo(e,t,n,r,i){let a=n===`up`||n===`down`,o=Ma(e,Da(e,r),i),s=o.visibility,c=oa({visibility:s,matches:e.nodes.filter(e=>pe(e)),platform:r}),l=de(s.viewportRects)??go(c);if(!l||!D(l))return;let u=c.flatMap(e=>{if(!D(e.rect))return[];let t=_o(e.rect,l);return!t||(a?t.height<=t.width:t.width<t.height)?[]:[{node:e,viewport:t}]}),d=new Map(u.map(e=>[e.node.index,e]));for(let e of o.resolve(t).indexed){let t=ho(e,s.nodeByIndex),n=t?d.get(t.index):void 0;if(n)return n.viewport}return u.sort(vo)[0]?.viewport}function ho(e,t){return pe(e)?e:Oe(e,t)}function go(e){let t;for(let n of e)D(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function _o(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width)-n,a=Math.min(e.y+e.height,t.y+t.height)-r;return i>0&&a>0?{x:n,y:r,width:i,height:a}:void 0}function vo(e,t){return t.viewport.width*t.viewport.height-e.viewport.width*e.viewport.height}function yo(e,t){let n=G(e,.5,.5),r=I.scrollUntilVisibleSwipe.nearEdgeFraction,i=I.scrollUntilVisibleSwipe.farEdgeFraction;switch(t){case`up`:return{start:n,end:G(e,.5,i)};case`down`:return{start:n,end:G(e,.5,r)};case`left`:return{start:n,end:G(e,i,.5)};case`right`:return{start:n,end:G(e,r,.5)}}}async function bo(t,n,r){let i=V(t.duration,`swipe.duration`);if(t.kind===`coordinates`){if(t.start.space!==t.end.space)throw new e(`INVALID_ARGS`,`Maestro swipe endpoints must use the same coordinate space.`);let a=t.start.space===`percent`?await r.resolveGestureViewport(W(n,n.command)):void 0;return{authored:t,gesture:So(await xo(t.start,n,r,a),await xo(t.end,n,r,a),i),...a?{viewport:a}:{}}}if(t.kind===`screen`){let e=await r.resolveGestureViewport(W(n,n.command)),{start:a,end:o}=Co(e,t.direction,r.platform);return{authored:t,gesture:So(a,o,i),viewport:e}}let a=await io(t.from,{purpose:`swipe`,timeoutMs:`optional`in n.command&&n.command.optional===!0?I.command.optionalTargetLookupTimeoutMs:I.command.targetLookupTimeoutMs},n,r),o=a.viewport??await r.resolveGestureViewport(W(n,n.command)),{start:s,end:c}=wo(a,t.direction,o);return{authored:t,gesture:So(s,c,i),target:a,viewport:o}}async function xo(e,t,n,r){if(e.space===`absolute`)return{x:e.x,y:e.y};let i=r??await n.resolveGestureViewport(W(t,t.command));return{x:i.x+Math.trunc(i.width*e.x/100),y:i.y+Math.trunc(i.height*e.y/100)}}function So(e,t,n){return{from:e,to:t,durationMs:n??I.command.swipeDurationMs}}function Co(e,t,n){if(t===`left`||t===`right`){let n=je(t,{referenceWidth:e.width,referenceHeight:e.height});return{start:{x:e.x+n.x1,y:e.y+n.y1},end:{x:e.x+n.x2,y:e.y+n.y2}}}let r=I.screenSwipe,i=G(e,r.centerFraction,r.nearEdgeFraction),a=G(e,r.centerFraction,r.farEdgeFraction),o=G(e,r.centerFraction,r.downStartFraction),s=G(e,r.centerFraction,r.upStartFraction[n]);return t===`up`?{start:s,end:i}:{start:o,end:a}}function G(e,t,n){return{x:e.x+Math.trunc(e.width*t),y:e.y+Math.trunc(e.height*n)}}function wo(e,t,n){let r=j(e.rect),i=n.x+Math.trunc(n.width*I.targetSwipe.nearEdgeFraction),a=n.y+Math.trunc(n.height*I.targetSwipe.nearEdgeFraction),o=n.x+Math.trunc(n.width*I.targetSwipe.farEdgeFraction),s=n.y+Math.trunc(n.height*I.targetSwipe.farEdgeFraction);switch(t){case`up`:return{start:r,end:{x:r.x,y:a}};case`down`:return{start:r,end:{x:r.x,y:s}};case`left`:return{start:r,end:{x:i,y:r.y}};case`right`:return{start:r,end:{x:o,y:r.y}}}}const To={launchApp:Ao,stopApp:Ao,clearState:Ao,openLink:Ao,tapOn:Mo,doubleTapOn:Mo,longPressOn:Mo,swipe:Lo,inputText:Ro,eraseText:Ro,scroll:K,scrollUntilVisible:K,hideKeyboard:K,pressKey:K,back:K,waitForAnimationToEnd:K,takeScreenshot:Vo,runScript:Vo,evalScript:Uo,assertVisible:Ho,assertNotVisible:Ho,assertTrue:Ho,extendedWaitUntil:Ho},Eo={launchApp:!0,stopApp:!0,clearState:!0,openLink:!0,tapOn:!0,doubleTapOn:!0,longPressOn:!0,swipe:!0,inputText:!0,eraseText:!0,scroll:!0,scrollUntilVisible:!0,hideKeyboard:!0,pressKey:!0,back:!0,waitForAnimationToEnd:!0,takeScreenshot:!1,runScript:!1,evalScript:!1,assertVisible:!1,assertNotVisible:!1,assertTrue:!1,extendedWaitUntil:!1};function Do(e){return Eo[e.kind]}async function Oo(e,t){let n=e.command;return await ko(n,e,t,W(e,n))}function ko(e,t,n,r){let i=To[e.kind];return i(e,t,n,r)}async function Ao(e,t,n,r){switch(e.kind){case`launchApp`:return await q(n.launchApp,jo(e,t),r,`invalidate`);case`stopApp`:return await q(n.stopApp,{appId:e.appId??t.appId},r,`invalidate`);case`clearState`:return await q(n.clearState,{appId:e.appId??t.appId},r,`invalidate`);case`openLink`:return await q(n.openLink,{link:e.link},r,`invalidate`)}}function jo(e,t){return F({appId:e.appId??t.appId,stopApp:e.stopApp,clearState:e.clearState,arguments:e.arguments,launchArguments:e.launchArguments})}async function Mo(e,t,n,r){switch(e.kind){case`tapOn`:return await No(e,t,n,r);case`doubleTapOn`:{let i=await Zo(e.target,{purpose:`doubleTap`,timeoutMs:Fo(e)},t,n),a=V(e.delay,`doubleTapOn.delay`)??I.command.repeatDelayMs;return await q(n.doubleTapOn,{target:i,delay:a},r,`invalidate`,i.resolution?ao(i.resolution):void 0)}case`longPressOn`:{let i=await Zo(e.target,{purpose:`longPress`,timeoutMs:Fo(e)},t,n);return await q(n.longPressOn,{target:i},r,`invalidate`,i.resolution?ao(i.resolution):void 0)}}}async function No(e,t,n,r){let i=await Po(e,t,n);return await q(n.tapOn,Io(e,i),r,`invalidate`,i.resolution?ao(i.resolution):void 0)}async function Po(e,t,n){let r={purpose:`tap`,timeoutMs:Fo(e),allowAtomicSelectorDispatch:e.repeat===void 0&&e.delay===void 0,...e.retryTapIfNoChange===!0?{includeSurfaceSignature:!0}:{}};return await Zo(e.target,r,t,n)}function Fo(e){return e.optional===!0?I.command.optionalTargetLookupTimeoutMs:I.command.targetLookupTimeoutMs}function Io(e,t){let n=V(e.repeat,`tapOn.repeat`),r=V(e.delay,`tapOn.delay`),i=n===void 0?r:r??I.command.repeatDelayMs;return F({target:t,retryTapIfNoChange:e.retryTapIfNoChange,repeat:n,delay:i})}async function Lo(e,t,n,r){let i=await bo(e.gesture,t,n);return await q(n.gesture,i.gesture,{...r,...i.viewport?{gestureViewport:i.viewport}:{}},`invalidate`,i.target?ao(i.target):void 0)}async function Ro(e,t,n,r){switch(e.kind){case`inputText`:return await q(n.inputText,F({text:e.text,label:e.label}),r,`invalidate`);case`eraseText`:return await q(n.eraseText,F({charactersToErase:V(e.charactersToErase,`eraseText.charactersToErase`)}),r,`invalidate`)}}async function K(e,t,n,r){switch(e.kind){case`scroll`:return await q(n.scroll,{direction:`down`},r,`invalidate`);case`scrollUntilVisible`:return await q(n.scrollUntilVisible,zo(e),r,`invalidate`);case`hideKeyboard`:return await q(n.hideKeyboard,{},r,`invalidate`);case`pressKey`:return await q(n.pressKey,{key:e.key},r,`invalidate`);case`back`:return await q(n.back,{},r,`invalidate`);case`waitForAnimationToEnd`:return await q(n.waitForAnimationToEnd,Bo(e),r,`preserve`)}}function zo(e){return{selector:e.element,direction:e.direction??`down`,timeoutMs:V(e.timeout,`scrollUntilVisible.timeout`)??I.command.scrollUntilVisibleTimeoutMs,durationMs:Nn(I.command.scrollUntilVisibleSpeed)}}function Bo(e){return F({timeoutMs:V(e.timeout,`waitForAnimationToEnd.timeout`)})}async function Vo(e,t,n,r){switch(e.kind){case`takeScreenshot`:return Go(await n.takeScreenshot({path:e.path},r),[],void 0,r.generation);case`runScript`:return await q(n.runScript,F({file:e.file,env:e.env}),r,`preserve`)}}async function Ho(t){throw new e(`COMMAND_FAILED`,`Maestro ${t.kind} must be executed by the observation engine.`)}function Uo(t){throw new e(`COMMAND_FAILED`,`Maestro evalScript must be executed by the compute engine at ${t.source.path??``}line ${t.source.line}.`)}async function q(e,t,n,r,i){let a=Wo(n,r);return Go(await e(t,a),[],r===`preserve`?i:void 0,a.generation)}function Wo(e,t){return t===`preserve`?e:(e.invalidateObservation(),{...e,generation:e.generation+1})}function Go(e,t,n,r){let i=e?.observation;return Ko(i,r),{...qo(n??i),...Jo(e?.outputEnv),...Yo(t,e?.artifactPaths),...Xo(e?.data),...e?.visualStabilityReached===void 0?{}:{visualStabilityReached:e.visualStabilityReached}}}function Ko(t,n){if(!(!t||n===void 0||t.generation===n))throw new e(`COMMAND_FAILED`,`Maestro operation evidence generation ${t.generation} does not match ${n}.`)}function qo(e){return e?{observation:e}:{}}function Jo(e){return e?{outputEnv:{...e}}:{}}function Yo(e,t){let n=[...new Set([...e,...t??[]])];return n.length>0?{artifactPaths:n}:{}}function Xo(e){return e&&Object.keys(e).length>0?{data:{...e}}:{}}async function Zo(e,t,n,r){if(e.space===`target`){let i=await io(e.selector,t,n,r);return{authored:e,point:j(i.rect),resolution:i}}return{authored:e,point:await xo(e,n,r)}}function Qo(e,t,n,r={}){let i=n===`ios`&&r.presentation?es(r.presentation):void 0,a=i?ts(e,t,i):Aa(e,t.selector,n);if(!a.parentMatched)return{ok:!1,message:`Maestro childOf parent did not match.`,evidence:as(t,a.matches,[],void 0)};let{matches:o,ranked:s}=a,c=i?Fa(s,t.selector.index):Pa(s,t.selector.index)?.node,l=as(t,o,s,c);if(!c)return ns(t,o,s,l);let u=i?Pa(i.visibleForSource(c),void 0):null,d=Ia(c),f=r.interactiveBounds?u?.rect??d:d??u?.rect;return f?{ok:!0,node:c,rect:f,matches:s.length,dispatchCandidates:n===`ios`&&t.allowAtomicSelectorDispatch&&!$o(t.selector)&&i?rs(d,s,u):0,evidence:l}:ns(t,o,s,l)}const $o=la;function es(e){let t=oe(e.snapshot.nodes),n=t.nodeByIndex,r=new Map,i=t=>(e.presentedIndexesBySourceIndex.get(t.index)??[]).flatMap(e=>{let t=n.get(e);return t?[t]:[]}),a=e=>{let n=r.get(e.index);if(n)return n;let a=i(e).filter(e=>ra(e,t,`ios`));return r.set(e.index,a),a};return{visibleForSource:a,isVisible:e=>a(e).length>0}}function ts(e,t,n){let r=Da(e,`ios`),i=ga(e,{},{orderUnindexed:e=>Oa(e,r)}),a=ja(t.selector,i),o=a.matches.filter(n.isVisible);return{...a,visible:o,clickability:r,ranked:Na(o,t.selector,`ios`,i.visibility,r)}}function ns(e,t,n,r){return t.length>0&&n.length===0?{ok:!1,message:`Maestro selector matched ${t.length} element(s), but none were visible.`,evidence:r}:{ok:!1,message:`Maestro selector did not match${e.selector.index===void 0?``:` index ${e.selector.index}`}.`,evidence:r}}function rs(e,t,n){return t.length===1?e&&n&&n.node.hittable!==!1&&is(n.rect,e)?1:0:t.length}function is(e,t){let n=j(e),r=j(t);return n.x===r.x&&n.y===r.y}function as(e,t,n,r){return F({selector:e.selector,matched:t.length>0,visible:n.length>0,candidateCount:t.length,ref:r?.ref})}const J={settleTimeoutMs:Pn,retryTapMaxAttempts:I.command.retryTapMaxAttempts,longPressDurationMs:I.command.longPressDurationMs,eraseTextMaxCharacters:I.command.eraseTextMaxCharacters,scrollUntilVisiblePercentage:I.command.scrollUntilVisiblePercentage,animationWaitTimeoutMs:I.command.waitForAnimationToEndTimeoutMs,animationDifferencePercent:I.command.waitForAnimationToEndDifferencePercent,observationPollMs:I.observation.pollIntervalMs};function os(e,t={}){return{execute:async n=>{let r=W(n,n.command),i=n.command.kind===`waitForAnimationToEnd`;await t.beforeExecute?.({context:r,requiresSettledPredecessor:Do(n.command)&&!i,visualStabilityBarrier:i});let a=await Oo(n,e);return t.afterExecute?.({context:r,visualStabilityReached:i&&a.visualStabilityReached===!0}),delete a.visualStabilityReached,a},observe:async n=>{let r=await no(n,e);return t.bindObservation?.(r)??r},...t.readMetrics?{readMetrics:t.readMetrics}:{}}}const ss=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function cs(t,n){let r=t.files[n];if(r===void 0)throw new e(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:t.entry});return r}function ls(e){let t=us(e),n=we(t);return Hn(`sha256`).update(n,`utf8`).digest(`hex`)}function us(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>ds(e,n[t]??null,r?.[t]??null))}}function ds(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,targetEvidences:e.targetEvidences??null,source:{path:n,line:t}}}function fs(e,t,n){let{from:r,digest:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e;if(r===void 0&&i===void 0)return{ok:!0,value:0};if(r===void 0||i===void 0)return{ok:!1,message:`replay --from requires --plan-digest (and --plan-digest requires --from).`};let s=ps({from:r,digest:i,planDigest:n,actionCount:t,pendingRecordAndHeal:a,sessionActionsLength:o});return s?{ok:!1,message:s}:{ok:!0,value:r-1}}function ps(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>ms({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>hs({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>gs(n,r)];for(let e of s){let t=e();if(t)return t}}function ms(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function hs(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(n?.expectedFrom===t&&r===n.actionsCountAtDivergence)return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function gs(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function _s(t,n){let r=t.trimStart()[0];if(r===`{`||r===`[`)throw new e(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let i=Fe(t),a=Le(t),o=ls({actions:i.actions,actionLines:i.actionLines,actionSourcePaths:i.actionSourcePaths,metadata:{platform:n?.platform??Me(i.actions)??a.platform,target:n?.target??a.target}}),s=i.actions.length;return{actions:i.actions,actionLines:i.actionLines,actionSourcePaths:i.actionSourcePaths,metadata:a,planDigest:o,resolveEntryIndex:e=>fs(e,s,o)}}function vs(e){let{recorded:t,isSelectorWait:n}=e;return n?t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`deferred-landmark`,landmark:t}:{kind:`skip`}}function ys(e){let{recorded:t,token:n}=e;return n===void 0||!n.startsWith(`@`)&&Ce(`positional`,[n]).kind!==`expression`?{kind:`skip`}:t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`verify`,token:n}}function bs(e,t){if(!(!e||!t)&&(e.documentOrder!==t.documentOrder||e.sibling!==t.sibling))return`position: recorded=doc${e.documentOrder}/sibling${e.sibling} observed=doc${t.documentOrder}/sibling${t.sibling}`}function xs(e,t,n){let{observed:r,expectedStructural:i,observedStructural:a}=t,o=bs(i,a);return{matchCount:n,observed:r,mismatches:[...r?ae(e,r):[],...o?[o]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}}function Ss(e,t){let{matchCount:n,observed:r,observedAncestry:i}=t;return{matchCount:n,observed:r,mismatches:r?[...ae(e,r),...ke(e.ancestry,i)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}}async function Cs(e,t,n,r,i,a){if(n.targetEvidences)return ws(e,t,n,r,i,a);let o=n.targetEvidence;if(!o)return Y(e,n,r,i,a);let s=e.beginTargetVerification(n,r,i);if(s.kind===`inactive`)return Y(e,n,r,i,a);if(s.kind===`post-resolution`){let c=vs({recorded:o,isSelectorWait:s.isSelectorWait});switch(c.kind){case`skip`:return Y(e,n,r,i,a);case`recorded-unverifiable`:return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};case`deferred-landmark`:return Es(e,t,n,r,i,a,{kind:`landmark`,landmark:c.landmark})}}let c=ys({recorded:o,token:s.token});if(c.kind===`skip`)return Y(e,n,r,i,a);if(c.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};let l=c.token,u=await e.captureObservation(n,i,{retryLaunchRace:!0});if(u.state!==`available`)return{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,Ts(u),a,t)};let d=e.classifyTarget({action:n,index:i,token:l,nodes:u.nodes});return d.verified?Es(e,t,n,r,i,a,{kind:`target`,guard:d.guard}):{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,{kind:d.kind,matchCount:d.matchCount,observed:d.observed,candidateNodes:d.candidateNodes,mismatches:d.mismatches,causeCode:d.causeCode,causeMessage:d.causeMessage},a,t)}}async function ws(e,t,n,r,i,a){let o=n.targetEvidences,s={};for(let c of[`source`,`destination`]){let l={...n,targetEvidence:o[c]},u=e.beginTargetVerification(l,r,i,c);if(u.kind!==`pre-dispatch`)return Y(e,n,r,i,a);let d=ys({recorded:o[c],token:u.token});if(d.kind===`skip`)return Y(e,n,r,i,a);if(d.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(l,i,a,t)};let f=await e.captureObservation(l,i,{retryLaunchRace:!0});if(f.state!==`available`)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,Ts(f),a,t)};let p=e.classifyTarget({action:l,index:i,token:d.token,nodes:f.nodes});if(!p.verified)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,{kind:p.kind,matchCount:p.matchCount,observed:p.observed,candidateNodes:p.candidateNodes,mismatches:p.mismatches,causeCode:p.causeCode,causeMessage:p.causeMessage},a,t)};s[c]=p.guard}return Es(e,t,n,r,i,a,{kind:`targets`,guards:{source:s.source,destination:s.destination}})}function Ts(e){return{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${e.reason}).`,...e.hint===void 0?{}:{causeHint:e.hint}}}async function Y(e,t,n,r,i){let a=await e.dispatchStep(t,n,r,i,void 0);switch(a.status){case`ok`:return{status:`ok`,artifactPaths:a.artifactPaths};case`failed`:return{status:`failed`,failure:a.failure};case`guard-mismatch`:case`landmark-mismatch`:return{status:`failed`,failure:a.plainFailure}}}async function Es(e,t,n,r,i,a,o){let s=await e.dispatchStep(n,r,i,a,o);if(s.status===`ok`)return{status:`ok`,artifactPaths:s.artifactPaths};if(s.status===`failed`)return{status:`failed`,failure:s.failure};let c=Ds(n,o,s);if(!c)return{status:`failed`,failure:s.plainFailure};let l=Os(c.recorded,c.matchCount,s);return{status:`failed`,failure:await e.buildPostDispatchTargetBindingFailure(c.reportAction,i,{kind:`identity-mismatch`,matchCount:l.matchCount,observed:l.observed,candidateNodes:[],mismatches:l.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:l.causeMessage},a,t)}}function Ds(e,t,n){if(n.status!==`guard-mismatch`||t.kind!==`targets`)return e.targetEvidence?{recorded:e.targetEvidence,reportAction:e,matchCount:t.kind===`target`?t.guard.matchCount:0}:void 0;let r=n.evidence.targetRole??`source`,i=e.targetEvidences?.[r];return i?{recorded:i,reportAction:{...e,targetEvidence:i},matchCount:t.guards[r].matchCount}:void 0}function Os(e,t,n){return n.status===`guard-mismatch`?xs(e,n.evidence,t):Ss(e,n.evidence)}async function ks(e,t){let{actions:n,entryIndex:r,keepSession:i}=e,a=Ye(e.varSources),o=[],s=[],c=Ns(n),l=0;for(let u=r;u<n.length;u+=1){let r=n[u];if(!Ms(r)||(t.armStep(),u===c&&(i||t.isRepairArmed())))continue;if(l+=1,t.onStep){let e=t.describeStepValue(r);t.onStep(Ps(u,n.length,r,e))}let d=nt(r,a,js(e,u)),f=qe(a),p=t.diagnosticsMarker(),m=await Cs(t,f,r,d,u,o);if(s.push(...t.diagnosticsSince(p)),m.status===`ok`){o=m.artifactPaths;continue}let h=await t.handleActionFailure({action:r,index:u,artifactPaths:As(o,m.failure.artifactPaths),snapshotDiagnosticSamples:s,scrubVars:f});return{status:`failed`,stepIndex:u,failure:h}}return{status:`completed`,replayed:l,artifactPaths:[...o],snapshotDiagnosticSamples:s}}function As(e,t){return t.length===0?e:[...new Set([...e,...t])]}function js(e,t){return{file:e.actionSourcePaths?.[t]??e.resolvedPath,line:e.actionLines[t]??1}}function Ms(e){return!!(e&&e.command!==`replay`)}function Ns(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(Ms(n))return n.command===`close`?t:void 0}}function Ps(e,t,n,r){return{index:e+1,total:t,command:n.command,...r===void 0?{}:{value:r}}}function Fs(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e.at(-1),n=t!==void 0&&/^\d+$/.test(t)?t:null,r=n===null?e.slice():e.slice(0,-1),i=Ce(`positional`,r);return i.kind!==`expression`||i.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:i.expression,selectorTimeout:n}}function Is(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),O(e.command)){let n=Ls(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let n=Ce(`is`,[...e.positionals]);n.kind===`expression`&&t.push(n.expression)}if(e.command===`wait`){let{selectorExpression:n}=Fs([...e.positionals]);n&&t.push(n)}return Se(t).filter(e=>e.trim().length>0)}function Ls(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&Rs(n)?t.slice(0,-1):t}function Rs(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function zs(e){let t=L.dirname(e),n=L.basename(e,L.extname(e));return L.join(t,`${n}.healed.ad`)}function Bs(e){let t=Vs({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:e.resumeStamper.sessionExists()});return e.resumeStamper.stampCorrectiveWatermark({resume:t,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),t}function Vs(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=Hs({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function Hs(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function Us(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!Ws(n))return`manual`;let i=Gs(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function Ws(e){return e.ancestry.length>0||e.scrollRegion!==void 0&&Ks(e.scrollRegion)}function Gs(e,t){let n=lt(t),r=Js(e.ancestry,n,t),i=e.scrollRegion;return i&&Ks(i)?r&&qs(i,n,t):r}function Ks(e){return e.id!==void 0||e.label!==void 0}function qs(e,t,n){return n.some(n=>Ue(Ke(n,t),e))}function Js(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=st(n,t,e.length);return!r.broken&&ue(r.chain,e)})}function Ys(e){let{sessionStore:t,observationStore:n,divergence:r,responseLevel:a}=e,o,s,c=wt({divergence:r,level:a,writeOverflowArtifact:e=>{let n=i(e),r=Qs(t,n);return`artifactPath`in r&&(o=n,s=r.artifactPath),r}}),l=(o??c).screen;if(l.state!==`available`||l.refs.length===0)return e.evidence&&n.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.state===`available`?l.refsGeneration:void 0,refs:[]}),c;if(!e.evidence)return Zs(s),Xs(c,`missing-evidence`);let u=n.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.refsGeneration,refs:l.refs.map(e=>e.ref)});return u.published===!0?c:(Zs(s),Xs(c,u.reason))}function Xs(e,t){let{overflow:n,...r}=e;return{...r,screen:{state:`unavailable`,reason:`ref-publication-${t}`,hint:`The replay observation changed before its refs could be published. Take a new snapshot before targeting an element.`},suggestions:e.suggestions.map(({ref:e,...t})=>t),...e.targetBinding?{targetBinding:{...e.targetBinding,candidates:e.targetBinding.candidates.map(({ref:e,...t})=>t)}}:{}}}function Zs(e){if(e)try{R.unlinkSync(e)}catch{}}function Qs(e,t){try{let n=L.join(e.ensureSessionDir(),`replay-divergence`);R.mkdirSync(n,{recursive:!0});let r=`${Date.now()}-step${t.step.index}.json`,i=L.join(n,r);return R.writeFileSync(i,`${JSON.stringify(t,null,2)}\n`),{artifactPath:i}}catch{return{artifactUnavailable:!0}}}const $s={id:0,"role-label":1,label:2,other:3};function ec(e){let t=new Map;for(let n of e){let e=t.get(n.nodeIndex);(!e||tc(n.basis)<tc(e.basis))&&t.set(n.nodeIndex,n)}return[...t.values()].sort((e,t)=>tc(e.basis)-tc(t.basis)||e.nodeIndex-t.nodeIndex)}function tc(e){return $s[e]}async function nc(e){let{error:t,action:n,index:r,sourcePath:i,sourceLine:a,session:o,sessionStore:s,observationStore:c,resumeStamper:l,logPath:u,responseLevel:d,scrubVars:f=[],planActions:p,planDigest:m,signal:h}=e,g=Ct(f),_={code:t.code,message:g(t.message),...t.hint?{hint:g(t.hint)}:{}},v=o?await ac({session:o,observationStore:c,logPath:u,action:n}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},y=lc(v,g),b=v.state===`available`&&o?mc({action:n,session:o,nodes:v.nodes,sanitize:g}):[],x=Us({kind:`action-failure`,targetEvidence:n.targetEvidence,capture:rc(v)}),S=Bs({failedIndex:r+1,actions:p,planDigest:m,repairHint:x,resumeStamper:l});return Ys({sessionStore:s,observationStore:c,divergence:{version:1,kind:`action-failure`,step:{index:r+1,source:{path:g(i),line:a}},action:g(Pe(n)),cause:_,screen:y,suggestions:b.slice(0,5),suggestionCount:b.length,resume:S,repairHint:x},responseLevel:d,evidence:v.state===`available`?v.evidence:void 0,...h?{signal:h}:{}})}function rc(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const ic=[300,500,800,1200,2e3,3e3,4e3];async function ac(e){let{session:t,observationStore:n,logPath:r,action:i,retryLaunchRace:a=!1}=e,o=sc(i),s=Date.now()+12e3,c=await oc({session:t,observationStore:n,logPath:r,flags:o});if(!a)return c.observation;for(let e of ic){if(c.observation.state===`available`||!c.retryable)break;let i=s-Date.now();if(i<=0)break;await yt(Math.min(e,i)),c=await oc({session:t,observationStore:n,logPath:r,flags:o})}return c.observation}async function oc(e){let{session:t,observationStore:n,logPath:r,flags:i}=e;try{let e=(await n.capture({flags:i,logPath:r})).snapshot;if(In(e.snapshotQuality))return{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0};let a=n.bindAuthority().store(e);return{observation:{state:`available`,nodes:e.nodes,refsGeneration:a.refsGeneration,evidence:a.evidence,appBundleId:t.appBundleId},retryable:!1}}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:Ot(e)}}}function sc(e){return{snapshotInteractiveOnly:cc(e)}}function cc(e){return!hc(e.command)||gc(e).requiresRect}function lc(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=pc(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function uc(e){return!!ht(e,pt(e.type??`Element`))||e.hittable===!0}function dc(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function fc(e,t){let n=ut(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&uc(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>dc(e,t)),...o.filter(e=>!dc(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function pc(e,t,n){let{nodes:r,truncated:i}=fc(e,n);return{refs:r.map(e=>{let n=pt(e.type??`Element`),r=ht(e,n);return{ref:e.ref,role:t(n),...r?{label:t(r)}:{}}}),truncated:i}}function mc(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!hc(t.command))return[];let a=Is(t);return a.length===0?[]:_c({candidates:a,nodes:r,session:n,action:t,matching:gc(t),sanitize:i})}function hc(e){return O(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function gc(e){let t=O(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function _c(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=vc({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}return ec(s).map(e=>e.suggestion)}function vc(e){let{candidate:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=be(t,n,{platform:r.device.platform,requireRect:a.requiresRect,allowDisambiguation:a.allowDisambiguation});if(s)return{suggestion:yc({node:s.node,nodes:n,session:r,action:i,basis:s.basis,sanitize:o}),basis:s.basis,nodeIndex:s.node.index}}function yc(e){let{node:t,nodes:n,session:r,action:i,basis:a,sanitize:o}=e,s=ye(t,r.device.platform,{action:i.command===`fill`?`fill`:O(i.command)?`click`:`get`,nodes:n}),c=pt(t.type??`Element`),l=ht(t,c);return{selector:o(s.join(` || `)),basis:a,...t.ref?{ref:t.ref}:{},role:o(c),...l?{label:o(l)}:{}}}function bc(e){return{...e,hint:e.hint??Cc(e.details,`hint`),diagnosticId:e.diagnosticId??Cc(e.details,`diagnosticId`),logPath:e.logPath??Cc(e.details,`logPath`)}}function xc(e){let{error:t,action:n,step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c}=e;return Sc({error:t,actionLabel:Pe(n),action:n.command,positionals:Be(n)??[],step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c})}function Sc(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u,warnings:d}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:St(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:St(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{...Tc(t.details),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},...d&&d.length>0?{warnings:d.map(e=>St(e,u))}:{},divergence:l}}}}function Cc(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const wc=[`reason`,`recovery`,`retriable`,`snapshotQuality`,`supportedOn`,`systemSurface`];function Tc(e){if(!e)return{};let t={};for(let n of wc)e[n]!==void 0&&(t[n]=e[n]);return t}async function Ec(e){return await Dc({...e,snapshotDiagnostics:g(e.snapshotDiagnosticSamples)})}async function Dc(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scrubVars:l,req:u,sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,planActions:h,planDigest:g}=e;if(t.ok)return t;let _=Oc(t.error.details?.replaySource),v=bc(t.error),y=await nc({error:v,action:n,index:r,sourcePath:_?.path??a,sourceLine:_?.line??o,session:f.get(),sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,responseLevel:u.meta?.responseLevel,scrubVars:l,planActions:h,planDigest:g,signal:N(u.meta?.requestId)});return xc({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:l})}function Oc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(n!==void 0||r!==void 0)return{path:n,line:r}}function kc(e,t){if(e)try{R.appendFileSync(e,`${JSON.stringify(i(t))}\n`)}catch(t){k({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}async function Ac(t){let{req:r,sessionName:i,action:a,resolved:o,filePath:s,line:c,step:l,sourcePath:u,tracePath:d,invoke:f,resolvedSessionScope:p,dependencies:m}=t,h=Date.now();kc(d,{type:`replay_action_start`,ts:new Date(h).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:o.command,positionals:Be(o)??[]});let g;try{g=await Mc({req:r,sessionName:i,resolved:o,sourceAction:a,invoke:f,resolvedSessionScope:p,dependencies:m})}catch(t){if(!(t instanceof e))throw t;g={ok:!1,error:n(t)}}let _=Date.now();return kc(d,{type:`replay_action_stop`,ts:new Date(_).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:o.command,ok:g.ok,durationMs:_-h,resultTiming:g.ok?Pc(g.data):void 0,errorCode:g.ok?void 0:g.error.code}),jc(g,u??s,c)}function jc(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function Mc(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:a,resolvedSessionScope:o,dependencies:s}=e,c=Fc(t.flags,r.flags),l=i.command===`fill`?it(rt(i)):void 0;return l&&(c.recordAs=l),await a(Nc({token:t.token,session:n,flags:c,runtime:r.runtime,meta:t.meta,dispatch:{...t.dispatch,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:o??s.resolveSessionScope(t)}:{}}},r))}function Nc(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:Ne(n,e.flags?.pointerCount)}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:Re(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function Pc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function Fc(e,t){return h(e,{...t??{}})}function Ic(e){return Uc(e.ok?Rc(e.data):Lc(e.error.details?.artifactPaths))}function Lc(e){return Array.isArray(e)?e.filter(Hc):[]}function Rc(e){return e?[Vc(e.path),Vc(e.outPath),...zc(e.artifacts)].filter(Hc):[]}function zc(e){return Array.isArray(e)?e.map(Bc).filter(Hc):[]}function Bc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return Vc(t.localPath)??Vc(t.path)}function Vc(e){return typeof e==`string`?e:void 0}function Hc(e){return typeof e==`string`}function Uc(e){return[...new Set(e.filter(Wc))]}function Wc(e){try{return R.statSync(e).isFile()}catch{return!1}}function Gc(e){let{recorded:t,token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}=e,c=Kc({token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}),l=lt(r),u=fe(t),d=ot(c.matchedNodes,l,u,t.ancestry),f=d.filter(e=>He(r,e)===t.sibling),p=d.filter(e=>Ue(Ke(e,l),t.scrollRegion)),m=Ge(p)[t.viewportOrder]?.ref,h=Ve({winnerRef:c.winnerRef,matchedRefs:c.matchedNodes.map(e=>e.ref),identitySetRefs:d.map(e=>e.ref),siblingMatchRefs:f.map(e=>e.ref),regionMemberRefs:p.map(e=>e.ref),viewportCandidateRef:m}),g=c.matchedNodes.find(e=>e.ref===c.winnerRef);return h.outcome===`verified`&&g?{verified:!0,winnerNode:g,matchCount:c.matchedNodes.length}:h.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:c.matchedNodes.length,observedNode:void 0,candidateNodes:d.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,...Yc({classification:h,matchCount:c.matchedNodes.length,winnerNode:g,identitySet:d,byIndex:l,recorded:t})}}function Kc(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?qc(n,t,i,a):Jc(n,t,r,a,o)}function qc(e,t,n,r){let i=e=>e!==null&&(!r||!!e.rect),s=o(t),c=s?a(e,s):null;if(i(c))return{matchedNodes:[c],winnerRef:c.ref};let l=n?at(e,n):null;return i(l)?{matchedNodes:[l],winnerRef:l.ref}:{matchedNodes:[],winnerRef:``}}function Jc(e,t,n,r,i){let a=xe(t,e,{platform:n,requireRect:r,allowDisambiguation:i});if(a.kind===`resolved`)return{matchedNodes:[...a.matchedNodes],winnerRef:a.winner.ref};let o=dt(e,a.matchedNodes);return{matchedNodes:[...a.matchedNodes],winnerRef:o?.ref??``}}function Yc(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Xc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Xc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Xc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function Xc(e,t,n){let r=We(t),i=st(t,n,Math.max(e.ancestry.length,1)).chain;return[...ae(e,r),...ke(e.ancestry,i)].slice(0,5)}function Zc(e,t){let n=e.positionals??[];if(e.command===`gesture`){let e=ze(n);return e?e[t??`source`]:void 0}if(e.command===`get`)return n[1];if(e.command===`is`){let e=Ce(`is`,n);return e.kind===`expression`?e.expression:void 0}if(!O(e.command)&&e.command!==`fill`)return;let r=n[0];if(r!==void 0&&!($c(r)&&$c(n[1])))return r}function Qc(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function $c(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function el(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionStore:l,resumeStamper:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=Ct(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:ul(fe(n),h),...t.observed?{observed:ul(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>dl(e,h))},_=Us({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=Bs({failedIndex:i,actions:p,planDigest:m,repairHint:_,resumeStamper:u}),y={version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(Pe(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},b=Ys({sessionStore:l,observationStore:e.observationStore,divergence:y,responseLevel:d,evidence:t.publicationEvidence,...e.signal?{signal:e.signal}:{}});return xc({error:{code:t.causeCode,message:t.causeMessage},action:r,step:i,replayPath:s,artifactPaths:c,divergence:b,scrubVars:f})}function tl(e,t,n){let r=Ct(e.scrubVars);return el(e,{kind:t.kind,matchCount:t.matchCount,observed:t.observed,candidateNodes:t.candidateNodes,mismatches:t.mismatches,causeCode:t.causeCode,causeMessage:t.causeMessage,...t.causeHint===void 0?{}:{causeHint:t.causeHint},screen:lc(n,r),publicationEvidence:al(n),repairCapture:rc(n)})}async function nl(e){let{session:t,observationStore:n,logPath:r,action:i,unavailableHint:a}=e;return t?await ac({session:t,observationStore:n,logPath:r,action:i}):{state:`unavailable`,reason:`no-session`,hint:a}}async function rl(e,t){return tl(e,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`},await nl({...t,unavailableHint:`The session closed before a screen could be captured to verify the recorded target evidence.`}))}async function il(e,t,n){return tl(e,t,await nl({...n,unavailableHint:`The session closed before a post-failure screen could be captured.`}))}function al(e){return e.state===`available`?e.evidence:void 0}function ol(e){let{action:t,resolvedAction:n,sessionStore:r,targetRole:i}=e,a=r.get();return a?he(t.command)===`post-resolution`?{kind:`post-resolution`,isSelectorWait:Ee(n.positionals??[])?.kind===`selector`}:{kind:`pre-dispatch`,token:Zc(n,i),platform:a.device.platform}:{kind:`inactive`}}function sl(e){let{recorded:t,token:n,action:r,nodes:i,platform:a}=e,o=gc(r),s=Gc({recorded:t,token:n,nodes:i,platform:a,refLabel:Qc(r),requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});return s.verified?{verified:!0,guard:{expected:{identity:We(s.winnerNode),structural:ce(s.winnerNode,i)},matchCount:s.matchCount}}:{verified:!1,kind:s.kind,matchCount:s.matchCount,observed:s.observedNode?We(s.observedNode):void 0,candidateNodes:s.candidateNodes,mismatches:s.mismatches,causeCode:s.causeCode,causeMessage:s.causeMessage}}function cl(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}function ll(e){return!e.ok&&e.error.details?.reason===ct}function ul(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function dl(e,t){let n=pt(e.type??`Element`),r=ht(e,n);return{...e.ref?{ref:e.ref}:{},role:t(n),...r?{label:t(r)}:{}}}function fl(e,t){let n=t?.kind===`target`?{replayTargetGuard:t.guard.expected}:t?.kind===`targets`?{replayTargetGuards:{source:t.guards.source.expected,destination:t.guards.destination.expected}}:t?.kind===`landmark`?{replayLandmarkGuard:t.landmark}:void 0;return n?{...e,dispatch:{...e.dispatch,...n}}:e}function pl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function ml(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function hl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.documentOrder==`number`&&typeof t.sibling==`number`)return{documentOrder:t.documentOrder,sibling:t.sibling}}function gl(e){return{...e?.targetRole===`source`||e?.targetRole===`destination`?{targetRole:e.targetRole}:{},observed:pl(e?.observed),expectedStructural:hl(e?.expectedStructural),observedStructural:hl(e?.observedStructural)}}function _l(e){return{matchCount:typeof e?.matchCount==`number`?e.matchCount:void 0,observed:pl(e?.observed),observedAncestry:ml(e?.observedAncestry)}}function vl(e,t){return{kind:e.error.code,message:e.error.message,artifactPaths:t}}function yl(e,t,n){let r=vl(e,n);return(t?.kind===`target`||t?.kind===`targets`)&&cl(e)?{status:`guard-mismatch`,evidence:gl(e.error.details),plainFailure:r,artifactPaths:n}:t?.kind===`landmark`&&ll(e)?{status:`landmark-mismatch`,evidence:_l(e.error.details),plainFailure:r,artifactPaths:n}:{status:`failed`,failure:r}}function bl(e){let{ctx:t,req:n,artifactPaths:r,onStep:i,armSaveScript:a}=e,o,s,c=(e,n,r,i)=>({recorded:e.targetEvidence,action:e,step:n+1,sourcePath:t.actionSourcePaths?.[n]??t.resolved,sourceLine:t.actionLines[n]??1,replayPath:t.resolved,artifactPaths:[...r],sessionStore:t.sessionStore,observationStore:t.observationStore,resumeStamper:t.coordinator.resumeStamper,responseLevel:t.responseLevel,scrubVars:i,planActions:t.actions,planDigest:t.planDigest,signal:t.signal}),l=e=>(o=e,vl(xl(e),Ic(e)));return{runtime:{beginTargetVerification(e,n,r,i){return ol({action:e,resolvedAction:n,sessionStore:t.sessionStore,targetRole:i})},async captureObservation(e,n,r){let i=t.observationStore.get(),a=i?await ac({session:i,observationStore:t.observationStore,logPath:t.logPath,action:e,retryLaunchRace:r.retryLaunchRace}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a screen could be captured to verify the recorded target.`};return s=a,a.state===`available`?{state:`available`,nodes:a.nodes}:{state:`unavailable`,reason:a.reason,hint:a.hint}},classifyTarget({action:e,token:n,nodes:r}){let i=t.sessionStore.get();return sl({recorded:e.targetEvidence,token:n,action:e,nodes:[...r],platform:i.device.platform})},async dispatchStep(e,n,i,a,s){let c=t.actionLines[i]??1,l=await Ac({req:fl(t.replayReq,s),sessionName:t.sessionName,action:e,resolved:n,filePath:t.resolved,line:c,sourcePath:t.actionSourcePaths?.[i],step:i+1,tracePath:t.actionTracePath,invoke:t.invoke,resolvedSessionScope:t.resolvedSessionScope,dependencies:t.dependencies});o=l,Ic(l).forEach(e=>r.add(e));let u=[...r];return l.ok?{status:`ok`,artifactPaths:u}:yl(l,s,u)},async buildRecordedUnverifiableFailure(e,n,r,i){let a=await rl(c(e,n,r,i),{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(a)},async buildTargetBindingFailure(e,t,n,r,i){let a=s??{state:`unavailable`,reason:`observation-missing`,hint:`No capture was recorded before this target-binding failure.`},o=tl(c(e,t,r,i),n,a);return l(o)},async buildPostDispatchTargetBindingFailure(e,n,r,i,a){let o=await il(c(e,n,i,a),r,{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(o)},async handleActionFailure({action:e,index:r,artifactPaths:i,snapshotDiagnosticSamples:a,scrubVars:s}){let c=xl(o),u=await Sl(t,n,e,r,c,[...i],[...a],s);return l(u)},armStep:()=>{s=void 0,a()},isRepairArmed:()=>t.coordinator.view()?.repairBoundary!==void 0,describeStepValue:e=>Cl(e),onStep:i,diagnosticsMarker:()=>Tl(t.sessionStore),diagnosticsSince:e=>El(t.sessionStore,e)},readLastResponse:()=>o}}function xl(e){return e&&!e.ok?e:u(`COMMAND_FAILED`,`replay step reported failure with no recorded response`)}async function Sl(e,t,n,r,i,a,o,s){let c=t=>e.coordinator.markSessionHeldIfArmed(t);return wl(i)?c(i):c(await Ec({response:i,action:n,index:r,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[r]??e.resolved,sourceLine:e.actionLines[r]??1,artifactPaths:a,snapshotDiagnosticSamples:o,scrubVars:s,req:t,sessionStore:e.sessionStore,observationStore:e.observationStore,resumeStamper:e.coordinator.resumeStamper,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function Cl(e){let t=e.positionals??[],n=Te(t[0]);if(n)return n;if(t.length!==0)return t.join(` `)}function wl(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function Tl(e){return e.get()?.snapshotDiagnostics?.samples.length??0}function El(e,t){return e.get()?.snapshotDiagnostics?.samples.slice(t)??[]}function Dl(e){let t=Me(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return Al(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function Ol(e,t){return t===`ios`?jl(e)??{}:{}}function kl(e,t){let n=Dl(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function Al(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!m(e))}function jl(e){let t=yr(e);return t?{appleSimulatorAppTarget:t}:void 0}function Ml(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i}=e,a=t.flags??{},o={AD_SESSION:n,AD_FILENAME:Nl(t,i)};return Fl(o,`AD_PLATFORM`,a.platform??r.platform),Fl(o,`AD_TARGET`,a.target??r.target),Fl(o,`AD_DEVICE`,a.device),Fl(o,`AD_DEVICE_ID`,Pl(a)),Il(o,`AD_SHARD_INDEX`,a.shardIndex),Il(o,`AD_SHARD_COUNT`,a.shardCount),Fl(o,`AD_ARTIFACTS`,a.artifactsDir),o}function Nl(e,t){let n=e.meta?.cwd??process.cwd();return L.relative(n,t)||t}function Pl(e){return typeof e.serial==`string`?e.serial:e.udid}function Fl(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function Il(e,t,n){typeof n==`number`&&(e[t]=String(n))}const Ll=3e4,Rl=1e3;function zl(t){let{scriptPath:r,env:i,publicNetworkOnly:a}=t,o=R.readFileSync(r,`utf8`),s=Object.create(null);try{Kn.runInNewContext(o,Bl(i,s,a),{filename:r,timeout:Ll})}catch(t){let i=n(t);throw new e(i.code,`Maestro runScript failed: ${i.message}`,f({...i.details??{},hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,retriable:i.retriable,supportedOn:i.supportedOn,scriptPath:r}),t instanceof Error?t:void 0)}return ql(s,r),Object.fromEntries(Object.entries(s).map(([e,t])=>[`output.${e}`,Jl(t)]))}function Bl(e,t,n){return{...e,output:t,json:Vl,http:{post:(e,t)=>Ul(`POST`,e,n,t)}}}function Vl(t){if(typeof t!=`string`)throw new e(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof t}.`);if(t.trim().length===0)throw new e(`COMMAND_FAILED`,`Maestro runScript json() received an empty body.`,{hint:`Check the preceding HTTP response status and setup server output.`});try{return JSON.parse(t,Hl)}catch(n){throw new e(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${n instanceof Error?n.message:String(n)}`,{bodyPreview:t.slice(0,Rl)},n instanceof Error?n:void 0)}}function Hl(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function Ul(t,n,r,i){let a=vt(process.execPath,Wl(),{stdin:JSON.stringify(Kl(t,n,i,r)),timeoutMs:Ll,allowFailure:!0});if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`Maestro runScript http.${t.toLowerCase()} failed for ${n}: ${Yl(a.stderr)}`,{exitCode:a.exitCode,stderr:a.stderr});try{return JSON.parse(a.stdout)}catch(r){throw new e(`COMMAND_FAILED`,`Maestro runScript http.${t.toLowerCase()} returned invalid JSON for ${n}`,{stdout:a.stdout.slice(0,Rl),stderr:a.stderr.slice(0,Rl)},r instanceof Error?r:void 0)}}function Wl(){let t=Gl(import.meta.url);if(!t)throw new e(`COMMAND_FAILED`,`Maestro runScript http helper entrypoint is unavailable; rebuild the package`);return t.endsWith(`.ts`)?[`--experimental-strip-types`,t]:[t]}function Gl(e){try{let t=Wn(e),n=L.extname(t)||`.js`;return[L.join(L.dirname(t),`run-script-http-child`+n),L.join(L.dirname(t),`internal`,`run-script-http-child`+n)].find(e=>R.existsSync(e))??null}catch{return null}}function Kl(e,t,n,r){return{method:e,url:t,headers:n?.headers??{},body:n?.body??``,publicNetworkOnly:r}}function ql(t,n){for(let r of Object.keys(t))if(r.includes(`.`))throw new e(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:n,key:r})}function Jl(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function Yl(e){let t=e.trim();return t.length>0?t.slice(0,Rl):`request process exited without stderr`}async function Xl(e){return await Zl(`tap`,async t=>{let n=L.join(t,`before.png`),r=L.join(t,`after.png`),i=await $l(e,n);return await e.run({matchesCurrent:async()=>{if(!(!i||!await $l(e,r)))return await Ql(n,r,e.signal,`tap`)}})})}async function Zl(e,t){let n=await Bn.mkdtemp(L.join(Un.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await Bn.rm(n,{recursive:!0,force:!0})}catch{}}}async function Ql(e,t,n,r){try{let[i,a]=await Promise.all([Bn.readFile(e),Bn.readFile(t)]);X(n);let o=await Ln(i,a,`Maestro screenshot`);return X(n),eu(o,r)}catch(e){nu(e,n),k({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:r,result:`error`,error:e instanceof Error?e.message:String(e)}});return}}async function $l(e,t){try{return await Bn.rm(t,{force:!0}),X(e.signal),await e.capture(t),X(e.signal),!0}catch(t){return nu(t,e.signal),!1}}function eu(e,t){if(e.status!==`compared`)return tu(t,e.status,e),!1;let n=e.differencePercent<=J.animationDifferencePercent;return tu(t,n?`stable`:`changed`,e),n}function tu(e,t,n){k({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:e,result:t,first:n.first,second:n.second,...`differencePercent`in n?{differencePercent:n.differencePercent}:{}}})}function nu(e,n){if(n?.aborted||t(e))throw c()}function X(e){if(e?.aborted)throw c()}async function ru(e){au(e.timeoutMs),X(e.signal);let t=e.now()+e.timeoutMs;return await Zl(`animation`,async n=>{let r=L.join(n,`first.png`),i=L.join(n,`second.png`);for(;;){if(X(e.signal),await iu(e,r,i))return!0;if(e.now()>=t)return!1}})}async function iu(e,t,n){let r=[await $l(e,t),await $l(e,n)];return!r[0]||!r[1]?!1:await Ql(t,n,e.signal,`animation`)===!0}function au(t){if(!Number.isFinite(t)||t<0)throw new e(`INVALID_ARGS`,`waitForAnimationToEnd timeout must be a non-negative number.`)}const ou=J.observationPollMs;async function su(e,t){for(;;){Z(e.context.signal);try{return await e.snapshot(e.context)}catch(n){if(!Cu(n)||(Z(e.context.signal),!await xu(e.dependencies,t,ou,e.context.signal)))throw n}}}function cu(e){return lu({...e,mode:e.query.purpose===`swipe`?`swipe`:`tap`})}function lu(e){let t=wn(e.snapshot),n=e.platform===`ios`?Rn(e.snapshot.nodes):void 0,r=n?{...e.snapshot,nodes:l(n.nodes)}:e.snapshot;return mu(Qo(e.snapshot,e.query,e.platform,{interactiveBounds:e.mode===`tap`,presentation:n?{snapshot:r,presentedIndexesBySourceIndex:n.presentedIndexesBySourceIndex}:void 0}),e.snapshot,e.context.generation,t,e.query,e.platform,e.mode)}async function uu(e){Su(e.timeoutMs,`observation`);let t,n=e.dependencies.now()+e.timeoutMs;for(;;){Z(e.context.signal);let r=await su(e,n),i=lu({query:{selector:e.condition.selector},context:e.context,snapshot:r,platform:e.platform,mode:`observe`});if(t=i,ro(e.condition,i))return i;if(e.dependencies.now()>=n)break;await xu(e.dependencies,n,ou,e.context.signal)}return Z(e.context.signal),Eu(t)}async function du(e){Su(e.timeoutMs,`scrollUntilVisible`);let t=e.dependencies.now()+e.timeoutMs,n,r;for(;;){Z(e.context.signal);let i=r??await su(e,t);if(r=void 0,n=lu({query:{selector:e.selector},context:e.context,snapshot:i,platform:e.platform,mode:`observe`}),n.visiblePercentage===J.scrollUntilVisiblePercentage)return n;if(e.dependencies.now()>=t)break;let a=t-e.dependencies.now();a>0&&(r=await e.scroll(a,i))}return Z(e.context.signal),Eu(n)}async function fu(e){Su(e.timeoutMs,`waitForAnimationToEnd`);let t=e.dependencies.now()+e.timeoutMs,n=e.initialSnapshot??await su(e,t),r=wu(n);for(;;){Z(e.context.signal),await xu(e.dependencies,t,ou,e.context.signal);let i=await su(e,t),a=wu(i);if(a===r)return{snapshot:i,signature:a,settled:!0};if(n=i,r=a,e.dependencies.now()>=t)return{snapshot:n,signature:r,settled:!1}}}function pu(e){return e?{x:0,y:0,width:e.referenceWidth,height:e.referenceHeight}:void 0}function mu(e,t,n,r,i,a,o){if(!e.ok){let t=pu(r);return{generation:n,matched:e.evidence.matched,visible:e.evidence.visible,candidateCount:e.evidence.candidateCount,...e.evidence.ref?{ref:e.evidence.ref}:{},...t?{viewport:t}:{}}}let s=gu({query:i,platform:a,mode:o,dispatchCandidates:e.dispatchCandidates}),c=pu(r);return{generation:n,matched:!0,visible:!0,...c?{visiblePercentage:hu(e.rect,c)}:{},candidateCount:e.evidence.candidateCount,rect:e.rect,...e.evidence.ref?{ref:e.evidence.ref}:{},...c?{viewport:c}:{},...s?{dispatchSelector:s}:{},...i.includeSurfaceSignature?{surfaceSignature:wu(t)}:{}}}function hu(e,t){return!D(e)||!D(t)?0:ge(t,e)?100:Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))*100/(e.width*e.height)}function gu(e){let{query:t,platform:n,mode:r,dispatchCandidates:i}=e;if(!(!_u(t,n,r)||i!==1))return vu(t.selector)}function _u(e,t,n){return t===`ios`&&n===`tap`&&e.allowAtomicSelectorDispatch===!0&&!$o(e.selector)}function vu(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);if(t.length!==1)return;let[n,r]=t[0];if(!yu(n)||typeof r!=`string`)return;let i=na(r)?.trim();return i?{key:n,value:i}:void 0}function yu(e){return e===`id`||e===`label`||e===`text`}async function bu(e,t,n){try{await e.sleep(t,n)}catch(e){throw n?.aborted?c():e}Z(n)}async function xu(e,t,n,r){let i=t-e.now();return i<=0?!1:(await bu(e,Math.min(n,i),r),!0)}function Z(e){if(e?.aborted)throw c()}function Su(t,n){if(!Number.isFinite(t)||t<0)throw new e(`INVALID_ARGS`,`${n} timeout must be a non-negative number.`)}function Cu(t){return t instanceof e&&t.details?.retriable===!0}function wu(e){return Hn(`sha256`).update(JSON.stringify([...e.nodes].sort((e,t)=>e.index-t.index).map(e=>({index:e.index,parentIndex:e.parentIndex,identifier:e.identifier??``,label:e.label??``,value:e.value??``,enabled:e.enabled??!1,selected:e.selected??!1,focused:e.focused??!1,bounds:Tu(e.rect)})))).digest(`hex`)}function Tu(e){if(e)return{left:Math.trunc(e.x),top:Math.trunc(e.y),right:Math.trunc(e.x+e.width),bottom:Math.trunc(e.y+e.height)}}function Eu(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Maestro observation completed without a snapshot result.`)}function Du(e){return e.kind===`clearState`?Mu(e):Ou(e)?ku(e):Bu(e)?Vu(e):Pu(e)}function Ou(e){return e.kind===`launchApp`||e.kind===`stopApp`||e.kind===`openLink`}function ku(e){switch(e.kind){case`launchApp`:return Au(e);case`stopApp`:return ju(e);case`openLink`:return Nu(e)}}function Au(e){return{command:`open`,positionals:e.appId?[e.appId]:[],flags:{...e.relaunch?{relaunch:!0}:{},...e.clearState?{clearAppState:!0}:{},...e.launchArgs.length>0?{launchArgs:e.launchArgs}:{}}}}function ju(e){return{command:`close`,positionals:e.appId?[e.appId]:[],dispatch:{closeAppOnly:!0}}}function Mu(e){return{command:`settings`,positionals:e.appId?[`clear-app-state`,e.appId]:[`clear-app-state`]}}function Nu(e){return{command:`open`,positionals:e.appId?[e.appId,e.link]:[e.link],...e.prewarmRunner?{flags:{maestro:{prewarmRunnerBeforeOpen:!0}}}:{}}}function Pu(e){switch(e.kind){case`gestureViewport`:return{command:`runtime`,positionals:[`gesture-viewport`]};case`typeText`:return{command:`type`,positionals:[e.text]};case`clickSelector`:return Fu(e);case`clickPoint`:return Iu(e);case`swipe`:return Lu(e);case`scroll`:return Ru(e);case`pressKey`:return zu(e)}}function Fu(e){return{command:`click`,positionals:[`${e.selector.key}=${JSON.stringify(e.selector.value)}`],flags:{...e.options,maestro:{allowNonHittableCoordinateFallback:!0,expectedTapPoint:e.expectedPoint}}}}function Iu(e){return{command:`click`,positionals:[String(e.point.x),String(e.point.y)],flags:{...e.options}}}function Lu(e){let{from:t,to:n,durationMs:r}=e.gesture;return{command:`gesture`,positionals:[],input:{kind:`pan`,origin:t,delta:{x:n.x-t.x,y:n.y-t.y},durationMs:r},flags:{postGestureStabilization:!1},dispatch:{gestureExecutionProfile:`endpoint-hold`,...e.viewport?{gestureViewport:e.viewport}:{}}}}function Ru(e){return{command:`scroll`,positionals:[e.direction],...e.durationMs===void 0?{}:{input:{direction:e.direction,durationMs:e.durationMs}},flags:{postGestureStabilization:!1}}}function zu(e){return e.key===`back`||e.key===`home`?{command:e.key,positionals:[]}:{command:`keyboard`,positionals:[e.key]}}function Bu(e){return e.kind===`screenshot`||e.kind===`snapshot`}function Vu(e){switch(e.kind){case`screenshot`:return{command:`screenshot`,positionals:[e.path],...e.stabilize===!1||e.captureBackend===`runner`?{flags:{...e.stabilize===!1?{screenshotNoStabilize:!0}:{},...e.captureBackend===`runner`?{maestro:{screenshotCaptureBackend:`runner`}}:{}}}:{}};case`snapshot`:return{command:`snapshot`,positionals:[],flags:{noRecord:!0},dispatch:{observationOnly:!0}}}}async function Hu(t,n){let r=Du(n),i=await t.invoke(f({...r,flags:Uu(t.flags,r.flags??{})}));if(!i.ok)throw Yu(i);if(n.kind===`gestureViewport`){let t=i.data?.viewport;if(typeof t!=`object`||!t||![`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`))throw new e(`COMMAND_FAILED`,`runtime gesture-viewport returned no valid viewport.`);return t}return i.data}function Uu(e,t){let n=e?.maestro===void 0&&t.maestro===void 0?void 0:{...e?.maestro,...t.maestro},r=f({...e,...t,maestro:n});return Object.keys(r).length>0?r:void 0}function Wu(e){return e?e.kind===`scalar`?[String(e.value)]:e.kind===`list`?e.values.map(String):Object.entries(e.values).flatMap(([e,t])=>[e,String(t)]):[]}function Gu(e,t){return{generation:t.generation,matched:t.matched&&t.visible,candidateCount:t.candidateCount,evidence:{kind:`selector`,selector:e,visible:t.visible,candidateCount:t.candidateCount,...t.ref?{ref:t.ref}:{}}}}function Ku(e){if(!e)return[];let t=[];if(typeof e.path==`string`&&t.push(e.path),Array.isArray(e.artifactPaths)&&t.push(...e.artifactPaths.filter(e=>typeof e==`string`)),Array.isArray(e.artifacts))for(let n of e.artifacts)typeof n.localPath==`string`?t.push(n.localPath):typeof n.path==`string`&&t.push(n.path);return[...new Set(t)]}function qu(t,n,r){if(L.isAbsolute(t))return t;let i=n.source?.path??r;if(!i)throw new e(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return L.resolve(L.dirname(i),t)}function Ju(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function Yu(t){let n=t.error,r=f({...n.details??{},hint:n.hint??Xu(n.details,`hint`),diagnosticId:n.diagnosticId??Xu(n.details,`diagnosticId`),logPath:n.logPath??Xu(n.details,`logPath`),retriable:n.retriable??Zu(n.details,`retriable`),supportedOn:n.supportedOn??Xu(n.details,`supportedOn`)});return new e(n.code,n.message,Object.keys(r).length?r:void 0)}function Xu(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Zu(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}function Qu(t){let n,r,i,a,o,s=0,c=0,l=async r=>{c+=1;let i=await Hu(t,{kind:`snapshot`});if(!i||!Array.isArray(i.nodes))throw new e(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=y(i,i);return n={generation:r.generation,snapshot:a},a};return{capture:async e=>{if(r?.generation===e.generation){let t=r.snapshot;return r=void 0,n={generation:e.generation,snapshot:t},t}return r=void 0,await l(e)},bindObservation:e=>{if(n?.generation!==e.generation)return e;let t=`maestro-observation-${++s}`;return n.observationIdentity=t,{...e,identity:t}},reuseObservation:e=>{if(e.cachedObservation?.generation===e.generation&&e.cachedObservation.identity!==void 0&&n?.generation===e.generation&&e.cachedObservation.identity===n.observationIdentity)return n.snapshot},readMetrics:()=>({hierarchyCaptures:c}),invalidate:e=>{i=n?.generation===e-1?{generation:e,snapshot:n.snapshot}:void 0,n=void 0,r=void 0},requireStability:e=>{o=e,a=i?.generation===e?i:void 0,i=void 0,r=void 0},consumeStabilityFromVisualWait:t=>{if(o!==void 0){if(o!==t.generation)throw new e(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${t.generation}.`);o=void 0,a=void 0,i=void 0,r=void 0}},prime:(e,t)=>{r={generation:e,snapshot:t}},settlePending:async i=>{if(o===void 0)return;if(o!==i.generation)throw new e(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${i.generation}.`);let s=n?.generation===i.generation?n.snapshot:a?.snapshot,c=await fu({timeoutMs:J.settleTimeoutMs,context:i,snapshot:l,dependencies:t.dependencies,...s?{initialSnapshot:s}:{}});return o=void 0,a=void 0,r={generation:i.generation,snapshot:c.snapshot},c}}}async function $u(e){let{input:t,context:n,snapshots:r,options:i}=e,a=i.dependencies.now()+t.timeoutMs,o=e.allowObservationReuse===!1?void 0:r.reuseObservation(n);for(;;){let e=i.dependencies.now(),s=o!==void 0;o??=await su({context:n,snapshot:r.capture,dependencies:i.dependencies},a);let c=cu({query:t,context:n,snapshot:o,platform:i.platform});if(ad(c,s))return c;if(o=void 0,!s){if(e>=a)return c;await xu(i.dependencies,a,ou,n.signal)}}}async function ed(e,t,n,r,i,a){let o=async()=>await rd(e,t,r,i,a.click);if(!a.retryIfNoChange){try{await o()}finally{t.requireStability(i.generation)}return}if(e.platform===`ios`){await Xl({signal:i.signal,capture:async t=>{n.screenshotCaptures+=1,await Hu(e,{kind:`screenshot`,path:t,stabilize:!1,captureBackend:`runner`})},run:async o=>await td(e,t,n,r,i,a.click,o)});return}await td(e,t,n,r,i,a.click)}async function td(e,t,n,r,i,a,o){let s=async()=>await rd(e,t,r,i,a),c=r.resolution?.surfaceSignature??(o?void 0:wu(await t.capture(i))),l=async()=>{let r=await fu({timeoutMs:J.settleTimeoutMs,context:i,snapshot:t.capture,dependencies:e.dependencies});return r.settled?n.settleLatches+=1:n.settleTimeouts+=1,r};try{let e=await nd({baselineSignature:c,screenshotBaseline:o,dispatch:s,settle:l,onRetry:()=>{n.tapRetries+=1}});t.prime(i.generation,e.snapshot)}catch(e){throw t.requireStability(i.generation),e}}async function nd(e){await e.dispatch();let t=await e.settle(),n=1;for(;(e.baselineSignature===void 0||t.signature===e.baselineSignature)&&n<J.retryTapMaxAttempts&&!(e.screenshotBaseline&&await e.screenshotBaseline.matchesCurrent()!==!0);)e.onRetry(),await e.dispatch(),n+=1,t=await e.settle();return t}async function rd(e,t,n,r,i){let a=n.resolution,o=a?.dispatchSelector;if(o&&n.point){t.invalidate(r.generation);try{await od(e,o,n.point,i);return}catch(n){if(!sd(n))throw n;let o=await $u({input:a.query,context:r,snapshots:t,options:e,allowObservationReuse:!1});if(!id(o))throw n;t.invalidate(r.generation),await cd(e,j(o.rect),i);return}}t.invalidate(r.generation),await cd(e,n.point,i)}function id(e){return e.matched&&e.visible&&e.rect!==void 0}function ad(e,t){return id(e)?!t||e.dispatchSelector!==void 0:!1}async function od(e,t,n,r){k({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`selector`,selectorKey:t.key,expectedPoint:n}}),await Hu(e,{kind:`clickSelector`,selector:t,expectedPoint:n,options:r})}function sd(e){let t=r(e);return t.code===`AMBIGUOUS_MATCH`||t.code===`ELEMENT_NOT_FOUND`||t.code===`ELEMENT_OFFSCREEN`||t.details?.reason===mt.selectorNotFound}async function cd(t,n,r){if(!n)throw new e(`COMMAND_FAILED`,`Maestro target did not resolve to a point.`);k({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`point`,point:n}}),await Hu(t,{kind:`clickPoint`,point:n,options:r})}function ld(e){let t=Qu(e),n={screenshotCaptures:0,tapRetries:0,settleLatches:0,settleTimeouts:0},r=e=>{e.settled?n.settleLatches+=1:n.settleTimeouts+=1},i=e.platform,a=t=>(t.kind===`screenshot`&&(n.screenshotCaptures+=1),Hu(e,t)),o=async(e,n,r=`none`)=>{t.invalidate(n.generation);try{return await e()}finally{r===`deferred`&&t.requireStability(n.generation)}},s=async(e,t,n=`none`)=>await o(()=>a(e),t,n),c=async(n,i)=>{_t(n),await s({kind:`typeText`,text:n},i);let a=await fu({timeoutMs:J.settleTimeoutMs,context:i,snapshot:t.capture,dependencies:e.dependencies});r(a),t.prime(i.generation,a.snapshot)};return{operations:{platform:i,resolveTarget:async(n,r)=>await $u({input:n,context:r,snapshots:t,options:e}),observe:async(n,r)=>await uu({condition:n.condition,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:i}),resolveGestureViewport:async()=>await a({kind:`gestureViewport`}),launchApp:async(e,t)=>{let n=e.appId??t.appId,r=[...Wu(e.arguments),...Wu(e.launchArguments)],i=e.clearState===!0,a=!i&&e.stopApp!==!1;await s({kind:`launchApp`,...n?{appId:n}:{},relaunch:a,clearState:i,launchArgs:r},t,`deferred`)},stopApp:async(e,t)=>{let n=e.appId??t.appId;await s({kind:`stopApp`,...n?{appId:n}:{}},t)},clearState:async(e,t)=>{let n=e.appId??t.appId;await s({kind:`clearState`,...n?{appId:n}:{}},t)},openLink:async(e,t)=>{await s({kind:`openLink`,...t.appId?{appId:t.appId}:{},link:e.link,prewarmRunner:i===`ios`},t,`deferred`)},tapOn:async(r,i)=>await ed(e,t,n,r.target,i,{click:{count:r.repeat,intervalMs:r.delay},retryIfNoChange:r.retryTapIfNoChange===!0}),doubleTapOn:async(t,n)=>{await o(()=>cd(e,t.target.point,f({doubleTap:!0,intervalMs:t.delay})),n,`deferred`)},longPressOn:async(t,n)=>{await o(()=>cd(e,t.target.point,{holdMs:J.longPressDurationMs}),n,`deferred`)},gesture:async(e,t)=>{let n=await s({kind:`swipe`,gesture:e,...t.gestureViewport?{viewport:t.gestureViewport}:{}},t,`deferred`);return n?{data:n}:void 0},inputText:async(e,t)=>await c(e.text,t),eraseText:async(e,t)=>await c(`\b`.repeat(e.charactersToErase??J.eraseTextMaxCharacters),t),scroll:async(e,t)=>{await s({kind:`scroll`,direction:e.direction},t,`deferred`)},scrollUntilVisible:async(n,r)=>{let a=await du({selector:n.selector,direction:n.direction,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:i,scroll:async(a,o)=>{let c=po(o,n.selector,n.direction,n.durationMs,i);return await s(c?{kind:`swipe`,...c}:{kind:`scroll`,direction:n.direction,durationMs:n.durationMs},r),(await fu({timeoutMs:Math.min(J.settleTimeoutMs,a),context:r,snapshot:t.capture,dependencies:e.dependencies})).snapshot}});if(a.visiblePercentage!==J.scrollUntilVisiblePercentage)throw di(`Maestro scrollUntilVisible target did not become visible.`,{selector:n.selector,timeoutMs:n.timeoutMs});return{observation:t.bindObservation(Gu(n.selector,a))}},pressKey:async(e,t)=>{await s({kind:`pressKey`,key:e.key},t,`deferred`)},back:async(e,t)=>{await s({kind:`pressKey`,key:`back`},t,`deferred`)},hideKeyboard:async(e,t)=>{await s({kind:`pressKey`,key:`dismiss`},t,`deferred`)},waitForAnimationToEnd:async(t,n)=>({visualStabilityReached:await ru({timeoutMs:t.timeoutMs??J.animationWaitTimeoutMs,now:e.dependencies.now,signal:n.signal,capture:async t=>{await a({kind:`screenshot`,path:t,stabilize:!1,...e.platform===`ios`?{captureBackend:`runner`}:{}})}})}),takeScreenshot:async e=>({artifactPaths:Ku(await a({kind:`screenshot`,path:e.path}))}),runScript:async(t,n)=>({outputEnv:zl({scriptPath:qu(t.file,n,e.sourcePath),publicNetworkOnly:e.publicNetworkOnly,env:{...n.env,...t.env?Ju(t.env):{}}})})},snapshots:t,readMetrics:()=>({...t.readMetrics(),...n}),recordSettle:r}}function ud(e){let{operations:t,snapshots:n,readMetrics:r,recordSettle:i}=ld(e);return os(t,{beforeExecute:async({context:e,requiresSettledPredecessor:t})=>{if(t){let t=await n.settlePending(e);t&&i(t)}},afterExecute:({context:e,visualStabilityReached:t})=>{t&&n.consumeStabilityFromVisualWait(e)},bindObservation:n.bindObservation,readMetrics:r})}function dd(e){let{filePath:t,tracePath:n,onStep:r}=e,i=new Map;return{actionStarted:e=>{i.set(e.stepIndex,e),fd(()=>hd(r,e)),fd(()=>gd(n,t,e))},actionCompleted:e=>{let r=pd(i,e.stepIndex);fd(()=>_d(n,t,md(r,e),!0))},actionFailed:e=>{let r=pd(i,e.stepIndex);fd(()=>_d(n,t,md(r,e),!1))}}}function fd(e){try{e()}catch{}}function pd(e,t){let n=e.get(t);return e.delete(t),n}function md(e,t){return f({...e??t,durationMs:t.durationMs,runtimeMetrics:t.runtimeMetrics,data:`data`in t?t.data:void 0,error:`error`in t?t.error:void 0})}function hd(e,t){e?.({index:t.stepIndex,total:t.stepTotal,command:t.action,...t.value?{value:t.value}:{}})}function gd(e,t,n){kc(e,{type:`replay_action_start`,ts:new Date().toISOString(),replayPath:t,...n.source.path&&n.source.path!==t?{sourcePath:n.source.path}:{},line:n.source.line,step:n.stepIndex,command:n.action,positionals:n.value?[n.value]:[]})}function _d(t,n,r,i){let a=vd(r);kc(t,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:n,...r.source.path&&r.source.path!==n?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:r.action,ok:i,durationMs:r.durationMs,...Object.keys(a).length>0?{resultTiming:a}:{},...!i&&`error`in r&&r.error instanceof e?{errorCode:r.error.code}:{}})}function vd(e){let t=`data`in e?e.data:void 0,n=yd(t?.timing)?t.timing:void 0;return f({...e.runtimeMetrics??{},...typeof n?.executionProfile==`string`?{executionProfile:n.executionProfile}:{},...typeof n?.gestureDurationMs==`number`?{gestureDurationMs:n.gestureDurationMs}:{}})}function yd(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function bd(e,t){let n=f({...e.dispatch,...xd(t.dispatch)});return f({...e,command:t.command,positionals:t.positionals,input:t.input,flags:t.flags,dispatch:Object.keys(n).length>0?n:void 0})}function xd(e){return f({closeAppOnly:e?.closeAppOnly,observationOnly:e?.observationOnly,gestureViewport:e?.gestureViewport,gestureExecutionProfile:e?.gestureExecutionProfile})}function Sd(e,t){let n={command:e.action,...e.value?{value:e.value}:{}};return{command:{kind:e.action},source:e.source,progress:n,action:{command:Ed(e.action),positionals:Dd(e.action,e.value),flags:t.flags??{}}}}async function Cd(e){let{failure:t,replayPath:n,req:r,sessionStore:i,observationStore:a,logPath:o}=e,s=N(r.meta?.requestId),c=Sd(t,r),l=bc(e.error),u=[...t.redactions],d=Ct(u),f={...l,message:d(l.message),...l.hint?{hint:d(l.hint)}:{}},p=a.get(),m=p?await ac({session:p,observationStore:a,logPath:o,action:c.action}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},h=p&&m.state===`available`&&!t.isControl?wd({failure:t,action:c.action,session:p,nodes:m.nodes,sanitize:d}):[],g=[t.action,Td(t.value)].filter(Boolean).join(` `),_=Ys({sessionStore:i,observationStore:a,divergence:{version:1,kind:`action-failure`,step:{index:t.stepIndex,source:{path:d(t.source.path??n),line:t.source.line}},action:d(g),cause:{code:f.code,message:f.message,...f.hint?{hint:f.hint}:{}},screen:lc(m,d),suggestions:h.slice(0,5),suggestionCount:h.length,resume:t.resume,repairHint:Us({kind:`action-failure`,targetEvidence:void 0,capture:rc(m)})},responseLevel:r.meta?.responseLevel,evidence:m.state===`available`?m.evidence:void 0,...s?{signal:s}:{}});return Sc({error:f,actionLabel:g,action:t.action,positionals:[...c.action.positionals],step:t.stepIndex,replayPath:n,artifactPaths:[...t.artifactPaths],snapshotDiagnostics:e.snapshotDiagnostics,divergence:_,scrubVars:u,warnings:t.warnings})}function wd(e){let t={createdAt:Date.now(),nodes:e.nodes};return ec(Ja(e.failure,t).map(({node:e,basis:t})=>({node:e,nodeIndex:e.index,basis:t}))).map(({node:t,basis:n})=>yc({node:t,nodes:e.nodes,session:e.session,action:e.action,basis:n,sanitize:e.sanitize}))}function Td(e){return!e||e===`<text>`?e??``:Ie(e)}function Ed(e){return e===`tapOn`||e===`doubleTapOn`?`click`:e===`longPressOn`?`longpress`:e===`assertVisible`||e===`assertNotVisible`||e===`extendedWaitUntil`||e===`scrollUntilVisible`?`wait`:e}function Dd(e,t){return!t||e===`inputText`?[]:[t]}function Od(e){let{command:t,outcome:n,startedAt:r,snapshotStart:i}=e,{session:{name:a,store:o}}=t,s=Ad(o,i),c=n.replayed;return{ok:!0,data:{replayed:c,healed:0,session:a,sessionActive:o.get()!==void 0,artifactPaths:n.artifactPaths,...n.warnings?{warnings:n.warnings}:{},...s?{snapshotDiagnostics:s}:{},message:jd(c,Date.now()-r)}}}async function kd(e){let{command:t,replayPath:r,state:i,outcome:a}=e,{request:o,session:{store:s,observationStore:c,logPath:l}}=t,{failure:u}=a,d=n(a.error);return u?await Cd({error:d,failure:u,replayPath:r,req:o,sessionStore:s,observationStore:c,logPath:l,snapshotDiagnostics:Ad(s,i.snapshotStart)}):{ok:!1,error:d}}function Ad(e,t){let n=e.get()?.snapshotDiagnostics?.samples.slice(t)??[];return g(n)}function jd(e,t){return`Replayed ${e} ${e===1?`step`:`steps`} in ${(t/1e3).toFixed(1)}s`}async function Md(e){let{request:t}=e,n=t.flags?.replayScriptSource;if(!n)return u(`INVALID_ARGS`,ss);if(t.flags?.saveScript!==void 0)return u(`INVALID_ARGS`,`Maestro YAML does not support --save-script; ADR 0012 repair recording applies only to .ad scripts.`);let r=Date.now(),i={snapshotStart:0};try{return await Nd({command:e,bundle:n,startedAt:r,state:i})}catch(t){return await kd({command:e,replayPath:n.entry,state:i,outcome:{ok:!1,error:t}})}}async function Nd(e){let{command:t,bundle:n,startedAt:r,state:i}=e,{request:a,session:{store:o},tracePath:s,onStep:c}=t,l=await Pd({command:t,bundle:n}),u=t.publicNetworkOnly===!0,d=Vd({command:t,device:l.device,platform:l.platform,runtimeHints:l.runtimeHints,sourcePath:l.filePath,publicNetworkOnly:u});i.snapshotStart=o.get()?.snapshotDiagnostics?.samples.length??0;let f=await qa(l.flow,d,{defaults:l.defaults,env:l.env,platform:l.platform,target:l.target,runtimeHints:l.runtimeHints,signal:l.signal,from:a.flags?.replayFrom,planDigest:a.flags?.replayPlanDigest,trustedScripts:!u,readSource:e=>cs(n,e),observer:dd({filePath:l.filePath,tracePath:s,onStep:c})});return f.ok?Od({outcome:f,command:t,startedAt:r,snapshotStart:i.snapshotStart}):await kd({command:t,replayPath:n.entry,state:i,outcome:f})}async function Pd(e){let{command:t,bundle:n}=e,{request:r,session:{name:i,store:a}}=t,o=n.entry,s=Ka(cs(n,o),o),c=a.lookup(),l=c?.session;c&&a.assertSelectorMatches(r.flags);let u=await Fd({req:r,sessionStore:a,sessionName:i,session:l,flow:s});return{filePath:o,flow:s,...u,defaults:zd({req:r,sessionName:i,filePath:o,platform:u.platform,target:u.target}),env:Bd(r),signal:N(r.meta?.requestId)}}async function Fd(e){let{req:t,sessionStore:n,sessionName:r,session:i,flow:a}=e,o=t.flags?.platform,s=i?.device??(o===`android`||o===`ios`?void 0:await Cn(t.flags??{},Ol(a.appTarget,o))),c=Kd(t,s),l=Ld({req:t,sessionStore:n,sessionName:r,device:s,platform:c});return await Id({req:t,sessionStore:n,sessionName:r,device:s,platform:c,target:qd(t,s),runtimeHints:l,flow:a})}async function Id(e){if(e.device||!Rd(e.runtimeHints))return e;let t=await Cn(e.req.flags??{},Ol(e.flow.appTarget,e.platform));return{device:t,platform:e.platform,target:qd(e.req,t),runtimeHints:Ld({req:e.req,sessionStore:e.sessionStore,sessionName:e.sessionName,device:t,platform:e.platform})}}function Ld(e){return e.sessionStore.resolveOpenRuntimeHints({request:e.req,device:e.device,platform:e.platform})}function Rd(e){return e?.metroPort!==void 0&&e.metroHost===void 0&&e.bundleUrl===void 0}function zd(e){return{...Ml({req:e.req,sessionName:e.sessionName,metadata:{},resolvedPath:e.filePath}),AD_PLATFORM:e.platform,AD_TARGET:e.target}}function Bd(e){return{...Qe(Xe(e.flags?.replayShellEnv)),...et(Je(e.flags?.replayEnv))}}function Vd(e){let{command:t,device:n,platform:r,runtimeHints:i,sourcePath:a,publicNetworkOnly:o}=e,{request:s,invoke:c}=t,l={...s,runtime:i,...t.dispatch?{dispatch:t.dispatch}:{}};return ud({invoke:e=>c(bd(l,e)),flags:Hd(n,r,s.flags),publicNetworkOnly:o,platform:r,sourcePath:a,dependencies:{now:Date.now,sleep:async(e,t)=>{await Gn(e,void 0,{signal:t})}}})}function Hd(e,t,n){if(!e)return Ud(t,n);let r={platform:t,target:e.target,noRecord:!0};return t===`android`?{...r,serial:e.id}:{...r,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}}}function Ud(e,t){let n={platform:e,target:t?.target??`mobile`,noRecord:!0};return t?.device&&(n.device=t.device),e===`android`?Wd(n,t):Gd(n,t)}function Wd(e,t){return t?.serial&&(e.serial=t.serial),t?.androidDeviceAllowlist&&(e.androidDeviceAllowlist=t.androidDeviceAllowlist),e}function Gd(e,t){return t?.udid&&(e.udid=t.udid),t?.iosSimulatorDeviceSet&&(e.iosSimulatorDeviceSet=t.iosSimulatorDeviceSet),e}function Kd(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;if(n?.platform===`android`)return`android`;if(n?.platform===`apple`&&n.appleOs===`ios`)return`ios`;throw new e(`INVALID_ARGS`,`Maestro replay requires --platform android|ios or an active mobile session.`)}function qd(e,t){return typeof e.flags?.target==`string`?e.flags.target:t?.target??`mobile`}async function Jd(e){let{resolved:t,keepSession:n,coordinator:r,command:i}=e,{request:a}=i;if($e(t,a.flags?.replayBackend)===`maestro`)return n?u(`INVALID_ARGS`,`--keep-session is supported only for native .ad replay; Maestro YAML owns its lifecycle.`):r.view()?.repairBoundary===void 0?await Md(i):u(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function Yd(e){let{req:t,sessionName:n,sessionStore:r,tracePath:i,resolved:a,script:o,coordinator:s,dispatch:c}=e,l=Xd(t);if(l)return{ok:!1,response:l};let{manifest:u,replayReq:d}=Zd(t,o,c),{metadata:f,actions:p,actionLines:m,actionSourcePaths:h,planDigest:g}=u,_=r.get(),v=Qd({req:t,coordinator:s,manifest:u,preEntrySession:_});return v.ok?{ok:!0,value:{replayReq:d,actions:p,actionLines:m,actionSourcePaths:h,planDigest:g,preEntrySession:_,entryIndex:v.value,varSources:ef({req:t,replayReq:d,sessionName:n,resolved:a,metadata:f}),actionTracePath:i??_?.trace?.outPath}}:{ok:!1,response:v.response}}function Xd(e){if(e.flags?.replayBackend&&e.flags.replayBackend!==`maestro`)return u(`INVALID_ARGS`,`Unsupported replay backend "${e.flags.replayBackend}".`)}function Zd(e,t,n){let r=_s(t,{platform:e.flags?.platform,target:e.flags?.target});return{manifest:r,replayReq:$d({...e,flags:kl(e.flags,r.actions),...n?{dispatch:n}:{}},r.metadata)}}function Qd(e){let{req:t,coordinator:n,manifest:r,preEntrySession:i}=e,a=r.resolveEntryIndex({from:t.flags?.replayFrom,digest:t.flags?.replayPlanDigest,pendingRecordAndHeal:n.view()?.pendingRecordAndHeal,sessionActionsLength:i?.actions.length??0});return a.ok?{ok:!0,value:a.value}:{ok:!1,response:u(`INVALID_ARGS`,a.message)}}function $d(e,t){return!t.platform&&!t.target?e:{...e,flags:tf(e.flags,t)}}function ef(e){let{req:t,replayReq:n,sessionName:r,resolved:i,metadata:a}=e;return{builtins:Ml({req:n,sessionName:r,metadata:a,resolvedPath:i}),fileEnv:a.env,shellEnv:Qe(Xe(t.flags?.replayShellEnv)),cliEnv:et(Je(t.flags?.replayEnv))}}function tf(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}const nf={kind:`none`,status:void 0,targetPath:void 0,targetForce:!1};function rf(e){let{req:t,entryIndex:n,sessionStore:r,sourcePath:i,coordinator:a}=e,o=af({entryIndex:n,sessionStore:r,coordinator:a});return o?{ok:!1,response:o}:(cf({req:t,coordinator:a}),sf({req:t,sessionStore:r,sourcePath:i,coordinator:a}))}function af(e){let t=lf(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get())return d()}function of(e){let{saveScript:t,force:n,preRunState:r,sourcePath:i}=e;return t&&r.kind===`authoring`?u(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${r.status}. Close this session and use a fresh one for repair authoring.`):uf({saveScript:t,liveForce:n,persistedForce:r.targetForce||void 0,sourcePath:i,existingSaveScriptPath:r.targetPath})}function sf(e){let{req:t,sourcePath:n,coordinator:r}=e,{saveScript:i,force:a}=t.flags??{},o=of({saveScript:i,force:a,preRunState:r.view()?.scriptPublication??nf,sourcePath:n});return o?{ok:!1,response:o}:(r.demoteForRerunIfArmed(),{ok:!0,armSaveScript:df({saveScript:i,force:a,coordinator:r,sourcePath:n})})}function cf(e){let{req:t,coordinator:n}=e;n.clearCorrectiveWatermarkIfExpected(t.flags?.replayFrom),t.flags?.saveScript&&n.clearTombstone()}function lf(e){let{entryIndex:t,coordinator:n}=e;if(!(t>0)&&n.view()?.repairBoundary!==void 0)return u(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function uf(e){let{saveScript:t,liveForce:n,persistedForce:r,sourcePath:i,existingSaveScriptPath:a}=e;if(!t)return;let o=typeof t==`string`?Dt(t):a??zs(i);if(!(n||r&&o===a)&&R.existsSync(o))return u(`COMMAND_FAILED`,`A file already exists at ${o}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function df(e){let{saveScript:t,force:n,coordinator:r,sourcePath:i}=e;if(!t)return()=>{};let a=!0;return()=>{r.armStep({saveScript:t,force:n,sourcePath:i,firstArm:a}),a=!1}}async function ff(e){let{request:t,session:{name:n,logPath:i,store:a,observationStore:o,coordinator:s},tracePath:c,onStep:l,invoke:d}=e,f=t.flags?.replayScriptSource;if(!f)return u(`INVALID_ARGS`,ss);let p=Date.now(),m=t.flags?.replayKeepSession===!0,h=``,g=new Set;try{if(h=f.entry,tt(h)&&t.flags?.replayBackend!==`maestro`)return u(`INVALID_ARGS`,Ze(`replay`,h));let r=await Jd({resolved:h,keepSession:m,coordinator:s,command:e});if(r)return r;let _=Yd({req:t,sessionName:n,sessionStore:a,tracePath:c,resolved:h,script:cs(f,h),coordinator:s,dispatch:e.dispatch});if(!_.ok)return _.response;let{replayReq:v,actions:y,actionLines:b,actionSourcePaths:x,planDigest:S,entryIndex:C,varSources:w,actionTracePath:ee}=_.value,te=rf({req:t,entryIndex:C,sessionStore:a,sourcePath:h,coordinator:s});if(!te.ok)return te.response;let{runtime:T,readLastResponse:ne}=bl({ctx:{replayReq:v,sessionName:n,sessionStore:a,observationStore:o,logPath:i,resolved:h,actions:y,actionLines:b,actionSourcePaths:x,planDigest:S,actionTracePath:ee,responseLevel:t.meta?.responseLevel,invoke:d,signal:N(t.meta?.requestId),coordinator:s,resolvedSessionScope:e.resolvedSessionScope,dependencies:e.dependencies},req:t,artifactPaths:g,onStep:l,armSaveScript:te.armSaveScript}),E=await ks({actions:y,entryIndex:C,keepSession:m,actionLines:b,actionSourcePaths:x,resolvedPath:h,varSources:w},T);return E.status===`failed`?ne()??u(`COMMAND_FAILED`,`replay step failed with no recorded response`):pf({startedAt:p,sessionName:n,sessionStore:a,replayed:E.replayed,artifactPaths:E.artifactPaths,snapshotDiagnosticSamples:E.snapshotDiagnosticSamples,armSaveScript:te.armSaveScript,coordinator:s,keepSession:m})}catch(e){let t=r(e);return u(t.code,t.message,g.size>0?{artifactPaths:[...g]}:void 0)}}function pf(e){let{startedAt:t,sessionName:n,sessionStore:r,replayed:i,artifactPaths:a,snapshotDiagnosticSamples:o,armSaveScript:s,coordinator:c,keepSession:l}=e;s(),c.markCompleteIfArmed();let u=r.get(),d=hf({keepSession:l,sessionName:n,completedSession:u,artifactPaths:a});if(d)return d;let f=g([...o]);return{ok:!0,data:{replayed:i,healed:0,session:n,sessionActive:u!==void 0,artifactPaths:[...a],...f?{snapshotDiagnostics:f}:{},message:mf(i,Date.now()-t)}}}function mf(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function hf(e){let{keepSession:t,sessionName:n,completedSession:r,artifactPaths:i}=e;if(!(!t||r))return u(`COMMAND_FAILED`,`Replay completed but --keep-session could not preserve session "${n}". Run the script again after checking which action closed the session.`,i.length>0?{artifactPaths:[...i]}:void 0)}function gf(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=L.resolve(n??`.`,t??`.agent-device/test-artifacts`);return L.join(i,r)}function _f(e,t){let n=t?L.relative(t,e):L.basename(e),r=n.length===0||n.startsWith(`..`)?L.basename(e):n;return De(r.toLowerCase().replaceAll(/[\\/]+/g,`__`).replaceAll(/[^a-z0-9._-]+/g,`-`))||`test`}function vf(e,t){R.mkdirSync(t,{recursive:!0}),xf(e,t)}function yf(e){let{outcome:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=t.status===`passed`,c=new Set(t.artifactPaths);t.status===`failed`&&typeof t.error.logPath==`string`&&c.add(t.error.logPath);let l=L.join(o,`result.txt`),u=L.join(o,`failure.txt`),d=bf([...c],o,[l,u]),f=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${s?`passed`:`failed`}`];t.status===`passed`?f.push(`replayed: ${t.replayed}`,`healed: ${t.healed}`):(f.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&f.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&f.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&f.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&f.push(`timeoutMode: cooperative`)),d.length>0&&f.push(`copiedArtifacts: ${d.map(e=>L.basename(e)).join(`, `)}`);let p=`${f.join(`
2
+ `)}\n`;R.writeFileSync(l,p),s||R.writeFileSync(u,p)}function bf(e,t,n){let r=[],i=new Set(n.map(e=>L.basename(e).toLowerCase()));for(let n of e){if(!Cf(n))continue;let e=L.basename(n);if(L.resolve(n)===L.resolve(t,e)&&!i.has(e.toLowerCase())){r.push(n);continue}let a=Sf(e,t,i),o=L.join(t,a);R.copyFileSync(n,o),r.push(o)}return r}function xf(e,t){let n=L.join(t,`replay.ad`);if(R.copyFileSync(e,n),L.extname(e).toLowerCase()===`.ad`)return;let r=L.join(t,L.basename(e));L.resolve(r)!==L.resolve(n)&&R.copyFileSync(e,r)}function Sf(e,t,n){let r=L.extname(e),i=r?e.slice(0,-r.length):e,a=e,o=2;for(;n.has(a.toLowerCase())||R.existsSync(L.join(t,a));)a=`${i}-${o++}${r}`;return a}function Cf(e){try{return R.statSync(e).isFile()}catch{return!1}}function wf(t){let{platformFilter:n,discoverSources:r}=t,i=r(),a=[];for(let e of i){let{path:t,manifest:r}=e,i={kind:`run`,path:t,title:r.title,manifest:r};if(!n){a.push(i);continue}let o=r.device.platform;if(o.kind===`caller-bound`){a.push(i);continue}if(o.kind===`unspecified`){a.push({kind:`skip`,path:t,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${n}`});continue}Af(n,o.value)&&a.push(i)}if(a.filter(e=>e.kind===`run`).length===0){let t=n?` for --platform ${n}`:``;throw new e(`INVALID_ARGS`,`No replay tests matched${t}.`)}return a}function Tf(e,t,n,r,i=0){let a=L.basename(n,L.extname(n)),o=De(a.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`));return`${e}:test:${t}:${r+1}${o?`-${o}`:``}:attempt-${i+1}`}function Ef(e){let t=e?.trim()||`${process.pid}-${Date.now().toString(36)}`;return De(t.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`))||`suite`}function Df(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e;return[t??n,...o===void 0?[]:[`shard`,o+1],`test`,i+1,L.basename(r),`attempt`,a+1].join(`:`)}function Of(e,t){return typeof e==`number`?e:t}function kf(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function Af(e,t){return e===`apple`?S(t):t===e}function jf(e){return{status:`failed`,error:e.error,artifactPaths:e.artifactPaths??[],warnings:e.warnings??[],infrastructure:e.infrastructure??!1,...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}const Mf=2e3;async function Nf(e){let{filePath:t,sessionName:r,requestId:i,parentRequestId:a,timeoutMs:o,platform:s,target:c,artifactsDir:l,shard:u,onStep:d,runReplay:f,cleanupSession:p,finalizeAttempt:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=g({attemptId:i,parentAttemptId:a}),v=new Set,y,b=!1,x,S=Date.now(),C=Bf({artifactsDir:l,artifactPaths:v,filePath:t,sessionName:r,requestId:i,timeoutMs:o,platform:s,target:c}),w=f({filePath:t,sessionName:r,platform:s,target:c,requestId:i,artifactsDir:l,artifactPaths:v,tracePath:C,appendTimingEvent:e=>Q(C,e),shard:u,onStep:d}).catch(e=>jf({error:n(e)})).finally(()=>{_.release()});try{x=typeof o==`number`?await Promise.race([w,new Promise(e=>{y=setTimeout(()=>{b=!0,_.cancel(),e(Vf(o,[...v]))},o)})]):await w,Q(C,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:r,ok:x.status===`passed`,timedOut:b,durationMs:Date.now()-S,errorCode:x.status===`passed`?void 0:x.error.code})}finally{y&&clearTimeout(y),b&&(await Ff(w)||(x=Rf(x),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:r,requestId:i,graceMs:Mf}}),If({replayPromise:w,cleanupSession:p,sessionName:r,requestId:i,emitDiagnostic:h})));let e=await Lf({finalizeAttempt:m,sessionName:r,artifactPaths:v,artifactsDir:l,tracePath:C,emitDiagnostic:h});x?.status===`passed`&&e&&(x=zf(x,`Replay test finalization failed: ${e.error.message}`));let t=Date.now();try{Q(C,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:r}),await p(r),Q(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!0,durationMs:Date.now()-t})}catch(e){let i=n(e);Q(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-t,errorCode:i.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:r,error:i.message}}),x=Pf(x,i,v)}}return x??jf({error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}})}function Pf(e,t,n){return e?.status===`failed`?{...e,infrastructure:!0}:jf({error:t,artifactPaths:[...n],infrastructure:!0})}async function Ff(e){return await Promise.race([e.then(()=>!0),Gn(Mf).then(()=>!1)])}async function If(e){let{replayPromise:t,cleanupSession:r,sessionName:i,requestId:a,emitDiagnostic:o}=e;try{await t}finally{try{await r(i)}catch(e){o({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:i,requestId:a,error:n(e).message}})}}}async function Lf(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o,emitDiagnostic:s}=e;if(!t)return;let c=Date.now();Q(o,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o,appendTimingEvent:e=>Q(o,e)});return Q(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:e===void 0,durationMs:Date.now()-c,errorCode:e?.error.code}),e}catch(e){let t=n(e);return Q(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-c,errorCode:t.code}),s({level:`warn`,phase:`test_finalize_failed`,data:{session:r,error:t.message}}),jf({error:t})}}function Rf(e){return!e||e.status===`passed`?e:{...e,infrastructure:!0,error:{...e.error,details:{...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0}}}}function zf(e,t){return{...e,warnings:[...e.warnings,t]}}function Bf(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=L.join(t,`replay-timing.ndjson`);return R.mkdirSync(L.dirname(l),{recursive:!0}),R.writeFileSync(l,``),n.add(l),Q(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function Q(e,t){e&&R.appendFileSync(e,`${JSON.stringify(t)}\n`)}function Vf(e,t=[]){return jf({artifactPaths:t,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}})}async function Hf(e){let t=Uf(e),n=await Wf(e,t);return{result:Xf(e,t,n),infrastructure:n.finalOutcome?.status===`failed`&&n.finalOutcome.infrastructure}}function Uf(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:L.join(i,...a?[`shard-${a.shardIndex+1}`]:[],_f(t.path,n)),maxAttempts:r+1}}async function Wf(e,t){Kf(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!e.isCanceled();r+=1){let i=await Gf(e,t,r);if(qf(n,i),Jf(e,i.outcome,r))break;Yf(e,t,i)}return n}async function Gf(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=Tf(i,a,r.path,o,n),h=L.join(t.testArtifactsDir,`attempt-${f}`);vf(r.path,h);let g=Df({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_={file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...$(d)},v=await Nf({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.manifest.device.platform.kind===`declared`?r.manifest.device.platform.value:void 0,target:r.manifest.device.target,artifactsDir:h,shard:d,onStep:t=>{e.emitProgress({type:`replay-test`,..._,status:`progress`,stepIndex:t.index,stepTotal:t.total,...t.command===void 0?{}:{stepCommand:t.command},...t.value===void 0?{}:{stepValue:t.value}})},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt,emitDiagnostic:e.emitDiagnostic,bindAttemptCancellation:e.bindAttemptCancellation}),y=Date.now()-p;return yf({outcome:v,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{outcome:v,sessionName:m,attempt:f,durationMs:y}}function Kf(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;e.emitProgress({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:Tf(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...$(c)})}function qf(e,t){e.finalOutcome=t.outcome,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,t.outcome.status!==`passed`&&e.attemptFailures.push({attempt:t.attempt,message:t.outcome.error.message,durationMs:t.durationMs})}function Jf(e,t,n){return t.status===`passed`||e.isCanceled()||t.infrastructure||n>=e.retries}function Yf(e,t,n){n.outcome.status!==`passed`&&e.emitProgress({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.outcome.error.message,hint:n.outcome.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...$(e.shard)})}function Xf(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalOutcome?.status===`passed`?Zf(e,t,n,r):Qf(e,t,n,r)}function Zf(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome;if(c?.status!==`passed`)throw Error(`Expected passing replay test outcome.`);return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...$(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,replayed:c.replayed,healed:c.healed,...c.warnings.length>0?{warnings:[...c.warnings]}:{},...c.snapshotDiagnostics?{snapshotDiagnostics:c.snapshotDiagnostics}:{},...ep(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function Qf(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome,l=c?.status===`failed`?c.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`};return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:l.message,hint:l.hint,...$(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:l,...$f(c),...ep(s)}}function $f(e){let t=e?.status===`failed`?e:void 0;return{...t&&t.warnings.length>0?{warnings:[...t.warnings]}:{},...t?.infrastructure?{infrastructure:!0}:{},...e?.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}function ep(e){return $(e)}function $(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function tp(e,t,n,r){if(!e||t.length===0)return;let i=await r(e.count);return{mode:e.kind,shardCount:e.count,total:n+(e.kind===`all`?t.length*e.count:t.length),shards:i.map((n,r)=>({shardIndex:r,shardCount:e.count,device:n,entries:e.kind===`all`?t:t.filter((t,n)=>n%e.count===r)}))}}async function np(e){let{request:t,runReplay:n,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l,discoverSources:u,resolveShardTargets:d}=e,f=t.sessionName;if(t.inputs.length===0)return{status:`failed`,error:{code:`INVALID_ARGS`,message:`test requires at least one path or glob`}};try{let e=Date.now(),r=await rp(t,u,d);sp(r,o);let p=r.shardPlan?cp({entries:r.entries,total:r.total,emitProgress:o}):[];return r.shardPlan?p.push(...await lp({shards:r.shardPlan.shards,sessionName:f,suiteInvocationId:r.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:r.suiteArtifactsDir,suiteTotal:r.total,runReplay:n,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l})):p.push(...await pp({discoveryEntries:r.entries,sessionName:f,suiteInvocationId:r.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:r.suiteArtifactsDir,suiteTotal:r.total,runReplay:n,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l})),{status:`completed`,data:gp(r.total,p,Date.now()-e,r.suiteArtifactsDir)}}catch(e){let t=r(e);return{status:`failed`,error:{code:t.code,message:t.message}}}}async function rp(e,t,n){let r=ip(e,t),i=ap(r),a=r.length-i.length,o=Ef(e.requestId),s=await tp(e.shard?{kind:e.shard.mode,count:e.shard.count}:void 0,i,a,n);return{entries:r,runnable:i,shardPlan:s,suiteInvocationId:o,suiteArtifactsDir:op(e,o),total:s?.total??r.length}}function ip(e,t){return wf({platformFilter:e.platformFilter,discoverSources:t})}function ap(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function op(e,t){return gf({artifactsDir:typeof e.artifactsDir==`string`?e.artifactsDir:void 0,cwd:e.cwd,suiteInvocationId:t})}function sp(e,t){t({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function cp(e){let{entries:t,total:n}=e,r=[];for(let[i,a]of t.entries())a.kind===`skip`&&(e.emitProgress({type:`replay-test`,file:a.path,status:`skip`,index:i+1,total:n,message:a.message}),r.push({file:a.path,status:`skipped`,durationMs:0,reason:a.reason,message:a.message}));return r}async function lp(e){return(await Promise.allSettled(e.shards.map(async t=>await dp({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[up(r,e.sessionName,t.reason)]:[]})}function up(e,t,r){let i=n(r);return{file:e.entries[0]?.entry.path??`shard-${e.shardIndex+1}`,session:fp(t,e),status:`failed`,durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}}async function dp(e){let{shard:t,sessionName:n}=e;return await mp({...e,entries:t.entries,sessionName:fp(n,t),shard:t})}function fp(e,t){return`${e}:shard-${t.shardIndex+1}`}async function pp(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h}=e,g=[],_=0;for(let[e,v]of t.entries()){if(p())break;if(v.kind===`skip`){f({type:`replay-test`,file:v.path,status:`skip`,index:e+1,total:c,message:v.message}),g.push({file:v.path,status:`skipped`,durationMs:0,reason:v.reason,message:v.message});continue}_+=1;let t=await Hf({entry:v,sessionName:n,suiteInvocationId:r,caseIndex:_-1,cwd:i,requestId:a,retries:kf(o.retries,v.manifest.attemptDefaults?.retries),timeoutMs:Of(o.timeoutMs,v.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h});if(g.push(t.result),hp(t,o,p))break}return g}async function mp(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=[];for(let[e,v]of t.entries()){if(m())break;let{entry:t,suiteIndex:y}=v,b=await Hf({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:kf(o.retries,t.manifest.attemptDefaults?.retries),timeoutMs:Of(o.timeoutMs,t.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:y,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g});if(_.push(b.result),hp(b,o,m))break}return _}function hp(e,t,n){return n()||t.failFast===!0&&e.result.status===`failed`||e.infrastructure}function gp(e,t,n,r){let i=t.filter(e=>e.status===`passed`).length,a=t.filter(e=>e.status===`failed`),o=a.length,s=t.filter(e=>e.status===`skipped`).length,c=i+o,l=v(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:c,passed:i,failed:o,skipped:s,notRun:Math.max(0,e-c-s),durationMs:n,failures:a,tests:t,artifactsDir:r,...l?{snapshotDiagnostics:l}:{}}}function _p(e,t){return()=>e.map(e=>vp(e,t))}function vp(e,t){let n=e.entry,r=cs(e,n),i=$e(n,t)===`maestro`,a=Le(r);return{path:n,manifest:{...i?{title:Ka(r,n).name}:{},device:{platform:a.platform?{kind:`declared`,value:a.platform}:i?{kind:`caller-bound`}:{kind:`unspecified`},...a.target===void 0?{}:{target:a.target}},...a.timeoutMs!==void 0||a.retries!==void 0?{attemptDefaults:{...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.retries===void 0?{}:{retries:a.retries}}}:{}}}}function yp(e){return async t=>(await Sp(e,t)).map(bp)}function bp(t){if(t.platform===`web`||!x(t))throw new e(`INVALID_ARGS`,`test sharding requires a mobile device; ${t.id} is ${t.platform}`);return{id:t.id,name:t.name,platform:t.platform,...t.target===void 0?{}:{target:t.target}}}function xp(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}async function Sp(t,n){let r=Ep(t),i=wp(await Sn(Cp(t)),r,t);if(i.length<n)throw new e(`DEVICE_NOT_FOUND`,`test sharding requires ${Tp(n)}, but only ${i.length} matched`);return i.slice(0,n)}function Cp(e){let t=bn(e?.androidDeviceAllowlist);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:te({simulatorSetPath:xn(e?.iosSimulatorDeviceSet),platform:e?.platform,target:e?.target}),androidSerialAllowlist:t?Array.from(t).sort():void 0}}function wp(e,t,n){return t.length>0?Dp(e,t,n):e.filter(e=>Op(e,n)).sort(jp)}function Tp(e){return`${e} device${e===1?``:`s`}`}function Ep(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Dp(t,n,r){return n.map(n=>{let i=Ap(n),a=t.find(e=>kp(e,r)&&(e.id===n||Ap(e.name)===i));if(!a)throw new e(`DEVICE_NOT_FOUND`,`No shard device matched ${n}`);return a})}function Op(e,t){return!kp(e,t)||!x(e)?!1:e.booted!==!1}function kp(e,t){return!(!ee(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Ap(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function jp(e,t){return e.id.localeCompare(t.id)}function Mp(t){let n=Np(t?.shardAll,`--shard-all`),r=Np(t?.shardSplit,`--shard-split`);if(n!==void 0&&r!==void 0)throw new e(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(n!==void 0)return{mode:`all`,count:n};if(r!==void 0)return{mode:`split`,count:r}}function Np(t,n){if(t!==void 0){if(typeof t!=`number`||!Number.isInteger(t)||t<1)throw new e(`INVALID_ARGS`,`${n} requires a positive integer`);return t}}const Pp=new Set([`IOS_BOOT_TIMEOUT`,`IOS_RUNNER_CONNECT_TIMEOUT`,`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,`IOS_TOOL_MISSING`,`ANDROID_BOOT_TIMEOUT`,`ADB_TRANSPORT_UNAVAILABLE`,`CI_RESOURCE_STARVATION_SUSPECTED`]);function Fp(e){return Pp.has(e.toUpperCase())}const Ip=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function Lp(e){if(!(`ok`in e)&&e.status===`failed`&&e.infrastructure===!0)return!0;let t=Rp(e);return t?zp(t.details)||Bp(t.code,t.message):!1}function Rp(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function zp(e){if(e?.recovery===`runner_recycle_budget_exhausted`)return!0;let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`||gt(t)?!0:t?Fp(t):!1}function Bp(e,t){let n=`${e}\n${t}`.toLowerCase();return Ip.some(e=>n.includes(e))}function Vp(e){if(!e.ok)return{status:`failed`,error:e.error,artifactPaths:Wp(e.error.details?.artifactPaths),warnings:ft(e.error.details),infrastructure:Lp(e),...Gp(e.error.details?.snapshotDiagnostics)};let t=e.data;return{status:`passed`,replayed:typeof t?.replayed==`number`?t.replayed:0,healed:typeof t?.healed==`number`?t.healed:0,warnings:ft(t),artifactPaths:Wp(t?.artifactPaths),...Gp(t?.snapshotDiagnostics)}}function Hp(e){if(!e||e.ok)return;let t=Vp(e);return t.status===`failed`?t:void 0}function Up(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Wp(e){return[...new Set(Up(e))]}function Gp(e){let t=_(e);return t?{snapshotDiagnostics:t}:{}}const Kp=1e3,qp=3e3;function Jp(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Yp(e)}}async function Yp(e){let{req:t,sessionName:n,sessionStore:r,artifactsDir:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0)return;let o=r.get();if(!o||o.screenRecording)return;let s=xt(o.device.platform),c=i?L.join(i,`recording${s}`):bt(o.device.platform);Zp(a,{type:`video_recording_start`,session:n,videoPath:c}),k({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:c}}),e.video.throwIfCanceled();let l=await e.video.record(Qp({req:t,sessionName:n,phase:`start`,outputPath:c}));if(!l.ok)return Zp(a,{type:`video_recording_start_failed`,session:n,videoPath:c,errorCode:l.error.code}),l;let u=Date.now();return await yt(Kp),Zp(a,{type:`video_preroll_done`,session:n,durationMs:Date.now()-u,requestedDurationMs:Kp}),k({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-u,data:{session:n,requestedDurationMs:Kp}}),l}async function Xp(e){let{req:t,sessionName:n,sessionStore:r,artifactPaths:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0||!r.get()?.screenRecording)return;Zp(a,{type:`video_tail_start`,session:n,requestedDurationMs:qp});let o=Date.now();await yt(qp);let s=Date.now(),c=await e.video.record(Qp({req:t,sessionName:n,phase:`stop`}));return Ic(c).forEach(e=>i.add(e)),Zp(a,{type:`video_recording_stop`,session:n,ok:c.ok,durationMs:Date.now()-s,tailDurationMs:s-o,errorCode:c.ok?void 0:c.error.code}),k({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-s,data:{session:n,ok:c.ok,tailDurationMs:s-o}}),c}function Zp(e,t){e({...t,ts:new Date().toISOString()})}function Qp(e){let t={token:e.req.token,meta:e.req.meta};return e.phase===`start`?{request:t,sessionName:e.sessionName,phase:`start`,outputPath:e.outputPath}:{request:t,sessionName:e.sessionName,phase:`stop`}}const $p=[{keys:[`replayKeepSession`],requested:e=>e.replayKeepSession===!0,message:`test does not support --keep-session; suite attempts own their cleanup. Run one native .ad script directly with replay --keep-session.`},{keys:[`replayFrom`,`replayPlanDigest`],requested:e=>e.replayFrom!==void 0||e.replayPlanDigest!==void 0,message:`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`},{keys:[`saveScript`,`force`],requested:e=>!!e.saveScript||e.force===!0,message:`test does not support --save-script/--force; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`}],em=({attemptId:e,parentAttemptId:t})=>{Yt(e);let n=tm(e,t);return{cancel:()=>Gt(e),release:()=>{n(),Jt(e)}}};function tm(e,t){if(!t||t===e)return()=>{};let n=N(t);if(!n)return()=>{};let r=()=>{Gt(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}function nm(e){let{platform:t,target:n,artifactsDir:r,shard:i,sourceBundle:a}=e,o=rm(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0&&a===void 0?o:xp({...o??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r},...a===void 0?{}:{replayScriptSource:a}},i)}function rm(e){if(!e||e.recordVideo!==!0&&e.replayScriptSources===void 0)return e;let t={...e};return delete t.recordVideo,delete t.replayScriptSources,Object.keys(t).length>0?t:void 0}async function im(e){let{request:t,session:{name:n,logPath:i},createSession:a,invoke:o,cleanupSession:s,video:c}=e;if(t.flags?.recordVideo===!0&&c===void 0)return u(`COMMAND_FAILED`,`Screen-recording runtime is not configured for replay video capture`);let l=t.flags??{};for(let e of $p)if(e.requested(l))return u(`INVALID_ARGS`,e.message);let d,f;try{d=sm(t,n),f=om(t)}catch(e){let t=r(e);return u(t.code,t.message)}let p=new Map(f.map(e=>[e.entry,e])),m=await np({request:d,emitProgress:Xt,isCanceled:()=>qt(t.meta?.requestId),emitDiagnostic:k,bindAttemptCancellation:em,runReplay:async({filePath:n,sessionName:r,platform:s,target:l,requestId:u,artifactsDir:d,artifactPaths:f,tracePath:m,appendTimingEvent:h,shard:g,onStep:_})=>{let v=e=>(f&&Ic(e).forEach(e=>f.add(e)),e),y=nm({parentFlags:t.flags,platform:s,target:l,artifactsDir:d,shard:g,sourceBundle:p.get(n)}),b=a(r,i),x=c?{req:t,sessionName:r,sessionStore:b.store,artifactsDir:d,appendTimingEvent:h,video:c}:void 0,S=x?Jp(x):void 0;return Vp(await ff({...cm(e,{request:{...t,command:`replay`,session:r,positionals:[n],flags:y,meta:{...t.meta??{},...u?{requestId:u}:{}}},openLifecycle:S}),session:b,tracePath:m,onStep:_,publicNetworkOnly:e.publicNetworkOnly,invoke:async e=>{let t=x?await Yp(x):void 0;return t&&!t.ok?t:v(await o(e))}}))},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:r,appendTimingEvent:o})=>{if(c)return Hp(await Xp({req:t,sessionName:e,sessionStore:a(e,i).store,artifactsDir:r,appendTimingEvent:o,artifactPaths:n,video:c}))},discoverSources:_p(f,t.flags?.replayBackend),resolveShardTargets:yp(t.flags),cleanupSession:s});return m.status===`completed`?{ok:!0,data:am(m.data,t)}:u(m.error.code,m.error.message)}function am(e,t){let n=t.meta?.clientArtifactPaths?.artifactsDir,r=e.artifactsDir;if(!n||!r)return e;let i=L.join(n,L.basename(r)),a=e=>e===r||e.startsWith(r+L.sep)?i+e.slice(r.length):e,o={...e,artifactsDir:i,tests:e.tests.map(e=>`artifactsDir`in e&&e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e),failures:e.failures.map(e=>e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e)};return R.existsSync(r)?{...o,artifacts:[{field:`artifactsDir`,artifactType:`test-artifacts`,path:r,localPath:n,fileName:L.basename(r)}]}:o}function om(t){let n=t.flags?.replayScriptSources;if(!n)throw new e(`INVALID_ARGS`,ss);return n}function sm(e,t){let n=e.flags??{},r=e.meta?.cwd,i=um(n.artifactsDir);return{inputs:e.positionals??[],sessionName:t,cwd:r,requestId:e.meta?.requestId,platformFilter:n.platform,artifactsDir:i===void 0?void 0:Dt(i,r),failFast:n.failFast===!0,retries:lm(n.retries),timeoutMs:lm(n.timeoutMs),shard:Mp(n)}}function cm(e,t){let{publicNetworkOnly:n,resolvedSessionScope:r,dispatch:i,dependencies:a}=e,o=i||t.openLifecycle?{...i,...t.openLifecycle?{openLifecycle:t.openLifecycle}:{}}:void 0;return{request:t.request,...n?{publicNetworkOnly:n}:{},...r?{resolvedSessionScope:r}:{},...o?{dispatch:o}:{},dependencies:a}}function lm(e){return typeof e==`number`?e:void 0}function um(e){return typeof e==`string`?e:void 0}function dm(t){let n=t.flags??{};if(n.waitMs===void 0)return;let[r]=Ae(`waitMs`);if(!r)throw new e(`INTERNAL_ERROR`,`The waitMs option has no flag declaration whose bounds the daemon can enforce.`);return p(n,`waitMs`,{min:r.min,max:r.max})}function fm(e){let t=e.internal?.openDeviceWait?.waitedMs;return t===void 0?{}:{waitedMs:t}}function pm(e){return{...fm(e),offersDeviceWait:e.command===`open`&&typeof e.flags?.waitMs!=`number`}}function mm(e){let{req:t,budgetMs:n,sessionName:r,sessionStore:i,deviceId:a}=e;if(t.command===`open`&&n!==void 0&&!(a===void 0||i.get(r)))return gm({req:t,sessionName:r,sessionStore:i,deviceId:a,budgetMs:n})}function hm(e,t,n){let r=e.findByDevice(t);if(!(!r||r.address===n))return r}function gm(e){let{req:t,sessionName:n,sessionStore:r,deviceId:i,budgetMs:a}=e,o=Et.fromTimeoutMs(a),s=()=>hm(r,i,n),c=async()=>{for(;;){let e=s();if(!e||o.isExpired())return;Xt({type:`command`,status:`progress`,message:`Waiting for ${e.session.device.name}: held by session "${e.address}" (${Math.round(o.elapsedMs())}ms of the ${Math.round(a)}ms wait budget used)`}),await yt(Math.min(250,o.remainingMs())),Kt(t.meta?.requestId)}};return{waitForDeviceOutsideLocks:c,runWhenDeviceIsUnheld:async e=>{let{acquireLocks:n,task:r}=e;for(;;){let e=await n(async()=>{if(s()){if(!o.isExpired())return{ran:!1};_m(t,o.elapsedMs())}return{ran:!0,outcome:await r()}});if(e.ran)return e.outcome;await c()}}}}function _m(e,t){if(t<=0)return;let n=e.internal??={};n.openDeviceWait={waitedMs:t}}const vm={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},ym=new Map;async function bm(e){let t=await z.mkdtemp(L.join(Un.tmpdir(),`agent-device-materialized-`));try{let n=await Tm(e.installablePath,L.join(t,`installable`)),r=e.archivePath?await Tm(e.archivePath,L.join(t,`archive`)):void 0,i=Vn.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{Cm(i)},a);return ym.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await z.rm(t,{recursive:!0,force:!0}),e}}async function xm(e,t){await wm(e,$t(ym,e,t,vm))}async function Sm(e){let t=Array.from(ym.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await wm(e,t)}))}async function Cm(e){let t=ym.get(e);if(t)try{await wm(e,t)}catch{}}async function wm(e,t){clearTimeout(t.timer),ym.delete(e),await z.rm(t.rootPath,{recursive:!0,force:!0})}async function Tm(e,t){let n=await z.stat(e);await z.mkdir(t,{recursive:!0});let r=L.join(t,L.basename(e));return n.isDirectory()?(await z.cp(e,r,{recursive:!0}),r):(await z.copyFile(e,r),r)}function Em(e){return e.device.platform===`web`}function Dm(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function Om(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await fn({session:t,sessionName:n,sessionStore:r,resourcePath:un.resolvePath(r.resolveSessionDir(n))})}async function km(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await dn({...e,session:t,intent:`disposal`})}async function Am(e,t){await t.stopSnapshotHelper(e.device)}async function jm(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>Dm(r)})}async function Mm(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function Nm(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return k({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function Pm(t){let{session:n,sessionName:r,sessionStore:i}=t;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[{step:`recording`,run:()=>Fm({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>Om({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Im({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>km({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>Am(n,a)},{step:`web_browser`,run:()=>jm({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>Sm(r)});let s=Nm({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await Mm(o)});if(s)throw s}async function Fm(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await zn({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Im(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await ln({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function Lm(e){return w(e)&&e.kind===`simulator`}function Rm(e){return e.platform===`android`&&e.kind===`emulator`}const zm=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Bm(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Vm(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Hm(e){return en(Vm(e))}function Um(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return A(t)}}function Wm(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function Gm(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Wm(t)}}function Km(t,n,r){if(t===void 0)return r;if(!s(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(r&&t!==r)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${n}" is bound to ${r}.`);return t}function qm(e){if(s(e))return e}function Jm(e,t){return{platform:t,metroHost:A(e?.metroHost),metroPort:Wm(e?.metroPort),bundleUrl:A(e?.bundleUrl),launchUrl:A(e?.launchUrl)}}function Ym(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Xm(e){if(Rm(e))return`10.0.2.2`;if(Lm(e))return`127.0.0.1`}function Zm(e,t){if(!e||A(e.metroHost)||A(e.bundleUrl)||e.metroPort===void 0)return e;let n=Xm(t);return n?{...e,metroHost:n}:e}function Qm(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!zm.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${zm.join(`, `)}.`);return{platform:Km(a.platform,r,i),metroHost:Um(a.metroHost,`metroHost`),metroPort:Gm(a.metroPort),bundleUrl:Um(a.bundleUrl,`bundleUrl`),launchUrl:Um(a.launchUrl,`launchUrl`)}}function $m(e,t,n){if(n){if(Bm(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function eh(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?T(r):void 0,s=qm(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function th(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?qm(T(i)):e.platform,o=n.getRuntimeHints(r),s=Qm({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=eh(n,r,i,a);return{runtime:i?Zm(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&Bm(s)>0?s:void 0;return{runtime:i?Zm(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function nh(e){return th(e).runtime}function rh(e){try{return{ok:!0,data:th(e)}}catch(e){let t=r(e);return u(t.code,t.message,t.details)}}async function ih(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!ah(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Vm(t)})}function ah(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Hm(e.previousRuntime)&&!Hm(e.runtime)}function oh(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&ve(i.owner,n)?le(i.fence):null;if(!a)return{status:`binding-invalid`};let o=P(pn(t)),s=on(nn(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!ch(c.stateDir,r)||!ve(an(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function sh(e){let t=P(pn(e));return tn(nn(t))}function ch(e,t){return L.resolve(e)===L.resolve(t)}function lh(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=T(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=S(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${Tt(i)}`,`${a} ${Tt(e.id)}`,...n===`release`||rn(t.classification)?[`--stale`]:[]].join(` `)}function uh(t,n){if(n.classification===`allocator-held`)return fh(t,n);let r=n.claim,i=lh(t,n,sn(n.classification)?`release`:`status`),a=T(r?{platform:r.device.family,appleOs:r.device.appleOs}:t);return new e(`DEVICE_IN_USE`,r?`${a} device ${t.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${t.name} has an ownership claim that could not be verified.`,{reason:yh(n.classification),classification:n.classification,deviceKey:n.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:sn(n.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function dh(e,t){return vh(uh(e,t))}function fh(t,n){let r=n.allocatorClaim,i=T({platform:r.device.family,appleOs:r.device.appleOs}),a=lh(t,n);return new e(`DEVICE_IN_USE`,`${i} device ${t.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:n.classification,deviceKey:n.deviceKey,owner:{kind:`allocator`,stateDir:r.stateDir,allocator:r.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function ph(t,n){return new e(`COMMAND_FAILED`,`${T(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:_e(n),deviceKey:P(pn(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function mh(t,n,r){return new e(`COMMAND_FAILED`,`${T(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:_e(n),deviceKey:P(pn(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function hh(t,n){return new e(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:_e(n),deviceKey:P(pn(t)),retriable:!1})}function gh(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:hh(e,t)};case`missing`:return{admitted:!1,error:ph(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:mh(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:uh(e,n.conflict)}}}function _h(e,t,n){let r=gh(e,t,n);return r.admitted?void 0:vh(r.error)}function vh(e){let{hint:t,retriable:n,...r}=e.details??{};return u(e.code,e.message,r,{hint:t,retriable:n})}function yh(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function bh(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{ar as $,bm as A,zs as B,km as C,Dm as D,Em as E,ff as F,vr as G,Ka as H,jl as I,hr as J,mr as K,Ol as L,pm as M,dm as N,xm as O,im as P,sr as Q,kl as R,Om as S,Pm as T,xr as U,cs as V,br as W,cr as X,gr as Y,or as Z,qm as _,uh as a,Fm as b,Jm as c,ih as d,ur as et,Ym as f,ah as g,$m as h,gh as i,Yn as it,mm as j,Sm as k,Bm as l,Vm as m,_h as n,$n as nt,sh as o,nh as p,pr as q,dh as r,Qn as rt,oh as s,bh as t,lr as tt,Hm as u,rh as v,Am as w,Nm as x,Im as y,Dl as z};
@@ -1,4 +1,4 @@
1
- import { O as Rect } from "./sdk-contracts.js";
1
+ import { k as Rect } from "./sdk-contracts.js";
2
2
  import { A as PointerTrajectory, M as SinglePointerGesturePlan, j as PointerTrajectorySample, k as MultiTouchGesturePlan } from "./sdk-selectors.js";
3
3
  import { Readable, Stream, Writable } from "node:stream";
4
4
  //#region packages/platform-android/src/helper-artifacts.d.ts
@@ -114,8 +114,8 @@ type AndroidAdbProcess = {
114
114
  * Runs device-scoped adb arguments after the device serial has already been selected.
115
115
  * Implementations must be safe to call concurrently for one request.
116
116
  */
117
- type AndroidAdbExecutor = (args: string[], options?: AndroidAdbExecutorOptions) => Promise<AndroidAdbExecutorResult>;
118
- type AndroidAdbSpawner = (args: string[], options?: AndroidAdbSpawnOptions) => AndroidAdbProcess;
117
+ type AndroidAdbExecutor = (args: readonly string[], options?: AndroidAdbExecutorOptions) => Promise<AndroidAdbExecutorResult>;
118
+ type AndroidAdbSpawner = (args: readonly string[], options?: AndroidAdbSpawnOptions) => AndroidAdbProcess;
119
119
  type AndroidPortReverseEndpoint = `tcp:${number}` | `localabstract:${string}`;
120
120
  type AndroidPortReverseMapping = {
121
121
  local: AndroidPortReverseEndpoint;
@@ -211,4 +211,4 @@ declare function dismissAndroidKeyboardWithAdb(adb: AndroidAdbExecutor): Promise
211
211
  declare function readAndroidClipboardWithAdb(adb: AndroidAdbExecutor): Promise<string>;
212
212
  declare function writeAndroidClipboardWithAdb(adb: AndroidAdbExecutor, text: string): Promise<void>;
213
213
  //#endregion
214
- export { readAndroidClipboardWithAdb as a, AndroidAdbExecutor as c, AndroidPortReverseEndpoint as d, AndroidPortReverseProvider as f, getAndroidKeyboardStatusWithAdb as i, AndroidAdbExecutorOptions as l, AndroidKeyboardState as n, writeAndroidClipboardWithAdb as o, dismissAndroidKeyboardWithAdb as r, AndroidInputOwner as s, AndroidKeyboardDismissResult as t, AndroidAdbProvider as u };
214
+ export { readAndroidClipboardWithAdb as a, AndroidAdbExecutor as c, AndroidAdbProvider as d, AndroidPortReverseEndpoint as f, getAndroidKeyboardStatusWithAdb as i, AndroidAdbExecutorOptions as l, AndroidKeyboardState as n, writeAndroidClipboardWithAdb as o, AndroidPortReverseProvider as p, dismissAndroidKeyboardWithAdb as r, AndroidInputOwner as s, AndroidKeyboardDismissResult as t, AndroidAdbExecutorResult as u };
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{C as t,j as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";var i=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,readInstalledAppProbe:()=>c,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>s});const a=`device_inventory_context_unavailable`,o=new r;async function s(e,t){return await o.run(e,t)}function c(){return o.getStore()?.findInstalledApp}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=o.getStore();if(!e)throw new t(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return n(e)||e instanceof t&&e.code===`COMMAND_FAILED`&&e.details?.reason===a?!0:e instanceof Error&&e.name===`AbortError`}export{m as a,u as i,l as n,s as o,d as r,i as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{D as t,F as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";var i=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,readInstalledAppProbe:()=>c,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>s});const a=`device_inventory_context_unavailable`,o=new r;async function s(e,t){return await o.run(e,t)}function c(){return o.getStore()?.findInstalledApp}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=o.getStore();if(!e)throw new t(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return n(e)||e instanceof t&&e.code===`COMMAND_FAILED`&&e.details?.reason===a?!0:e instanceof Error&&e.name===`AbortError`}export{m as a,u as i,l as n,s as o,d as r,i as t};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";const t=[`portrait`,`portrait-upside-down`,`landscape-left`,`landscape-right`],n={portrait:0,"landscape-left":1,"portrait-upside-down":2,"landscape-right":3};function r(e){return n[e]*90}function i(e){return n[e]%2==0?`PORTRAIT`:`LANDSCAPE`}function a(t){if(t===void 0)throw new e(`INVALID_ARGS`,`orientation requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.`);switch(t?.trim().toLowerCase()){case`portrait`:return`portrait`;case`portrait-upside-down`:case`upside-down`:return`portrait-upside-down`;case`landscape-left`:case`left`:return`landscape-left`;case`landscape-right`:case`right`:return`landscape-right`;default:throw new e(`INVALID_ARGS`,`Invalid rotation: ${t}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}export{a,r as i,n,i as r,t};
1
+ import{D as e}from"./sdk-contracts.js";const t=[`portrait`,`portrait-upside-down`,`landscape-left`,`landscape-right`],n={portrait:0,"landscape-left":1,"portrait-upside-down":2,"landscape-right":3};function r(e){return n[e]*90}function i(e){return n[e]%2==0?`PORTRAIT`:`LANDSCAPE`}function a(t){if(t===void 0)throw new e(`INVALID_ARGS`,`orientation requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.`);switch(t?.trim().toLowerCase()){case`portrait`:return`portrait`;case`portrait-upside-down`:case`upside-down`:return`portrait-upside-down`;case`landscape-left`:case`left`:return`landscape-left`;case`landscape-right`:case`right`:return`landscape-right`;default:throw new e(`INVALID_ARGS`,`Invalid rotation: ${t}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}export{a,r as i,n,i as r,t};