agent-device 0.21.0 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.apk → agent-device-android-ime-helper-0.21.2.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.manifest.json → agent-device-android-ime-helper-0.21.2.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.manifest.json → agent-device-android-snapshot-helper-0.21.2.manifest.json} +6 -6
  7. package/apple/snapshot-bridge/README.md +58 -1
  8. package/apple/snapshot-bridge/SnapshotBridge.m +6 -0
  9. package/apple/snapshot-bridge/SnapshotBridgeCapture.h +25 -0
  10. package/apple/snapshot-bridge/SnapshotBridgeCapture.m +138 -0
  11. package/apple/snapshot-bridge/SnapshotBridgeRuntime.h +1 -0
  12. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +32 -3
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +12 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +413 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +15 -15
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +72 -0
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +63 -14
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +668 -82
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +48 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +39 -4
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1078 -211
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +290 -0
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +1 -1
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +10 -10
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +250 -74
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +101 -42
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +13 -13
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +55 -43
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +71 -4
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +144 -7
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +13 -1
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +216 -17
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +206 -22
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +289 -42
  36. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +92 -22
  37. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +617 -122
  38. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +79 -4
  39. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +71 -71
  40. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +92 -6
  41. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +67 -67
  42. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +4 -4
  43. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +17 -17
  44. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +30 -30
  45. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +31 -31
  46. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +28 -0
  47. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +101 -0
  48. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +19 -19
  49. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +55 -17
  50. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +26 -5
  51. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +126 -75
  52. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +8 -12
  53. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +9 -9
  54. package/dist/src/absence-observation-errors.js +1 -0
  55. package/dist/src/adapter.js +1 -1
  56. package/dist/src/adb-executor.js +1 -1
  57. package/dist/src/adb-failure.js +1 -1
  58. package/dist/src/agent-browser-lifecycle.js +1 -1
  59. package/dist/src/agent-browser-process-record.js +1 -1
  60. package/dist/src/agent-browser-provider.js +1 -1
  61. package/dist/src/agent-browser-tool.js +1 -1
  62. package/dist/src/agent-device-client.js +2 -2
  63. package/dist/src/ai-sdk.d.ts +1 -1
  64. package/dist/src/ai-sdk.js +1 -1
  65. package/dist/src/alert-runtime.js +1 -1
  66. package/dist/src/android-input-ownership.js +1 -1
  67. package/dist/src/app-catalog.js +1 -1
  68. package/dist/src/app-deployment-resolution.js +1 -1
  69. package/dist/src/app-helpers.js +1 -1
  70. package/dist/src/app-inventory-contract.js +1 -1
  71. package/dist/src/app-inventory.js +1 -1
  72. package/dist/src/app-launch.js +2 -2
  73. package/dist/src/app-lifecycle.js +3 -3
  74. package/dist/src/app-lifecycle2.js +1 -1
  75. package/dist/src/app-log-files.js +1 -1
  76. package/dist/src/app-log-runtime2.js +3 -3
  77. package/dist/src/app-resolution.js +1 -1
  78. package/dist/src/apple-runner-platform.js +1 -0
  79. package/dist/src/application-lifecycle-interaction.js +1 -1
  80. package/dist/src/archive.js +1 -1
  81. package/dist/src/artifact-download.js +1 -1
  82. package/dist/src/auth-session.js +1 -1
  83. package/dist/src/auth.js +1 -1
  84. package/dist/src/back-mode.js +1 -1
  85. package/dist/src/backend-snapshot-options.js +1 -1
  86. package/dist/src/boot-diagnostics.js +1 -1
  87. package/dist/src/browser-launch.js +1 -0
  88. package/dist/src/capture.js +1 -1
  89. package/dist/src/catalog.js +1 -1
  90. package/dist/src/cli-config.js +1 -1
  91. package/dist/src/cli-help.js +30 -26
  92. package/dist/src/cli.js +4 -4
  93. package/dist/src/click-button.js +1 -1
  94. package/dist/src/client-metro-companion.js +1 -1
  95. package/dist/src/client-metro.js +1 -1
  96. package/dist/src/client-types.d.ts +28 -13
  97. package/dist/src/code-signature-cache.js +1 -1
  98. package/dist/src/code-signature.js +1 -1
  99. package/dist/src/command-metadata.js +1 -1
  100. package/dist/src/command-schema.js +3 -3
  101. package/dist/src/command-tools.js +2 -2
  102. package/dist/src/command.js +1 -1
  103. package/dist/src/config.js +1 -1
  104. package/dist/src/connection-runtime.js +1 -1
  105. package/dist/src/connection.js +3 -3
  106. package/dist/src/contracts.d.ts +1 -1
  107. package/dist/src/contracts.js +1 -1
  108. package/dist/src/daemon-client-lifecycle.js +1 -1
  109. package/dist/src/daemon-process.js +1 -1
  110. package/dist/src/daemon-shutdown-report.js +1 -1
  111. package/dist/src/daemon.js +1 -1
  112. package/dist/src/debug-symbols-facade.js +1 -1
  113. package/dist/src/device-boot.js +1 -0
  114. package/dist/src/device-claim-inspection.js +1 -1
  115. package/dist/src/device-claim-rule.js +1 -1
  116. package/dist/src/device-input-state.d.ts +1 -1
  117. package/dist/src/device-inventory-context.js +1 -1
  118. package/dist/src/device-rotation.js +1 -1
  119. package/dist/src/device-selection-resolver.js +1 -1
  120. package/dist/src/device-session.js +1 -1
  121. package/dist/src/device2.js +1 -1
  122. package/dist/src/diagnostics.js +1 -1
  123. package/dist/src/dispatch-resolve.js +1 -1
  124. package/dist/src/doctor2.js +1 -1
  125. package/dist/src/durable-resource.js +1 -1
  126. package/dist/src/engine-eval-script.js +1 -0
  127. package/dist/src/error.js +1 -1
  128. package/dist/src/exec.js +1 -1
  129. package/dist/src/file.js +1 -1
  130. package/dist/src/find.js +1 -1
  131. package/dist/src/finders.js +1 -1
  132. package/dist/src/format.js +1 -2
  133. package/dist/src/generic-settle.js +1 -1
  134. package/dist/src/gesture-plan.js +1 -1
  135. package/dist/src/gesture-runtime.js +1 -1
  136. package/dist/src/harmonyos.js +1 -1
  137. package/dist/src/hdc.js +1 -1
  138. package/dist/src/helper.js +2 -2
  139. package/dist/src/human-control-contract.js +1 -1
  140. package/dist/src/human-control.js +1 -1
  141. package/dist/src/index.d.ts +1 -1
  142. package/dist/src/index.js +1 -1
  143. package/dist/src/input-actions.js +1 -1
  144. package/dist/src/input-actions2.js +2 -2
  145. package/dist/src/install-artifact-facade.js +1 -1
  146. package/dist/src/install-source-network-transport.js +1 -1
  147. package/dist/src/install-source2.js +1 -1
  148. package/dist/src/interaction-positionals.js +1 -1
  149. package/dist/src/interaction-ref-policy.js +1 -1
  150. package/dist/src/interaction.js +1 -1
  151. package/dist/src/interaction2.js +1 -1
  152. package/dist/src/interactor.js +5 -5
  153. package/dist/src/interactor2.js +1 -1
  154. package/dist/src/interactors.js +1 -1
  155. package/dist/src/internal/bin.js +1 -1
  156. package/dist/src/internal/daemon.js +2 -2
  157. package/dist/src/internal/png-worker.d.ts +3 -0
  158. package/dist/src/internal/png-worker.js +1 -1
  159. package/dist/src/internal/run-script-http-child.js +1 -1
  160. package/dist/src/inventory.js +2 -2
  161. package/dist/src/inventory2.js +1 -1
  162. package/dist/src/inventory3.js +1 -1
  163. package/dist/src/inventory5.js +1 -1
  164. package/dist/src/ios-snapshot-acquisition.js +1 -1
  165. package/dist/src/ios-snapshot-planning.js +1 -1
  166. package/dist/src/ios-snapshot-runtime.js +1 -1
  167. package/dist/src/ios-system-surface.js +1 -0
  168. package/dist/src/lease-scope.js +1 -1
  169. package/dist/src/lease.js +1 -1
  170. package/dist/src/limrun-runtime-dependencies.js +1 -1
  171. package/dist/src/limrun.d.ts +1 -1
  172. package/dist/src/linux.js +1 -1
  173. package/dist/src/local-interactor-operation-set.js +1 -1
  174. package/dist/src/location-coordinates.js +1 -1
  175. package/dist/src/managed-device-scope.js +1 -1
  176. package/dist/src/mechanics.js +16 -16
  177. package/dist/src/mobile-snapshot-semantics.js +1 -1
  178. package/dist/src/mp4-atoms.js +1 -0
  179. package/dist/src/multitouch-support.js +1 -1
  180. package/dist/src/observation.js +1 -1
  181. package/dist/src/open-target-resolution.js +1 -0
  182. package/dist/src/owner-identity.js +3 -3
  183. package/dist/src/parameterized-recorded-fill.js +1 -1
  184. package/dist/src/perf-facade.js +2 -2
  185. package/dist/src/perf-process-identity.js +1 -0
  186. package/dist/src/perf-runtime-operation-builder.js +1 -1
  187. package/dist/src/perf-runtime-plan.js +1 -1
  188. package/dist/src/perf.js +1 -1
  189. package/dist/src/physical-device-control.js +1 -1
  190. package/dist/src/platform-request-scope.js +1 -1
  191. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  192. package/dist/src/platform-runtime-app-log-process.js +1 -1
  193. package/dist/src/platform-runtime-host.js +1 -1
  194. package/dist/src/platform-runtime-managed-owner.js +1 -1
  195. package/dist/src/platform-runtime-open-target.js +1 -1
  196. package/dist/src/platform-runtime-operation-host.js +2 -2
  197. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  198. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  199. package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -1
  200. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  201. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  202. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  203. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  204. package/dist/src/platform-runtime-unavailable.js +1 -1
  205. package/dist/src/platform-runtime.js +1 -1
  206. package/dist/src/platform-runtime2.js +1 -1
  207. package/dist/src/png-crop-bytes.js +1 -0
  208. package/dist/src/png-worker-contract.js +1 -1
  209. package/dist/src/png.js +1 -0
  210. package/dist/src/prepare-kind.js +1 -1
  211. package/dist/src/process.js +1 -1
  212. package/dist/src/provider-device-runtime.js +1 -1
  213. package/dist/src/provider-session-ownership.js +1 -1
  214. package/dist/src/provider-webdriver.js +1 -1
  215. package/dist/src/proxy.js +1 -1
  216. package/dist/src/quality-warnings.js +1 -0
  217. package/dist/src/react-native.js +1 -1
  218. package/dist/src/record-runtime.js +1 -1
  219. package/dist/src/rect-center.js +1 -1
  220. package/dist/src/register-builtins.js +1 -1
  221. package/dist/src/registry.js +36 -36
  222. package/dist/src/remote-config2.js +1 -1
  223. package/dist/src/replay-divergence.js +1 -1
  224. package/dist/src/replay.js +2 -2
  225. package/dist/src/reporting.js +9 -8
  226. package/dist/src/request-admission.js +1 -1
  227. package/dist/src/request-cancel.js +1 -1
  228. package/dist/src/request-cancellation.js +1 -1
  229. package/dist/src/request-runtime-binding.js +1 -1
  230. package/dist/src/retry.js +1 -1
  231. package/dist/src/runner-cache-metadata.js +2 -2
  232. package/dist/src/runner-client.js +1 -1
  233. package/dist/src/runner-disposal.js +1 -1
  234. package/dist/src/runner-operations-facade.js +1 -1
  235. package/dist/src/runner-presentation.js +1 -1
  236. package/dist/src/runner.js +1 -1
  237. package/dist/src/runtime-transport-hints.js +1 -1
  238. package/dist/src/runtime.js +3 -3
  239. package/dist/src/runtime10.js +1 -0
  240. package/dist/src/runtime2.js +4 -4
  241. package/dist/src/runtime3.js +1 -1
  242. package/dist/src/runtime4.js +5 -4
  243. package/dist/src/runtime5.js +1 -1
  244. package/dist/src/runtime6.js +1 -1
  245. package/dist/src/runtime7.js +1 -1
  246. package/dist/src/runtime8.js +1 -1
  247. package/dist/src/runtime9.js +1 -1
  248. package/dist/src/screen-recording-live-handle.js +1 -1
  249. package/dist/src/screen-recording-options.js +1 -1
  250. package/dist/src/screen-recording-resource-recovery.js +1 -1
  251. package/dist/src/screenshot-density.js +1 -1
  252. package/dist/src/screenshot-runtime.js +1 -1
  253. package/dist/src/screenshot.js +1 -1
  254. package/dist/src/screenshot3.js +3 -3
  255. package/dist/src/script.js +1 -1
  256. package/dist/src/scroll-command.js +1 -1
  257. package/dist/src/scroll-gesture.js +1 -1
  258. package/dist/src/sdk-batch-runner.js +2 -2
  259. package/dist/src/sdk-batch.js +2 -2
  260. package/dist/src/sdk-contracts.d.ts +69 -26
  261. package/dist/src/sdk-contracts.js +2 -2
  262. package/dist/src/sdk-device.js +1 -1
  263. package/dist/src/sdk-finders.d.ts +1 -1
  264. package/dist/src/sdk-finders.js +1 -1
  265. package/dist/src/sdk-io.js +1 -1
  266. package/dist/src/sdk-remote-config.d.ts +1 -1
  267. package/dist/src/sdk-remote-config.js +1 -1
  268. package/dist/src/sdk-selectors.d.ts +80 -16
  269. package/dist/src/sdk-selectors.js +1 -1
  270. package/dist/src/selection.js +0 -0
  271. package/dist/src/selector-runtime.js +1 -1
  272. package/dist/src/selectors.js +1 -1
  273. package/dist/src/semantic-index.js +1 -1
  274. package/dist/src/server.js +3 -3
  275. package/dist/src/session-allocation.js +1 -1
  276. package/dist/src/session-observation.js +1 -0
  277. package/dist/src/session-routing.js +1 -1
  278. package/dist/src/session-runtime-admission.js +1 -1
  279. package/dist/src/session-snapshot.js +1 -1
  280. package/dist/src/session-store.js +3 -3
  281. package/dist/src/session-target-evidence.js +1 -1
  282. package/dist/src/session2.js +5 -5
  283. package/dist/src/settings.js +1 -1
  284. package/dist/src/simulator-boot.js +3 -0
  285. package/dist/src/simulator.js +1 -1
  286. package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
  287. package/dist/src/snapshot-runtime-binding.js +1 -1
  288. package/dist/src/snapshot-runtime.js +1 -1
  289. package/dist/src/snapshot-state.js +1 -1
  290. package/dist/src/snapshot2.js +1 -1
  291. package/dist/src/snapshot3.js +1 -1
  292. package/dist/src/snapshot4.js +1 -1
  293. package/dist/src/src.js +1 -1
  294. package/dist/src/src7.js +2 -2
  295. package/dist/src/src8.js +2 -2
  296. package/dist/src/string-enum.js +1 -1
  297. package/dist/src/takeover.js +1 -1
  298. package/dist/src/telemetry.js +1 -1
  299. package/dist/src/tool-provider.js +2 -2
  300. package/dist/src/tool-provider2.js +1 -1
  301. package/dist/src/tool-provider3.js +1 -1
  302. package/dist/src/toolchain-probe.js +1 -1
  303. package/dist/src/touch-reference-frame.js +1 -0
  304. package/dist/src/touch-runtime.js +1 -1
  305. package/dist/src/transport.js +1 -1
  306. package/dist/src/tree.js +1 -1
  307. package/dist/src/tv-remote.js +1 -1
  308. package/dist/src/type-text-runtime.js +1 -1
  309. package/dist/src/update-check.js +1 -1
  310. package/dist/src/vars.js +2 -0
  311. package/dist/src/verified-file.js +1 -1
  312. package/dist/src/version.js +1 -1
  313. package/dist/src/video.js +2 -2
  314. package/dist/src/viewport.js +1 -0
  315. package/dist/src/web.js +1 -1
  316. package/dist/src/web2.js +1 -1
  317. package/dist/src/webdriver-ios-snapshot.js +1 -1
  318. package/dist/src/webdriver-source.js +1 -1
  319. package/dist/src/window-state.js +1 -0
  320. package/package.json +4 -2
  321. package/server.json +2 -2
  322. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.0.apk.sha256 +0 -1
  323. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk +0 -0
  324. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk.sha256 +0 -1
  325. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -93
  326. package/dist/src/platform-runtime-apple-resources.js +0 -1
  327. package/dist/src/runner-selector-query.js +0 -1
  328. package/dist/src/snapshot-quality-verdict.js +0 -1
@@ -1 +1 @@
1
- import{f as e,m as t,y as n}from"./sdk-contracts.js";import{u as r}from"./capture.js";import{r as i}from"./snapshot-capture-annotations.js";import{r as a}from"./snapshot-diagnostics.js";import{f as o}from"./android-input-ownership.js";import{c as s,d as c,v as l}from"./sdk-device.js";import{It as u,St as d,Tr as f,ct as ee,lt as te,ot as ne,pt as re,st as ie,vt as ae,zt as oe}from"./sdk-batch.js";import{C as se,u as ce,w as le}from"./runtime.js";import{n as p}from"./success-text.js";import{i as ue}from"./click-button.js";import{a as de,r as m}from"./diagnostics.js";import{t as h}from"./timeouts.js";import"./diagnostics2.js";import"./retry.js";import{t as fe}from"./snapshot-state.js";import{i as pe}from"./lease-context.js";import{i as g,n as me}from"./request-runtime-binding.js";import{t as he}from"./interactor-types.js";import{randomInt as ge}from"node:crypto";var _=class e{#e;constructor(e){this.#e=e}get state(){return this.#e.state}get scope(){return this.#e.scope}get tree(){return this.#e.tree}get generation(){return this.#e.generation}static expire(t){return t.#e.state===`expired`?t:new e({...t.#e,state:`expired`})}};const _e=new _({state:`active`,scope:`all`,tree:void 0,generation:void 0});function ve(e){return new _({state:`active`,...e})}function ye(e){return _.expire(e)}const be=new WeakMap;function v(e){return e.refFrame??_e}function y(e){return v(e).generation??e.snapshotGeneration}function xe(e){return v(e).tree}function Se(e){Ce(e),e.refFrame=ye(v(e)),e.snapshotScopeSource=void 0}function Ce(e){let t=we(e)+1;return be.set(e,t),t}function we(e){return be.get(e)??0}function Te(e){b(e,`all`)}function Ee(e,t){b(e,t)}function b(e,t){e.refFrame=ve({scope:t,tree:e.snapshot,generation:e.snapshotGeneration})}function x(e){return v(e).state}function S(e){return v(e).scope}function De(e){let t=e.ref.startsWith(`@`)?e.ref.slice(1):e.ref;return{admission:Oe({session:e.session,refBody:t,mintedGeneration:e.mintedGeneration}),scope:S(e.session),currentGeneration:y(e.session)}}function Oe(e){let{session:t,refBody:n,mintedGeneration:r}=e;if(x(t)===`expired`)return{admitted:!1,reason:`ref_frame_expired`};if(r!==void 0&&r!==y(t))return{admitted:!1,reason:`ref_generation_mismatch`};let i=S(t);if(i!==`all`){if(r===void 0)return{admitted:!1,reason:`plain_ref_requires_complete_frame`};if(!i.has(n))return{admitted:!1,reason:`ref_not_issued`}}return{admitted:!0}}const ke=[250,400,600];function C(e){return e===`press`||e===`click`||e===`back`||e===`open`}function w(e){return e.map(e=>[e.depth??0,e.type??``,e.label??``,e.value??``,e.identifier??``,e.enabled===!1?`disabled`:`enabled`,e.hittable===!0?`hittable`:`not-hittable`].join(`|`))}function Ae(e,t){return e<12?!1:t<=Math.floor(e*.2)}function je(e,t,n){return n.interactiveOnly&&e.snapshot.nodes.length===0&&e.rawNodeCount!==void 0&&e.rawNodeCount>=12?`empty-interactive`:n.mode===`ref-refresh`?null:Ae(t.baselineCount,e.snapshot.nodes.length)?Me(e.snapshot)?null:`sharp-drop`:t.routeComparable&&C(t.action)&&Ne(t.baselineSignatures,e.snapshot.nodes)?`stuck-route`:null}function Me(e){return e.nodes.some(e=>e.hittable===!0||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())}function Ne(e,t){if(!e||e.length===0)return!1;let n=Math.max(e.length,t.length);if(n<12)return!1;let r=w(t),i=Math.min(e.length,r.length),a=0;for(let t=0;t<i;t+=1)e[t]===r[t]&&(a+=1);let o=Math.max(0,r.length-e.length),s=Math.max(0,e.length-r.length),c=Math.max(3,Math.floor(n*.15));return a>=Math.floor(n*.9)&&o<=c&&s<=c}async function Pe(e){let t=e.window.markedAt+e.retry.retryBudgetMs,n=await e.capture(),r=e.classify(n),a=0;for(let i of e.retry.delaysMs){if(!r)break;let o=t-Date.now();if(o<=0)break;await h(Math.min(i,o)),n=await e.capture(),a+=1,r=e.classify(n)}r||e.onTrustworthyCapture?.();let o=a>0||r?{action:e.window.action,retryCount:a,staleAfterRetries:!!r,reason:r??void 0}:void 0;return{...n,annotations:{...n.annotations,...i({freshness:o})}}}function Fe(e,t,n=e.snapshot){if(e.device.platform!==`android`)return;let r=Ie(e,n),i=r?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:(r??n)?.nodes.length??0,baselineSignatures:i?w(r?.nodes??[]):void 0,routeComparable:i}}function Ie(e,t){if(t?.comparisonSafe===!0)return t;let n=e.lastComparisonSafeSnapshot;return!n||n.comparisonSafe!==!0?t:Date.now()-n.createdAt<=5e3?n:t}function T(e){if(!e||e.device.platform!==`android`)return;let t=e.androidSnapshotFreshness;if(t){if(Date.now()-t.markedAt>2500){delete e.androidSnapshotFreshness;return}return t}}function E(e){!e||e.device.platform!==`android`||delete e.androidSnapshotFreshness}async function Le(e,t){return Pe({capture:e.capture,classify:n=>je({snapshot:n.snapshot,rawNodeCount:n.annotations.analysis?.rawNodeCount},t,{interactiveOnly:e.interactiveOnly,mode:e.androidFreshnessMode}),window:t,retry:{retryBudgetMs:1500,delaysMs:ke},onTrustworthyCapture:()=>E(e.session)})}function Re(e,t){return`${[e,...t].join(` `).trim()} produced no visible change: the tree still matches its pre-gesture state. Either the container is already at its edge, or it ignores synthesized scrolls — a raw drag moves such lists: swipe x1 y1 x2 y2 (start inside the list).`}function ze(e,t){return t?{...e,warnings:[...e.warnings??[],Re(t.action,t.positionals)]}:e}function D(e,t,n,i,a,o){return{requestId:a??de().requestId,appBundleId:n,runnerLeaseContext:pe({meta:o}),activity:t?.activity,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,clearAppState:t?.clearAppState,verbose:t?.verbose,logPath:e,traceLogPath:i,iosXctestrunFile:t?.iosXctestrunFile,iosXctestDerivedDataPath:t?.iosXctestDerivedDataPath,iosXctestEnvDir:t?.iosXctestEnvDir,screenshotCaptureBackend:t?.maestro?.screenshotCaptureBackend,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotPreferredBackend:t?.snapshotPreferredBackend,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,snapshotCustomActions:t?.snapshotCustomActions,snapshotIncludeHiddenContentHints:t?.snapshotIncludeHiddenContentHints,...r(t),count:t?.count,intervalMs:t?.intervalMs,delayMs:t?.delayMs,durationMs:t?.durationMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,pixels:t?.pixels,doubleTap:t?.doubleTap,clickButton:ue(t),backMode:t?.backMode,pauseMs:t?.pauseMs,pattern:t?.pattern}}function Be(e){return e?.interactionOutcome?.retryOnNoChange===!0}function Ve(e){let{session:t,command:n,positionals:r,flags:i,preSnapshot:a}=e;if(!Be(i)||!L(t))return;let o=Ye(n);if(!o||!et(r))return;let s=M(a?.nodes??[]);s.length!==0&&(t.pendingInteractionOutcome={action:n,command:o,positionals:r,flags:j(i),markedAt:Date.now(),attemptsRemaining:2,preSignature:s})}function He(e){let t=e?.pendingInteractionOutcome;if(!(!e||!t)){if(!L(e)){O(e);return}if(Date.now()-t.markedAt>3e4){O(e);return}return t}}function O(e){e?.pendingInteractionOutcome&&(e.pendingInteractionOutcome=void 0)}async function k(e){let{pending:t,snapshot:n}=e,r=N(t.preSignature,M(n.nodes));if(r!==`unchanged`||t.attemptsRemaining<=0)return{retried:!1,change:r};let i=e.retryTap,a=i?R(t.positionals):void 0;if(!i||!a)return A(t,i?`unreadable-retry-point`:`device-runtime-unavailable`),{retried:!1,change:r};let o=Date.now();return--t.attemptsRemaining,await Ue(i,e)?(m({level:`info`,phase:`interaction_no_change_retry`,data:{action:t.action,attemptsRemaining:t.attemptsRemaining,durationMs:Date.now()-o}}),{retried:!0,change:r}):(A(t,`retry-tap-unavailable`),{retried:!1,change:r})}async function Ue(e,t){let{session:n,pending:r}=t,i=R(r.positionals);if(!i)return!1;try{return await e({device:n.device,point:i,context:{...D(t.logPath,r.flags,n.appBundleId,n.trace?.outPath),surface:n.surface}})}catch{return!1}}function A(e,t){m({level:`info`,phase:`interaction_no_change_retry_skipped`,data:{action:e.action,attemptsRemaining:e.attemptsRemaining,reason:t}})}function We(e){m({level:e.attempts>0?`info`:`debug`,phase:`interaction_settled`,data:{action:e.pending.action,change:e.change,attempts:e.attempts,durationMs:Date.now()-e.startedAt}})}function Ge(e){m({level:`warn`,phase:`interaction_settle_timeout`,data:{action:e.pending.action,attempts:e.attempts,durationMs:Date.now()-e.startedAt}})}function j(e){if(!e?.interactionOutcome&&!e?.postGestureStabilization)return e;let{interactionOutcome:t,postGestureStabilization:n,...r}=e;return r}function M(e){let t=new Map,n=[],r=le(e);for(let i of e){let e=Xe(i,t,r);e&&n.push(e)}return n}function N(e,t){return e.length===0||t.length===0?`ambiguous`:F(e,t)?`unchanged`:`changed`}function P(e,t){return Math.abs(e.x-t.x)<=1&&Math.abs(e.y-t.y)<=1&&Math.abs(e.width-t.width)<=1&&Math.abs(e.height-t.height)<=1}function F(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.key!==i.key||!P(r,i))return!1}return!0}function Ke(e,t){let n=I(e),r=I(t);if(n.size===0||r.size===0)return`ambiguous`;let i=0,a=!1;for(let[e,t]of n){let n=r.get(e);if(!n){a=!0;continue}if(i+=1,!P(t,n))return`changed`}if(i===0)return`ambiguous`;let o=r.size>i;return a&&o?`changed`:`unchanged`}function I(e){let t=new Map;for(let n of e)!n.identity||!n.discriminating||t.has(n.identity)||t.set(n.identity,n);return t}function qe(e,t){let n=e.filter(e=>e.discriminating),r=t.filter(e=>e.discriminating);if(n.length===0||n.length!==r.length)return!1;let i=new Map(r.map(e=>[e.key,e]));for(let e of n){let t=i.get(e.key);if(!t||!P(e,t))return!1}return!0}function Je(e,t){let n=new Map(t.filter(e=>e.discriminating).map(e=>[e.key,e])),r=0,i=0,a=0;for(let t of e){if(!t.discriminating)continue;let e=n.get(t.key);if(!e){r+=1;continue}n.delete(t.key),a+=1,P(t,e)||(i+=1)}return{onlyInBaseline:r,onlyInCurrent:n.size,rectMismatched:i,shared:a}}function L(e){return c(e.device)}function R(e){let t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?{x:t,y:n}:void 0}function Ye(e){if(e===`click`||e===`press`)return`press`}function Xe(e,t,n){if(!e.rect||!tt(e.rect)||nt(e))return;let r=$e(e);if(!r)return;let i=t.get(r)??0;t.set(r,i+1);let a=Ze(e);return{key:`${r}|#${i}`,...a?{identity:a}:{},x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height),discriminating:!Qe(e,n)}}function Ze(e){let t=[e.identifier,e.label,e.value].map(e=>typeof e==`string`?e.trim():``).join(`|`);if(t.replaceAll(`|`,``))return`${t}|${e.type??``}`}function Qe(e,t){return f(e)||e.ref!==void 0&&t.has(e.ref)}function $e(e){let t=[e.identifier,e.label,e.value,e.type,e.role,e.enabled===!1?`disabled`:`enabled`,e.selected===!0?`selected`:`unselected`,e.hittable===!0?`hittable`:`not-hittable`].map(e=>typeof e==`string`?e.trim():``).join(`|`);return t.replaceAll(`|`,``)?t:void 0}function et(e){return e.length===2&&e.every(e=>Number.isFinite(Number(e)))}function tt(e){return[e.x,e.y,e.width,e.height].every(e=>Number.isFinite(e))&&e.width>0&&e.height>0}function nt(e){return`${e.label??``} ${e.identifier??``}`.toLowerCase().includes(`scroll bar`)}const z=3500;function rt(e){let{needsBaselineDistrust:t,baselineSignature:n,quietSignature:r,elapsedMs:i,distrustCapMs:a}=e;return!t||!n?.length||e.classifyBaselineEvidence(n,r)!==`unchanged`?`trust`:i<a?`distrust`:`accept-stale`}async function it(e){let{pending:t,needsBaselineDistrust:n,hooks:r}=e,i=Date.now(),a=1,o=await B(r,e.initial),s=t.baselineSignature,c=t.baselineBackend,l=!1,u=1500;for(;a<2||Date.now()-i<u;){await h(200),a+=1;let e=await B(r);if(r.signaturesStable(o.signature,e.signature)){let d=Date.now()-i;if(s&&c!==e.backend){m({level:`debug`,phase:`post_gesture_snapshot_baseline_rebased`,data:{action:t.action,from:c,to:e.backend,attempts:a}}),s=e.signature,c=e.backend,l=!0,o=e;continue}let f=rt({needsBaselineDistrust:n,baselineSignature:s,quietSignature:e.signature,elapsedMs:d,distrustCapMs:z,classifyBaselineEvidence:r.classifyBaselineEvidence});if(f===`distrust`){u=z,o=e;continue}return at(f,t.action,a,d),ot(f,t,e,r,l)}o=e}return m({level:`warn`,phase:`post_gesture_snapshot_stabilization_timeout`,data:{action:t.action,attempts:a,durationMs:Date.now()-i}}),{value:o.value}}async function B(e,t){let n=t??await e.capture();return{value:n,...e.readSurface(n)}}function at(e,t,n,r){if(e===`accept-stale`){m({level:`warn`,phase:`post_gesture_snapshot_stale_accept`,data:{action:t,attempts:n,durationMs:r,matchedPreGestureBaseline:!0}});return}m({level:n>2?`info`:`debug`,phase:`post_gesture_snapshot_stabilized`,data:{action:t,attempts:n,durationMs:r}})}function ot(e,t,n,r,i){if(e!==`accept-stale`)return{value:n.value};let a=t.baselineSignature;return a!==void 0&&r.surfacesIdentical(a,n.signature)?{value:n.value,gestureNoEffect:{action:t.action,positionals:t.positionals}}:(m({level:`info`,phase:`post_gesture_no_effect_vetoed`,data:{action:t.action,backend:n.backend,...i?{reason:`baseline_rebased`}:{reason:`surface_divergence`,...a===void 0?{}:r.summarizeDivergence(a,n.signature)}}}),{value:n.value})}function st(e){let{session:t,command:n,action:r=n,positionals:i,flags:a,scheduleOutcomeRetry:o=!1,androidFreshnessBaseline:s}=e;o&&Ve({session:t,command:n,positionals:i,flags:a,preSnapshot:t.snapshot}),C(r)&&Fe(t,r,s??t.snapshot),ct(t,r,i,a)}function ct(e,t,n=[],r){if(!K(e.device)||!pt(t,n,r))return;let i=q(e.device)?M(e.snapshot?.nodes??[]):void 0;e.postGestureStabilization={action:t,positionals:n,markedAt:Date.now(),...i?.length?{baselineSignature:i,baselineBackend:G(e.snapshot)}:{}}}function lt(e){e?.postGestureStabilization&&(e.postGestureStabilization=void 0)}function V(e){return!!e?.postGestureStabilization}async function ut(e){let t=He(e.session);if(t&&e.session)return await dt({...e,session:e.session},t);if(c(e.device)&&e.session&&V(e.session))return await ft({...e,session:e.session});let n=T(e.session);if(n&&e.device.platform===`android`){let t=await Le(e,n);return{snapshot:t.snapshot,...t.annotations}}}async function dt(e,t){let n=e.session,r=Date.now(),i=0,a=await H(e,t,await U(e)),o=await k({session:n,pending:t,logPath:e.logPath,snapshot:a.snapshot,retryTap:e.retryTap});for(;o.retried;)i+=1,a=await H(e,t,await U(e)),o=await k({session:n,pending:t,logPath:e.logPath,snapshot:a.snapshot,retryTap:e.retryTap});O(n);let s=await W({session:n,initial:a,capture:async()=>await U(e),readSnapshot:e=>e.snapshot});return a=s.value,o.change!==`ambiguous`&&a.annotations.freshness?.staleAfterRetries!==!0&&E(n),o.change===`unchanged`?Ge({pending:t,attempts:i,startedAt:r}):We({pending:t,change:o.change,attempts:i,startedAt:r}),{snapshot:a.snapshot,...ze(a.annotations,s.gestureNoEffect)}}async function H(e,t,n){let r=n;return N(t.preSignature,M(r.snapshot.nodes))===`unchanged`?(await h(500),r=await U(e),r):r}async function ft(e){let t=await W({session:e.session,capture:async()=>await U(e),readSnapshot:e=>e.snapshot}),n=t.value;return{snapshot:n.snapshot,...ze(n.annotations,t.gestureNoEffect)}}async function U(e){let t=T(e.session);return t&&e.device.platform===`android`?await Le(e,t):await e.capture()}async function W(e){let{session:t,capture:n,readSnapshot:r}=e,i=t?.postGestureStabilization;if(!t||!K(t.device)||!i)return{value:e.initial??await n()};let a=await it({pending:{action:i.action,positionals:i.positionals??[],baselineSignature:i.baselineSignature,baselineBackend:i.baselineBackend},needsBaselineDistrust:q(t.device),initial:e.initial,hooks:{capture:n,readSurface:e=>{let t=r(e);return{signature:M(t.nodes),backend:G(t)}},signaturesStable:F,classifyBaselineEvidence:Ke,surfacesIdentical:qe,summarizeDivergence:Je}});return lt(t),a}function G(e){return e?.comparisonKey??e?.snapshotQuality?.backend}function pt(e,t,n){return n?.postGestureStabilization===!1?!1:n?.postGestureStabilization===!0||e===`swipe`||e===`scroll`||e===`gesture`&&t[0]===`swipe`}function K(e){return c(e)}function q(e){return s(e.platform)}async function J(e){let t=await ht(e.inspectFacts)(e.device);for(let n of e.required){let r=t.operations[n];if(!r.available)return{type:`response`,response:e.unavailableResponse?e.unavailableResponse(r):g(`UNSUPPORTED_OPERATION`,`${e.command} is not supported on this device`,void 0,r.hint?{hint:r.hint}:void 0)}}return{type:`admitted`,bind:gt(e.bindDevice)}}async function Y(e){let t=await J({...e,required:e.use.required});if(t.type===`response`)return t;let n=await t.bind(e.device,e.use);return e.readiness!==void 0&&await me(n,e.readiness),{type:`runtime`,runtime:n}}async function mt(e,t){let n=await Y(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:async({dispatchContext:e})=>await t(r,e)}}function ht(e){if(e)return e;throw new n(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`,{reason:`runtime-gateway-missing`})}function gt(e){if(e)return e;throw new n(`COMMAND_FAILED`,`Device runtime binding is unavailable.`,{reason:`runtime-gateway-missing`})}function _t(e){let{flags:t,logPath:n,meta:r,session:i,snapshotScope:a}=e,{appBundleId:o,trace:s,surface:c}=i??{},l=e.context??D(n??``,t,o,s?.outPath,r?.requestId,r);return{options:{appBundleId:o,interactiveOnly:t?.snapshotInteractiveOnly,preferredBackend:t?.snapshotPreferredBackend,depth:t?.snapshotDepth,scope:a,raw:t?.snapshotRaw,customActions:t?.snapshotCustomActions,includeHiddenContentHints:t?.snapshotIncludeHiddenContentHints,includeRects:e.includeRects,surface:c},execution:X(l),...e.signal===void 0?{}:{signal:e.signal}}}function X(e){return{requestId:e.requestId,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}async function vt(e){let{getInteractor:t}=await import(`./interactors.js`),n=await(await t(e.device,e.runnerContext)).snapshot(e.options);if(!(`stage`in n))return n;let{presentIosSnapshotAcquisition:r}=await import(`./ios-snapshot-runtime.js`);return await r(n,e.options)}function yt(e){let t=e?e.textEntryReadiness:void 0,n=wt(t)?{textEntryReadiness:t}:{},r=bt(e);return r?{...n,...r}:n}function bt(e){if(!xt(e))return null;let t=St(e.target);return t?{verification:`unconfirmed`,requested:e.requested,before:e.before,after:e.after,target:t}:null}function xt(e){return!!(e&&e.verification===`unconfirmed`&&typeof e.requested==`string`&&Z(e.before)&&Z(e.after))}function St(e){if(!Et(e)||!Ct(e))return null;let t=Tt(e.rect);return t?{resourceId:e.resourceId,className:e.className,packageName:e.packageName,rect:t}:null}function Ct(e){return Z(e.resourceId)&&Z(e.className)&&Z(e.packageName)}function wt(e){return typeof e==`string`&&he.includes(e)}function Z(e){return e===null||typeof e==`string`}function Tt(e){return!Et(e)||![e.x,e.y,e.width,e.height].every(e=>typeof e==`number`)?null:e}function Et(e){return!!e&&typeof e==`object`}async function Q(e){let t={device:e.device,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice},n=u(e.command,e.requiresCapture),r=await J({command:e.command,required:n.use.required,...e.unavailableResponse?{unavailableResponse:e.unavailableResponse}:{},...t});if(r.type===`response`)return{ok:!1,response:r.response};let i=r.bind;switch(n.kind){case`tap-point`:return{ok:!0,runtime:{kind:`tap`,captured:!1,runtime:await i(e.device,oe)}};case`captured-tap`:return{ok:!0,runtime:{kind:`tap`,captured:!0,runtime:await i(e.device,te)}};case`long-press-point`:return{ok:!0,runtime:{kind:`long-press`,captured:!1,runtime:await i(e.device,d)}};case`captured-long-press`:return{ok:!0,runtime:{kind:`long-press`,captured:!0,runtime:await i(e.device,ee)}};case`hover-point`:return{ok:!0,runtime:{kind:`hover`,captured:!1,runtime:await i(e.device,ae)}};case`captured-hover`:return{ok:!0,runtime:{kind:`hover`,captured:!0,runtime:await i(e.device,ie)}};case`fill-point`:return{ok:!0,runtime:{kind:`fill`,captured:!1,runtime:await i(e.device,re)}};case`captured-fill`:return{ok:!0,runtime:{kind:`fill`,captured:!0,runtime:await i(e.device,ne)}}}}function Dt(e,t){let n={execution:X(t),appBundleId:t.appBundleId},r=e.captured?Nt(e.runtime):void 0;switch(e.kind){case`tap`:return Ot(e,t,n,r);case`long-press`:return kt(e,n,r);case`hover`:return At(e,n,r);case`fill`:return jt(e,t,n,r)}}function Ot(e,t,n,r){let i=e.captured?e.runtime.operations.tapRef:void 0,a=e.captured?e.runtime.operations.tapElementSelector:void 0;return Object.freeze({captureSnapshot:r,tapPoint:async(r,i={})=>{let a=Pt(i,t),o=await e.runtime.operations.tapPoint({point:r,options:a,...n});return{x:r.x,y:r.y,count:a.count,intervalMs:a.intervalMs,holdMs:a.holdMs,jitterPx:a.jitterPx,doubleTap:a.doubleTap,...a.button===`primary`?{}:{button:a.button},...o??{},...p(Lt(r,a.button))}},tapRef:i?async e=>await i({ref:e,...n}):void 0,tapElementSelector:e.captured&&a?async t=>{let r=await e.runtime.operations.tapElementSelector?.({selector:t,...n}),i=r?.maestroNonHittableCoordinateFallbackUsed===!0;return{selector:t.raw,...r??{},...p(i?`tapped via non-hittable coordinate fallback`:`Tapped ${t.raw}`)}}:void 0})}function kt(e,t,n){return Object.freeze({captureSnapshot:n,longPressPoint:async(n,r)=>{let i=await e.runtime.operations.longPressPoint({point:n,durationMs:r,...t});return{x:n.x,y:n.y,durationMs:r,...i??{},...p(`Long pressed (${n.x}, ${n.y})`)}}})}function At(e,t,n){let r=e.captured?e.runtime.operations.hoverRef:void 0;return Object.freeze({captureSnapshot:n,hoverPoint:async n=>{let r=await e.runtime.operations.hoverPoint({point:n,...t});return{x:n.x,y:n.y,...r??{},...p(`Hovered (${n.x}, ${n.y})`)}},hoverRef:r?async e=>await r({ref:e,...t}):void 0})}function jt(e,t,n,r){let i=e.captured?e.runtime.operations.fillRef:void 0,a=e=>se(e??t.delayMs??0,`delay-ms`,0,1e4);return Object.freeze({captureSnapshot:r,fillPoint:async(t,r,i={})=>{let o=a(i.delayMs),s=await e.runtime.operations.fillPoint({point:t,text:r,delayMs:o,allowNonHittableCoordinateFallback:i.allowNonHittableCoordinateFallback===!0,...n});return{x:t.x,y:t.y,text:r,delayMs:o,...Mt(s)?{maestroNonHittableCoordinateFallbackUsed:!0}:{},...yt(s),...p(`Filled ${Array.from(r).length} chars`)}},fillRef:i?async(e,t,r={})=>await i({ref:e,text:t,delayMs:a(r.delayMs),...n}):void 0})}function Mt(e){return typeof e==`object`&&!!e&&`maestroNonHittableCoordinateFallbackUsed`in e&&e.maestroNonHittableCoordinateFallbackUsed===!0}function Nt(e){return async t=>await e.operations.captureSnapshot(t)}function Pt(e,t){let n=Ft(e,t);return It(n),{button:e.button??ue(t),...n,surface:e.surface??t.surface}}function Ft(e,t){return{count:$(e.count,t.count,1,`count`,1,200),intervalMs:$(e.intervalMs,t.intervalMs,0,`interval-ms`,0,1e4),holdMs:$(e.holdMs,t.holdMs,0,`hold-ms`,0,1e4),jitterPx:$(e.jitterPx,t.jitterPx,0,`jitter-px`,0,100),doubleTap:e.doubleTap??t.doubleTap??!1}}function $(e,t,n,r,i,a){return se(e??t??n,r,i,a)}function It(e){if(e.doubleTap&&e.holdMs>0)throw new n(`INVALID_ARGS`,`double-tap cannot be combined with hold-ms`);if(e.doubleTap&&e.jitterPx>0)throw new n(`INVALID_ARGS`,`double-tap cannot be combined with jitter-px`)}function Lt(e,t){return t===`primary`?`Pressed (${e.x}, ${e.y})`:`${t===`secondary`?`Right`:`Middle`} clicked (${e.x}, ${e.y})`}function Rt(e){let{inspectFacts:t,bindDevice:n}=e;if(!t||!n)return;let r=new Map;return async({device:e,point:i,context:a})=>{let o=r.get(e.id);o||(o=Q({device:e,command:`press`,requiresCapture:!1,inspectFacts:t,bindDevice:n}),r.set(e.id,o));let s=await o;if(!s.ok)return!1;let c=Dt(s.runtime,a);return c.tapPoint?(await c.tapPoint(i),!0):!1}}async function zt(e){let t=await ut({session:e.session,device:e.device,logPath:e.logPath,interactiveOnly:e.flags?.snapshotInteractiveOnly===!0,androidFreshnessMode:e.androidFreshnessMode,capture:()=>Vt(e),retryTap:Rt(e)});if(t)return t;let n=await Vt(e);return E(e.session),{snapshot:n.snapshot,...n.annotations}}async function Bt(e){if(e.captureData)return await e.captureData();let{device:t,session:n,logPath:r}=e,i=D(r,Ht(e),n?.appBundleId,n?.trace?.outPath);return await vt({device:t,runnerContext:{requestId:i.requestId,signal:e.signal,appBundleId:i.appBundleId,verbose:i.verbose,logPath:i.logPath,traceLogPath:i.traceLogPath,iosXctestrunFile:i.iosXctestrunFile,iosXctestDerivedDataPath:i.iosXctestDerivedDataPath,iosXctestEnvDir:i.iosXctestEnvDir,runnerLeaseContext:i.runnerLeaseContext},options:{appBundleId:i.appBundleId,signal:e.signal,interactiveOnly:i.snapshotInteractiveOnly,preferredBackend:i.snapshotPreferredBackend,depth:i.snapshotDepth,scope:i.snapshotScope,raw:i.snapshotRaw,customActions:i.snapshotCustomActions,includeRects:e.includeRects,includeHiddenContentHints:i.snapshotIncludeHiddenContentHints,surface:n?.surface}})}async function Vt(e){let t=Date.now(),n=await Bt(e);a(e.session,{durationMs:Date.now()-t,backend:n.backend,platform:l(e.device)});let r=i(n),s=o(n,fe(n,Ht(e)));return r.androidSnapshot?.systemSurfaceOnly===!0&&(s.systemSurfaceOnly=!0),{data:n,snapshot:s,annotations:r}}function Ht(e){return e.snapshotScope===void 0?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function Ut(n,r){if(!n||!n.trim().startsWith(`@`))return{ok:!0,scope:n};if(!r?.snapshot)return g(`INVALID_ARGS`,`Ref scope requires an existing snapshot in session.`);let i=t(n.trim());if(!i)return g(`INVALID_ARGS`,`Invalid ref scope: ${n}`);let a=[r.snapshot,...r.snapshotScopeSource?[r.snapshotScopeSource]:[]],o;for(let t of a){let n=e(t.nodes,i);if(o=n?ce(n,t.nodes):void 0,o)break}return o?{ok:!0,scope:o}:g(`COMMAND_FAILED`,`Ref ${n} not found or has no label`)}function Wt(e,t,n={}){if(!e)return;let r=xe(e);return{name:t,appBundleId:e.appBundleId,appName:e.appName,...n.includeSnapshot===!0?{snapshot:e.snapshot,...r&&n.omitRefFrameSnapshot!==!0?{refFrameSnapshot:r}:{}}:{},metadata:{surface:e.surface,...n.metadata??{}}}}function Gt(e){return{get:t=>t===e.sessionName?Wt(e.getSession(),e.sessionName,e.recordOptions):void 0,set:t=>{if(t.name!==e.sessionName){m({level:`warn`,phase:`runtime_session_write_skipped`,data:{expected:e.sessionName,received:t.name}});return}e.setRecord(t)}}}function Kt(e,t){e.snapshot!==t&&(e.snapshotGeneration=Jt(e.snapshotGeneration)),e.snapshot=t,e.snapshotScopeSource=void 0,t.comparisonSafe===!0&&(e.lastComparisonSafeSnapshot=t)}function qt(e,t){e.snapshotScopeSource=t.scopeSource,e.snapshotGeneration=t.keptCurrentSnapshot?t.previousGeneration:Jt(t.previousGeneration)}function Jt(e){return e===void 0?ge(1e5,1e6):e+1}function Yt(e){let t=e.startsWith(`@`)?e.slice(1):e,n=t.indexOf(`~`);return n===-1?t:t.slice(0,n)}function Xt(e,t){let n=new Set;for(let e of t){let t=Yt(e);t.length>0&&n.add(t)}n.size!==0&&Ee(e,n)}function Zt(e,t){if(t?.diff)return Xt(e,Qt(t)),e.snapshotGeneration}function Qt(e){let t=[];for(let n of e.diff?.lines??[])n.ref&&t.push(n.ref);for(let n of e.refs??[])t.push(n.ref);for(let n of e.tail??[])t.push(n.ref);return t}function $t(e){return`Ref @${e.ref.startsWith(`@`)?e.ref.slice(1):e.ref} was minted from snapshot s${e.mintedGeneration} but the session's ref frame is now s${e.currentFrameEpoch} — re-run snapshot -i.`}function en(e){let{session:t,ref:n,mintedGeneration:r}=e;if(t&&x(t)===`expired`)return`The UI may have changed since these refs were issued, so they no longer represent current device state. Take a new snapshot before relying on or interacting with them.`;if(r!==void 0){let e=t?y(t)??0:0;if(r!==e)return $t({ref:n,mintedGeneration:r,currentFrameEpoch:e})}}export{Se as C,v as E,Te as S,we as T,V as _,qt as a,D as b,Bt as c,Q as d,_t as f,mt as g,Y as h,Kt as i,Ut as l,J as m,Xt as n,Gt as o,X as p,en as r,zt as s,Zt as t,Dt as u,st as v,De as w,T as x,j as y};
1
+ import{C as e,g as t,l as n,m as r,v as i}from"./sdk-contracts.js";import{l as a}from"./capture.js";import{r as o}from"./snapshot-capture-annotations.js";import{r as s}from"./snapshot-diagnostics.js";import{f as c}from"./android-input-ownership.js";import{c as l,d as u,v as d}from"./sdk-device.js";import{Bt as f,Ct as ee,Er as te,Lt as ne,ct as re,lt as ie,mt as ae,st as oe,ut as se,yt as ce}from"./sdk-batch.js";import{A as le,a as ue,d as de,k as fe,o as pe,t as me,w as he}from"./runtime.js";import{n as p}from"./success-text.js";import{i as m}from"./click-button.js";import{a as ge,r as h}from"./diagnostics.js";import{t as g}from"./timeouts.js";import"./diagnostics2.js";import"./retry.js";import{t as _e}from"./snapshot-state.js";import{i as _,n as ve}from"./request-runtime-binding.js";import{i as ye}from"./lease-context.js";import{t as be}from"./interactor-types.js";import{randomInt as xe}from"node:crypto";var v=class e{#e;constructor(e){this.#e=e}get state(){return this.#e.state}get scope(){return this.#e.scope}get tree(){return this.#e.tree}get generation(){return this.#e.generation}static expire(t){return t.#e.state===`expired`?t:new e({...t.#e,state:`expired`})}};const Se=new v({state:`active`,scope:`all`,tree:void 0,generation:void 0});function Ce(e){return new v({state:`active`,...e})}function we(e){return v.expire(e)}const Te=new WeakMap;function y(e){return e.refFrame??Se}function b(e){return y(e).generation??e.snapshotGeneration}function Ee(e){return y(e).tree}function De(e){Oe(e),e.refFrame=we(y(e)),e.snapshotScopeSource=void 0}function Oe(e){let t=ke(e)+1;return Te.set(e,t),t}function ke(e){return Te.get(e)??0}function Ae(e){x(e,`all`)}function je(e,t){x(e,t)}function x(e,t){e.refFrame=Ce({scope:t,tree:e.snapshot,generation:e.snapshotGeneration})}function S(e){return y(e).state}function C(e){return y(e).scope}function Me(e){let t=e.ref.startsWith(`@`)?e.ref.slice(1):e.ref;return{admission:Ne({session:e.session,refBody:t,mintedGeneration:e.mintedGeneration}),scope:C(e.session),currentGeneration:b(e.session)}}function Ne(e){let{session:t,refBody:n,mintedGeneration:r}=e;if(S(t)===`expired`)return{admitted:!1,reason:`ref_frame_expired`};if(r!==void 0&&r!==b(t))return{admitted:!1,reason:`ref_generation_mismatch`};let i=C(t);if(i!==`all`){if(r===void 0)return{admitted:!1,reason:`plain_ref_requires_complete_frame`};if(!i.has(n))return{admitted:!1,reason:`ref_not_issued`}}return{admitted:!0}}const Pe=[250,400,600];function w(e){return e===`press`||e===`click`||e===`back`||e===`open`}function Fe(e){return e.map(e=>[e.depth??0,e.type??``,e.label??``,e.value??``,e.identifier??``,e.enabled===!1?`disabled`:`enabled`,e.hittable===!0?`hittable`:`not-hittable`].join(`|`))}function Ie(e,t){return e<12?!1:t<=Math.floor(e*.2)}function Le(e,t,n){return n.interactiveOnly&&e.snapshot.nodes.length===0&&e.rawNodeCount!==void 0&&e.rawNodeCount>=12?`empty-interactive`:n.mode===`ref-refresh`?null:Ie(t.baselineCount,e.snapshot.nodes.length)?Re(e.snapshot)?null:`sharp-drop`:t.routeComparable&&w(t.action)&&ze(t.baselineSignatures,e.snapshot.nodes)?`stuck-route`:null}function Re(e){return e.nodes.some(e=>e.hittable===!0||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())}function ze(e,t){if(!e||e.length===0)return!1;let n=Math.max(e.length,t.length);if(n<12)return!1;let r=Fe(t),i=Math.min(e.length,r.length),a=0;for(let t=0;t<i;t+=1)e[t]===r[t]&&(a+=1);let o=Math.max(0,r.length-e.length),s=Math.max(0,e.length-r.length),c=Math.max(3,Math.floor(n*.15));return a>=Math.floor(n*.9)&&o<=c&&s<=c}async function Be(e){let t=e.window.markedAt+e.retry.retryBudgetMs,n=await e.capture(),r=e.classify(n),i=0;for(let a of e.retry.delaysMs){if(!r)break;let o=t-Date.now();if(o<=0)break;await g(Math.min(a,o)),n=await e.capture(),i+=1,r=e.classify(n)}r||e.onTrustworthyCapture?.();let a=i>0||r?{action:e.window.action,retryCount:i,staleAfterRetries:!!r,reason:r??void 0}:void 0;return{...n,annotations:{...n.annotations,...o({freshness:a})}}}function Ve(e,t,n=e.snapshot){if(e.device.platform!==`android`)return;let r=He(e,n),i=r?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:(r??n)?.nodes.length??0,baselineSignatures:i?Fe(r?.nodes??[]):void 0,routeComparable:i}}function He(e,t){if(t?.comparisonSafe===!0)return t;let n=e.lastComparisonSafeSnapshot;return!n||n.comparisonSafe!==!0?t:Date.now()-n.createdAt<=5e3?n:t}function T(e){if(!e||e.device.platform!==`android`)return;let t=e.androidSnapshotFreshness;if(t){if(Date.now()-t.markedAt>2500){delete e.androidSnapshotFreshness;return}return t}}function E(e){!e||e.device.platform!==`android`||delete e.androidSnapshotFreshness}async function Ue(e,t){return Be({capture:e.capture,classify:n=>Le({snapshot:n.snapshot,rawNodeCount:n.annotations.analysis?.rawNodeCount},t,{interactiveOnly:e.interactiveOnly,mode:e.androidFreshnessMode}),window:t,retry:{retryBudgetMs:1500,delaysMs:Pe},onTrustworthyCapture:()=>E(e.session)})}function We(e,t){return`${[e,...t].join(` `).trim()} produced no visible change: the tree still matches its pre-gesture state. Either the container is already at its edge, or it ignores synthesized scrolls — a raw drag moves such lists: swipe x1 y1 x2 y2 (start inside the list).`}function Ge(e,t){return t?{...e,warnings:[...e.warnings??[],We(t.action,t.positionals)]}:e}const Ke=`activity.launchConsole.launchArgs.clearAppState.verbose.iosXctestrunFile.iosXctestDerivedDataPath.iosXctestEnvDir.snapshotInteractiveOnly.snapshotPreferredBackend.snapshotDepth.snapshotScope.snapshotRaw.snapshotCustomActions.snapshotIncludeHiddenContentHints.count.intervalMs.delayMs.durationMs.holdMs.jitterPx.pixels.until.doubleTap.backMode.pauseMs.pattern`.split(`.`);function qe(e){return Object.fromEntries(Ke.map(t=>[t,e?.[t]]))}function D(e,t,n,r,i,o){return{requestId:i??ge().requestId,appBundleId:n,runnerLeaseContext:ye({meta:o}),logPath:e,traceLogPath:r,...qe(t),screenshotCaptureBackend:t?.maestro?.screenshotCaptureBackend,...a(t),clickButton:m(t)}}function Je(e){return e?.interactionOutcome?.retryOnNoChange===!0}function Ye(e){let{session:t,command:n,positionals:r,flags:i,preSnapshot:a}=e;if(!Je(i)||!L(t))return;let o=rt(n);if(!o||!ct(r))return;let s=M(a?.nodes??[]);s.length!==0&&(t.pendingInteractionOutcome={action:n,command:o,positionals:r,flags:j(i),markedAt:Date.now(),attemptsRemaining:2,preSignature:s})}function Xe(e){let t=e?.pendingInteractionOutcome;if(!(!e||!t)){if(!L(e)){O(e);return}if(Date.now()-t.markedAt>3e4){O(e);return}return t}}function O(e){e?.pendingInteractionOutcome&&(e.pendingInteractionOutcome=void 0)}async function k(e){let{pending:t,snapshot:n}=e,r=N(t.preSignature,M(n.nodes));if(r!==`unchanged`||t.attemptsRemaining<=0)return{retried:!1,change:r};let i=e.retryTap,a=i?R(t.positionals):void 0;if(!i||!a)return A(t,i?`unreadable-retry-point`:`device-runtime-unavailable`),{retried:!1,change:r};let o=Date.now();return--t.attemptsRemaining,await Ze(i,e)?(h({level:`info`,phase:`interaction_no_change_retry`,data:{action:t.action,attemptsRemaining:t.attemptsRemaining,durationMs:Date.now()-o}}),{retried:!0,change:r}):(A(t,`retry-tap-unavailable`),{retried:!1,change:r})}async function Ze(e,t){let{session:n,pending:r}=t,i=R(r.positionals);if(!i)return!1;try{return await e({device:n.device,point:i,context:{...D(t.logPath,r.flags,n.appBundleId,n.trace?.outPath),surface:n.surface}})}catch{return!1}}function A(e,t){h({level:`info`,phase:`interaction_no_change_retry_skipped`,data:{action:e.action,attemptsRemaining:e.attemptsRemaining,reason:t}})}function Qe(e){h({level:e.attempts>0?`info`:`debug`,phase:`interaction_settled`,data:{action:e.pending.action,change:e.change,attempts:e.attempts,durationMs:Date.now()-e.startedAt}})}function $e(e){h({level:`warn`,phase:`interaction_settle_timeout`,data:{action:e.pending.action,attempts:e.attempts,durationMs:Date.now()-e.startedAt}})}function j(e){if(!e?.interactionOutcome&&!e?.postGestureStabilization)return e;let{interactionOutcome:t,postGestureStabilization:n,...r}=e;return r}function M(e){let t=new Map,n=[],r=le(e);for(let i of e){let e=it(i,t,r);e&&n.push(e)}return n}function N(e,t){return e.length===0||t.length===0?`ambiguous`:F(e,t)?`unchanged`:`changed`}function P(e,t){return Math.abs(e.x-t.x)<=1&&Math.abs(e.y-t.y)<=1&&Math.abs(e.width-t.width)<=1&&Math.abs(e.height-t.height)<=1}function F(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.key!==i.key||!P(r,i))return!1}return!0}function et(e,t){let n=I(e),r=I(t);if(n.size===0||r.size===0)return`ambiguous`;let i=0,a=!1;for(let[e,t]of n){let n=r.get(e);if(!n){a=!0;continue}if(i+=1,!P(t,n))return`changed`}if(i===0)return`ambiguous`;let o=r.size>i;return a&&o?`changed`:`unchanged`}function I(e){let t=new Map;for(let n of e)!n.identity||!n.discriminating||t.has(n.identity)||t.set(n.identity,n);return t}function tt(e,t){let n=e.filter(e=>e.discriminating),r=t.filter(e=>e.discriminating);if(n.length===0||n.length!==r.length)return!1;let i=new Map(r.map(e=>[e.key,e]));for(let e of n){let t=i.get(e.key);if(!t||!P(e,t))return!1}return!0}function nt(e,t){let n=new Map(t.filter(e=>e.discriminating).map(e=>[e.key,e])),r=0,i=0,a=0;for(let t of e){if(!t.discriminating)continue;let e=n.get(t.key);if(!e){r+=1;continue}n.delete(t.key),a+=1,P(t,e)||(i+=1)}return{onlyInBaseline:r,onlyInCurrent:n.size,rectMismatched:i,shared:a}}function L(e){return u(e.device)}function R(e){let t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?{x:t,y:n}:void 0}function rt(e){if(e===`click`||e===`press`)return`press`}function it(e,t,n){if(!e.rect||!lt(e.rect)||ut(e))return;let r=st(e);if(!r)return;let i=t.get(r)??0;t.set(r,i+1);let a=at(e);return{key:`${r}|#${i}`,...a?{identity:a}:{},x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height),discriminating:!ot(e,n)}}function at(e){let t=[e.identifier,e.label,e.value].map(e=>typeof e==`string`?e.trim():``).join(`|`);if(t.replaceAll(`|`,``))return`${t}|${e.type??``}`}function ot(e,t){return te(e)||e.ref!==void 0&&t.has(e.ref)}function st(e){let t=[e.identifier,e.label,e.value,e.type,e.role,e.enabled===!1?`disabled`:`enabled`,e.selected===!0?`selected`:`unselected`,e.hittable===!0?`hittable`:`not-hittable`].map(e=>typeof e==`string`?e.trim():``).join(`|`);return t.replaceAll(`|`,``)?t:void 0}function ct(e){return e.length===2&&e.every(e=>Number.isFinite(Number(e)))}function lt(e){return[e.x,e.y,e.width,e.height].every(e=>Number.isFinite(e))&&e.width>0&&e.height>0}function ut(e){return`${e.label??``} ${e.identifier??``}`.toLowerCase().includes(`scroll bar`)}const z=3500;function dt(e){let{needsBaselineDistrust:t,baselineSignature:n,quietSignature:r,elapsedMs:i,distrustCapMs:a}=e;return!t||!n?.length||e.classifyBaselineEvidence(n,r)!==`unchanged`?`trust`:i<a?`distrust`:`accept-stale`}async function ft(e){let{pending:t,needsBaselineDistrust:n,hooks:r}=e,i=Date.now(),a=1,o=await B(r,e.initial),s=t.baselineSignature,c=t.baselineBackend,l=!1,u=1500;for(;a<2||Date.now()-i<u;){await g(200),a+=1;let e=await B(r);if(r.signaturesStable(o.signature,e.signature)){let d=Date.now()-i;if(s&&c!==e.backend){h({level:`debug`,phase:`post_gesture_snapshot_baseline_rebased`,data:{action:t.action,from:c,to:e.backend,attempts:a}}),s=e.signature,c=e.backend,l=!0,o=e;continue}let f=dt({needsBaselineDistrust:n,baselineSignature:s,quietSignature:e.signature,elapsedMs:d,distrustCapMs:z,classifyBaselineEvidence:r.classifyBaselineEvidence});if(f===`distrust`){u=z,o=e;continue}return pt(f,t.action,a,d),mt(f,t,e,r,l)}o=e}return h({level:`warn`,phase:`post_gesture_snapshot_stabilization_timeout`,data:{action:t.action,attempts:a,durationMs:Date.now()-i}}),{value:o.value}}async function B(e,t){let n=t??await e.capture();return{value:n,...e.readSurface(n)}}function pt(e,t,n,r){if(e===`accept-stale`){h({level:`warn`,phase:`post_gesture_snapshot_stale_accept`,data:{action:t,attempts:n,durationMs:r,matchedPreGestureBaseline:!0}});return}h({level:n>2?`info`:`debug`,phase:`post_gesture_snapshot_stabilized`,data:{action:t,attempts:n,durationMs:r}})}function mt(e,t,n,r,i){if(e!==`accept-stale`)return{value:n.value};let a=t.baselineSignature;return a!==void 0&&r.surfacesIdentical(a,n.signature)?{value:n.value,gestureNoEffect:{action:t.action,positionals:t.positionals}}:(h({level:`info`,phase:`post_gesture_no_effect_vetoed`,data:{action:t.action,backend:n.backend,...i?{reason:`baseline_rebased`}:{reason:`surface_divergence`,...a===void 0?{}:r.summarizeDivergence(a,n.signature)}}}),{value:n.value})}function ht(e){let{session:t,command:n,action:r=n,positionals:i,flags:a,scheduleOutcomeRetry:o=!1,androidFreshnessBaseline:s}=e;o&&Ye({session:t,command:n,positionals:i,flags:a,preSnapshot:t.snapshot}),w(r)&&Ve(t,r,s??t.snapshot),gt(t,r,i,a)}function gt(e,t,n=[],r){if(!G(e.device)||!St(t,n,r))return;let i=K(e.device)?M(e.snapshot?.nodes??[]):void 0;e.postGestureStabilization={action:t,positionals:n,markedAt:Date.now(),...i?.length?{baselineSignature:i,baselineBackend:W(e.snapshot)}:{}}}function _t(e){e?.postGestureStabilization&&(e.postGestureStabilization=void 0)}function V(e){return!!e?.postGestureStabilization}async function vt(e){let t=Xe(e.session);if(t&&e.session)return await yt({...e,session:e.session},t);if(u(e.device)&&e.session&&V(e.session))return await bt({...e,session:e.session});let n=T(e.session);if(n&&e.device.platform===`android`){let t=await Ue(e,n);return{snapshot:t.snapshot,...t.annotations}}}async function yt(e,t){let n=e.session,r=Date.now(),i=0,a=await H(e,t,await U(e)),o=await k({session:n,pending:t,logPath:e.logPath,snapshot:a.snapshot,retryTap:e.retryTap});for(;o.retried;)i+=1,a=await H(e,t,await U(e)),o=await k({session:n,pending:t,logPath:e.logPath,snapshot:a.snapshot,retryTap:e.retryTap});O(n);let s=await xt({session:n,initial:a,capture:async()=>await U(e),readSnapshot:e=>e.snapshot});return a=s.value,o.change!==`ambiguous`&&a.annotations.freshness?.staleAfterRetries!==!0&&E(n),o.change===`unchanged`?$e({pending:t,attempts:i,startedAt:r}):Qe({pending:t,change:o.change,attempts:i,startedAt:r}),{snapshot:a.snapshot,...Ge(a.annotations,s.gestureNoEffect)}}async function H(e,t,n){let r=n;return N(t.preSignature,M(r.snapshot.nodes))===`unchanged`?(await g(500),r=await U(e),r):r}async function bt(e){let t=await xt({session:e.session,capture:async()=>await U(e),readSnapshot:e=>e.snapshot}),n=t.value;return{snapshot:n.snapshot,...Ge(n.annotations,t.gestureNoEffect)}}async function U(e){let t=T(e.session);return t&&e.device.platform===`android`?await Ue(e,t):await e.capture()}async function xt(e){let{session:t,capture:n,readSnapshot:r}=e,i=t?.postGestureStabilization;if(!t||!G(t.device)||!i)return{value:e.initial??await n()};let a=await ft({pending:{action:i.action,positionals:i.positionals??[],baselineSignature:i.baselineSignature,baselineBackend:i.baselineBackend},needsBaselineDistrust:K(t.device),initial:e.initial,hooks:{capture:n,readSurface:e=>{let t=r(e);return{signature:M(t.nodes),backend:W(t)}},signaturesStable:F,classifyBaselineEvidence:et,surfacesIdentical:tt,summarizeDivergence:nt}});return _t(t),a}function W(e){return e?.comparisonKey??e?.snapshotQuality?.backend}function St(e,t,n){return n?.postGestureStabilization===!1?!1:n?.postGestureStabilization===!0||e===`swipe`||e===`scroll`||e===`gesture`&&t[0]===`swipe`}function G(e){return u(e)}function K(e){return l(e.platform)}let q;async function J(){if(q)return q;let{createAppleSessionObservation:e}=await import(`./session-observation.js`),{listLocalDeviceInventory:t,shouldPropagateDeviceInventoryProbeError:n}=await import(`./device-inventory-context.js`).then(e=>e.t);return q??=e({listLocalDevices:t,shouldPropagateProbeError:n}),q}const Ct=Object.freeze({async observeRunnerSession(e){return(await J()).observeRunnerSession(e)},async resolveSoleForegroundApp(e){return(await J()).resolveSoleForegroundApp(e)}});async function wt(e,t,n,r){let{queryAppleRunnerSelector:i}=await import(`./runner-operations-facade.js`);return await i(e,t,n,r)}async function Y(e){let t=await Dt(e.inspectFacts)(e.device);for(let n of e.required){let r=t.operations[n];if(!r.available)return{type:`response`,response:e.unavailableResponse?e.unavailableResponse(r):_(`UNSUPPORTED_OPERATION`,`${e.command} is not supported on this device`,void 0,r.hint?{hint:r.hint}:void 0)}}return{type:`admitted`,bind:Ot(e.bindDevice)}}async function Tt(e){let t=await Y({...e,required:e.use.required});if(t.type===`response`)return t;let n=await t.bind(e.device,e.use);return e.readiness!==void 0&&await ve(n,e.readiness),{type:`runtime`,runtime:n}}async function Et(e,t){let n=await Tt(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:async({dispatchContext:e})=>await t(r,e)}}function Dt(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`,{reason:`runtime-gateway-missing`})}function Ot(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime binding is unavailable.`,{reason:`runtime-gateway-missing`})}function kt(e){let{flags:t,logPath:r,meta:a,session:o,snapshotScope:s}=e,{appBundleId:c,trace:l,surface:u}=o??{},d=e.context??D(r??``,t,c,l?.outPath,a?.requestId,a);return{options:{appBundleId:c,...i(t,n),scope:s,includeRects:e.includeRects,surface:u},execution:X(d),...e.signal===void 0?{}:{signal:e.signal}}}function X(e){return{requestId:e.requestId,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}function At(e){let t=he(e);return{...t,capture:me(t),selectors:pe(t),interactions:ue(t)}}async function jt(e){let{getInteractor:t}=await import(`./interactors.js`),n=await(await t(e.device,e.runnerContext)).snapshot(e.options);if(!(`stage`in n))return n;let{presentIosSnapshotAcquisition:r}=await import(`./ios-snapshot-runtime.js`);return await r(n,e.options)}function Mt(e){let t=e?e.textEntryReadiness:void 0,n=Lt(t)?{textEntryReadiness:t}:{},r=Nt(e);return r?{...n,...r}:n}function Nt(e){if(!Pt(e))return null;let t=Ft(e.target);return t?{verification:`unconfirmed`,requested:e.requested,before:e.before,after:e.after,target:t}:null}function Pt(e){return!!(e&&e.verification===`unconfirmed`&&typeof e.requested==`string`&&Z(e.before)&&Z(e.after))}function Ft(e){if(!Q(e)||!It(e))return null;let t=Rt(e.rect);return t?{resourceId:e.resourceId,className:e.className,packageName:e.packageName,rect:t}:null}function It(e){return Z(e.resourceId)&&Z(e.className)&&Z(e.packageName)}function Lt(e){return typeof e==`string`&&be.includes(e)}function Z(e){return e===null||typeof e==`string`}function Rt(e){return!Q(e)||![e.x,e.y,e.width,e.height].every(e=>typeof e==`number`)?null:e}function Q(e){return!!e&&typeof e==`object`}async function zt(e){let t={device:e.device,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice},n=ne(e.command,e.requiresCapture),r=await Y({command:e.command,required:n.use.required,...e.unavailableResponse?{unavailableResponse:e.unavailableResponse}:{},...t});if(r.type===`response`)return{ok:!1,response:r.response};let i=r.bind;switch(n.kind){case`tap-point`:return{ok:!0,runtime:{kind:`tap`,captured:!1,runtime:await i(e.device,f)}};case`captured-tap`:return{ok:!0,runtime:{kind:`tap`,captured:!0,runtime:await i(e.device,se)}};case`long-press-point`:return{ok:!0,runtime:{kind:`long-press`,captured:!1,runtime:await i(e.device,ee)}};case`captured-long-press`:return{ok:!0,runtime:{kind:`long-press`,captured:!0,runtime:await i(e.device,ie)}};case`hover-point`:return{ok:!0,runtime:{kind:`hover`,captured:!1,runtime:await i(e.device,ce)}};case`captured-hover`:return{ok:!0,runtime:{kind:`hover`,captured:!0,runtime:await i(e.device,re)}};case`fill-point`:return{ok:!0,runtime:{kind:`fill`,captured:!1,runtime:await i(e.device,ae)}};case`captured-fill`:return{ok:!0,runtime:{kind:`fill`,captured:!0,runtime:await i(e.device,oe)}}}}function Bt(e,t){let n={execution:X(t),appBundleId:t.appBundleId},r=e.captured?Kt(e.runtime):void 0;switch(e.kind){case`tap`:return Vt(e,t,n,r);case`long-press`:return Ht(e,n,r);case`hover`:return Ut(e,n,r);case`fill`:return Wt(e,t,n,r)}}function Vt(e,t,n,r){let i=e.captured?e.runtime.operations.tapRef:void 0,a=e.captured?e.runtime.operations.tapElementSelector:void 0;return Object.freeze({captureSnapshot:r,tapPoint:async(r,i={})=>{let a=qt(i,t),o=await e.runtime.operations.tapPoint({point:r,options:a,...n});return{x:r.x,y:r.y,count:a.count,intervalMs:a.intervalMs,holdMs:a.holdMs,jitterPx:a.jitterPx,doubleTap:a.doubleTap,...a.button===`primary`?{}:{button:a.button},...o??{},...p(Xt(r,a.button))}},tapRef:i?async e=>await i({ref:e,...n}):void 0,tapElementSelector:e.captured&&a?async t=>{let r=await e.runtime.operations.tapElementSelector?.({selector:t,...n}),i=r?.maestroNonHittableCoordinateFallbackUsed===!0;return{selector:t.raw,...r??{},...p(i?`tapped via non-hittable coordinate fallback`:`Tapped ${t.raw}`)}}:void 0})}function Ht(e,t,n){return Object.freeze({captureSnapshot:n,longPressPoint:async(n,r)=>{let i=await e.runtime.operations.longPressPoint({point:n,durationMs:r,...t});return{x:n.x,y:n.y,durationMs:r,...i??{},...p(`Long pressed (${n.x}, ${n.y})`)}}})}function Ut(e,t,n){let r=e.captured?e.runtime.operations.hoverRef:void 0;return Object.freeze({captureSnapshot:n,hoverPoint:async n=>{let r=await e.runtime.operations.hoverPoint({point:n,...t});return{x:n.x,y:n.y,...r??{},...p(`Hovered (${n.x}, ${n.y})`)}},hoverRef:r?async e=>await r({ref:e,...t}):void 0})}function Wt(e,t,n,r){let i=e.captured?e.runtime.operations.fillRef:void 0,a=e=>fe(e??t.delayMs??0,`delay-ms`,0,1e4);return Object.freeze({captureSnapshot:r,fillPoint:async(t,r,i={})=>{let o=a(i.delayMs),s=await e.runtime.operations.fillPoint({point:t,text:r,delayMs:o,allowNonHittableCoordinateFallback:i.allowNonHittableCoordinateFallback===!0,...n});return{x:t.x,y:t.y,text:r,delayMs:o,...Gt(s)?{maestroNonHittableCoordinateFallbackUsed:!0}:{},...Mt(s),...p(`Filled ${Array.from(r).length} chars`)}},fillRef:i?async(e,t,r={})=>await i({ref:e,text:t,delayMs:a(r.delayMs),...n}):void 0})}function Gt(e){return typeof e==`object`&&!!e&&`maestroNonHittableCoordinateFallbackUsed`in e&&e.maestroNonHittableCoordinateFallbackUsed===!0}function Kt(e){return async t=>await e.operations.captureSnapshot(t)}function qt(e,t){let n=Jt(e,t);return Yt(n),{button:e.button??m(t),...n,surface:e.surface??t.surface}}function Jt(e,t){return{count:$(e.count,t.count,1,`count`,1,200),intervalMs:$(e.intervalMs,t.intervalMs,0,`interval-ms`,0,1e4),holdMs:$(e.holdMs,t.holdMs,0,`hold-ms`,0,1e4),jitterPx:$(e.jitterPx,t.jitterPx,0,`jitter-px`,0,100),doubleTap:e.doubleTap??t.doubleTap??!1}}function $(e,t,n,r,i,a){return fe(e??t??n,r,i,a)}function Yt(t){if(t.doubleTap&&t.holdMs>0)throw new e(`INVALID_ARGS`,`double-tap cannot be combined with hold-ms`);if(t.doubleTap&&t.jitterPx>0)throw new e(`INVALID_ARGS`,`double-tap cannot be combined with jitter-px`)}function Xt(e,t){return t===`primary`?`Pressed (${e.x}, ${e.y})`:`${t===`secondary`?`Right`:`Middle`} clicked (${e.x}, ${e.y})`}function Zt(e){let{inspectFacts:t,bindDevice:n}=e;if(!t||!n)return;let r=new Map;return async({device:e,point:i,context:a})=>{let o=r.get(e.id);o||(o=zt({device:e,command:`press`,requiresCapture:!1,inspectFacts:t,bindDevice:n}),r.set(e.id,o));let s=await o;if(!s.ok)return!1;let c=Bt(s.runtime,a);return c.tapPoint?(await c.tapPoint(i),!0):!1}}async function Qt(e){let t=await vt({session:e.session,device:e.device,logPath:e.logPath,interactiveOnly:e.flags?.snapshotInteractiveOnly===!0,androidFreshnessMode:e.androidFreshnessMode,capture:()=>en(e),retryTap:Zt(e)});if(t)return t;let n=await en(e);return E(e.session),{snapshot:n.snapshot,...n.annotations}}async function $t(e){if(e.captureData)return await e.captureData();let{device:t,session:r,logPath:a}=e,o=D(a,tn(e),r?.appBundleId,r?.trace?.outPath);return await jt({device:t,runnerContext:{requestId:o.requestId,signal:e.signal,appBundleId:o.appBundleId,verbose:o.verbose,logPath:o.logPath,traceLogPath:o.traceLogPath,iosXctestrunFile:o.iosXctestrunFile,iosXctestDerivedDataPath:o.iosXctestDerivedDataPath,iosXctestEnvDir:o.iosXctestEnvDir,runnerLeaseContext:o.runnerLeaseContext},options:{appBundleId:o.appBundleId,signal:e.signal,...i(o,n),includeRects:e.includeRects,surface:r?.surface}})}async function en(e){let t=Date.now(),n=await $t(e);s(e.session,{durationMs:Date.now()-t,backend:n.backend,platform:d(e.device)});let r=o(n),i=c(n,_e(n,tn(e)));return r.androidSnapshot?.systemSurfaceOnly===!0&&(i.systemSurfaceOnly=!0),{data:n,snapshot:i,annotations:r}}function tn(e){return e.snapshotScope===void 0?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function nn(e,n){if(!e||!e.trim().startsWith(`@`))return{ok:!0,scope:e};if(!n?.snapshot)return _(`INVALID_ARGS`,`Ref scope requires an existing snapshot in session.`);let i=t(e.trim());if(!i)return _(`INVALID_ARGS`,`Invalid ref scope: ${e}`);let a=[n.snapshot,...n.snapshotScopeSource?[n.snapshotScopeSource]:[]],o;for(let e of a){let t=r(e.nodes,i);if(o=t?de(t,e.nodes):void 0,o)break}return o?{ok:!0,scope:o}:_(`COMMAND_FAILED`,`Ref ${e} not found or has no label`)}function rn(e,t,n={}){if(!e)return;let r=Ee(e);return{name:t,appBundleId:e.appBundleId,appName:e.appName,...n.includeSnapshot===!0?{snapshot:e.snapshot,...r&&n.omitRefFrameSnapshot!==!0?{refFrameSnapshot:r}:{}}:{},metadata:{surface:e.surface,...n.metadata??{}}}}function an(e){return{get:t=>t===e.sessionName?rn(e.getSession(),e.sessionName,e.recordOptions):void 0,set:t=>{if(t.name!==e.sessionName){h({level:`warn`,phase:`runtime_session_write_skipped`,data:{expected:e.sessionName,received:t.name}});return}e.setRecord(t)}}}function on(e,t){e.snapshot!==t&&(e.snapshotGeneration=cn(e.snapshotGeneration)),e.snapshot=t,e.snapshotScopeSource=void 0,t.comparisonSafe===!0&&(e.lastComparisonSafeSnapshot=t)}function sn(e,t){e.snapshotScopeSource=t.scopeSource,e.snapshotGeneration=t.keptCurrentSnapshot?t.previousGeneration:cn(t.previousGeneration)}function cn(e){return e===void 0?xe(1e5,1e6):e+1}function ln(e){let t=e.startsWith(`@`)?e.slice(1):e,n=t.indexOf(`~`);return n===-1?t:t.slice(0,n)}function un(e,t){let n=new Set;for(let e of t){let t=ln(e);t.length>0&&n.add(t)}n.size!==0&&je(e,n)}function dn(e,t){if(t?.diff)return un(e,fn(t)),e.snapshotGeneration}function fn(e){let t=[];for(let n of e.diff?.lines??[])n.ref&&t.push(n.ref);for(let n of e.refs??[])t.push(n.ref);for(let n of e.tail??[])t.push(n.ref);return t}function pn(e){return`Ref @${e.ref.startsWith(`@`)?e.ref.slice(1):e.ref} was minted from snapshot s${e.mintedGeneration} but the session's ref frame is now s${e.currentFrameEpoch} — re-run snapshot -i.`}function mn(e){let{session:t,ref:n,mintedGeneration:r}=e;if(t&&S(t)===`expired`)return`The UI may have changed since these refs were issued, so they no longer represent current device state. Take a new snapshot before relying on or interacting with them.`;if(r!==void 0){let e=t?b(t)??0:0;if(r!==e)return pn({ref:n,mintedGeneration:r,currentFrameEpoch:e})}}export{D as C,Me as D,De as E,ke as O,j as S,Ae as T,Et as _,sn as a,V as b,$t as c,zt as d,At as f,Tt as g,Y as h,on as i,y as k,nn as l,X as m,un as n,an as o,kt as p,mn as r,Qt as s,dn as t,Bt as u,Ct as v,T as w,ht as x,wt as y};
@@ -1,4 +1,4 @@
1
- import{F as e,y as t}from"./sdk-contracts.js";import{n}from"./capture.js";import{g as r}from"./sdk-batch-runner.js";import{i,r as a,t as o,v as s}from"./sdk-device.js";import{Jn as c,b as l,f as ee,qn as te,rn as u,tn as ne}from"./sdk-batch.js";import{n as re,t as d}from"./back-mode.js";import{r as ie}from"./scroll-gesture.js";import{_ as f,c as ae,d as oe,g as se,h as ce,i as le,l as ue,m as de,o as fe,p,s as pe,u as m,y as me}from"./script.js";import{A as he,C as ge,D as _e,E as ve,M as ye,N as be,O as xe,S as Se,T as Ce,_ as h,a as we,b as Te,c as Ee,i as De,n as Oe,o as ke,r as Ae,t as je,u as Me,v as Ne,w as Pe,x as Fe,y as Ie}from"./parameterized-recorded-fill.js";import{n as g,t as Le}from"./catalog.js";import{t as Re}from"./session.js";import{n as ze}from"./success-text.js";import{t as Be}from"./click-button.js";import"./device.js";import{t as _}from"./device-rotation.js";import{a as v,r as y}from"./diagnostics.js";import{D as Ve}from"./owner-identity.js";import"./file.js";import{t as He}from"./tv-remote.js";import"./diagnostics2.js";import{n as Ue,r as We}from"./session-repair-tombstone.js";import{n as Ge,r as b,t as x}from"./session-paths.js";import{t as Ke}from"./keyboard-actions.js";import S from"node:path";import C from"node:fs";import{createHash as qe}from"node:crypto";import{StringDecoder as Je}from"node:string_decoder";function Ye(e,t={}){let n=[e.command];return e.command===`snapshot`?oe(n,e):e.command===`open`?le(n,e):e.command===`runtime`?ae(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?pe(n,e):e.command===`screenshot`?ue(n,e):fe(n,e),n.join(` `)}function Xe(e){return e.targetEvidences?[te(e.targetEvidences)]:e.targetEvidence?[c(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??h}function Ze(e,t){let n=w(e),r=typeof t.saveScript==`string`?x(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Ie(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function Qe(e){e.scriptPublication=Fe(w(e))}function $e(e){e.scriptPublication=Ce(w(e))}function et(e,t){e.scriptPublication=ve(w(e),t)}function tt(e){e.scriptPublication=Ne(w(e))}function nt(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function rt(e){return w(e).kind===`repair`}function it(e){return Pe(w(e))}function T(e){return _e(w(e))}function at(e){return xe(w(e))}function ot(e,t){if(t.flags?.noRecord||gt(e,t))return;t.flags&&Ee(e,t.flags);let n=ct(t),r=dt(e,lt(t,n));n&&ut(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:vt(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),y({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function st(e,t,n,r,i,a){t&&e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function ct(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=be(e.flags.recordAs),n=ye(t);return{literal:ke({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function lt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:pt(e.positionals,r),result:je(e.result,n,r),targetEvidence:Oe(e.targetEvidence,n,r)}}function ut(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function dt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=Ae(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?ft(t.targetEvidence,n):E(t.targetEvidence,n),a=t.targetEvidences?{source:E(t.targetEvidences.source,n),destination:E(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function ft(e,t){return e&&(we(e,t)?void 0:e)}function E(e,t){return!e||!we(e,t)?e:{...De(e,t),verification:`unverifiable`}}function pt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const mt=new Set([`snapshot`,`get`,`is`,`find`]);function ht(e){return e.internal?.replayPlanStep!==!0&&mt.has(e.command)}function gt(e,t){return!t.interactiveObservation||T(e)===void 0?!1:t.flags?.record!==!0}const _t=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,`snapshotCustomActions`,...n,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function vt(e){if(!e)return{};let t={};for(let n of _t)e[n]!==void 0&&(t[n]=e[n]);return t}function yt(e){let n=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new t(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new t(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[t,n]of e.entries())l({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(Tt))throw new t(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function bt(e){for(let n of e){if(xt(n)){St(n);continue}let e=Et(n),r=e??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&l(n)===`mutates-app`)throw new t(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=e;if(!(!i||!u(i)||n.targetEvidence))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function xt(e){return Ct(e)!==void 0}function St(e){let n=Ct(e);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!u(n))&&!e.targetEvidences)throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Ct(e){return e.command===`gesture`?me(e.positionals):void 0}function wt(e,n){if(e instanceof t){if(e.details?.reason===`script_target_exists`)return new t(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=e.details?.retriable===!0;return new t(e.code,e.message,{...e.details,retriable:n,hint:e.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Tt(e){if(e.command!==`wait`)return!1;let t=ne(e.positionals);return t?.kind!==`selector`||!u(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Et(e){if(e.command===`get`)return e.positionals[1];if(se(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Dt(t)&&Dt(n)?void 0:t}}function Dt(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Ot(e){let t=e.scriptPublication??h;return t.kind===`repair`?t.status===`committed`||!ge(t):!1}function kt(e){return!Se(e.scriptPublication??h)||Ot(e)}var At=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=rt(e),r=t?.publication===`active`,i;try{if(kt(e))return{written:!1};let a=jt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=S.dirname(i);return C.existsSync(o)||C.mkdirSync(o,{recursive:!0}),Pt({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Te(e.scriptPublication??h)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Mt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=he(e.scriptPublication??h);if(t)return x(t);let n=b(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${n}-${r}.ad`)}};function jt(e,t){let n=Ft(e,{strictPortableRefs:t.activePublication});return t.activePublication&&yt(n),{script:Gt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Mt(e){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=e;if(y({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:Nt(r,i)};if(o)return{written:!1,error:wt(r,i)};if(r instanceof t)throw r;return{written:!1}}function Nt(e,n){if(e instanceof t)return e;let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function Pt(e){let{scriptPath:n,script:r,force:i}=e;try{Ve({destination:n,contents:r,publish:i?`replace`:`link-exclusive`})}catch(e){throw e.code===`EEXIST`?new t(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):e}}function Ft(e,t={}){let n=T(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=Rt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&It(n);let o=Wt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&bt(a),a}function It(e){let n=e.command===`gesture`?me(e.positionals??[]):void 0;if(n){Lt(n);return}if(!D(e.command))return;let r=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Lt(e){let n=[e.source,e.destination].find(e=>e.startsWith(`@`));if(n)throw new t(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Rt(e){let t=zt(e);if(!(!t||!D(e.command)))return ce(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Vt(e,t):e.command===`fill`?Bt(e,t):Ht(e,t)}function zt(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function D(e){return se(e)||e===`fill`||e===`get`}function Bt(e,t){let n=ke(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Vt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Ut(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Ht(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Ut(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Wt(e,t){if(!D(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function Gt(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${s(e.device)} device=${de(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Xe(e)),r.push(Kt(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
- `)}\n`}function Kt(e){return qt([e.command],e)||Ye(e)}function qt(e,t){if(ce(t.command))return Jt(e,t);if(t.command===`fill`)return Yt(e,t);if(t.command===`get`)return Xt(e,t)}function Jt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(p(f(n))),O(e,t),m(e,t),e.join(` `);if(t.positionals.length===1)return e.push(p(n)),m(e,t),e.join(` `)}}function Yt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(p(f(n))),O(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(p(r)),m(e,t),e.join(` `)}function Xt(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(p(n)),e.push(p(f(r))),r.startsWith(`@`)&&O(e,t),e.join(` `)}function O(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(p(n))}const Zt=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Qt={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function $t(e,t){let n=t??{};switch(e.command){case g.devices:return en(n.devices);case g.apps:return tn(n.apps,e.flags?.appsFilter);case g.boot:return nn(`Booted`,n,!0);case g.shutdown:return nn(`Shut down`,n,!1);case g.install:return k(`Installed`,n);case g.reinstall:return k(`Reinstalled`,n);case g.screenshot:return rn(e,n);default:return{}}}function en(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=on(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:hn(`Found ${t.length} ${gn(`device`,t.length)}`,i.map(e=>pn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function tn(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=M(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:hn(`Found ${n.length} ${gn(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function nn(e,t,n){let r=sn(t);if(!r)return{};let i={device:r,...fn(t),booted:n};return{summary:`${e} ${pn(i,!1)}`,details:i}}function k(e,t){let n=M(t.appName),r=M(t.bundleId),i=A(t,[`packageName`,`package`]),a=M(t.platform),o=M(t.launchTarget),s=A(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=mn(n,s);if(!c)return{};let l={};return j(l,`appName`,n),j(l,`bundleId`,r),j(l,`packageName`,i),j(l,`platform`,a),o!==s&&j(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function rn(e,t){let n=an(e,t);return n?{details:{requestedFileName:n}}:{}}function an(e,t){let n=R(e.meta?.clientArtifactPaths?.path)??R(t.path);if(n)return L(n)}function on(e){if(!r(e))return;let t=sn(e);if(t)return{name:t,...fn(e)}}function sn(e){let t=A(e,[`name`,`deviceName`,`device`]);return!t||!cn(e,t)?t:un(e)}function cn(e,t){let n=ln(t);return Zt.some(t=>{let r=M(e[t]);return r!==void 0&&ln(r)===n})}function ln(e){return e.toLowerCase()}function un(e){let t=M(e.appleOs),n=M(e.platform),r=M(e.kind),i=dn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function dn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Qt,n)))return Qt[n]}function fn(e){let t=M(e.platform),n=M(e.appleOs),r=M(e.kind),i=M(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function pn(e,t){let n=M(e.name)??M(e.device)??`device`,r=M(e.platform),i=M(e.appleOs),a=[r,i===r?void 0:i,M(e.kind),M(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function mn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function A(e,t){for(let n of t){let t=M(e[n]);if(t)return t}}function j(e,t,n){n&&(e[t]=n)}function hn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function gn(e,t){return t===1?e:`${e}s`}function M(e){let t=R(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function N(e){return M(e)}function P(e){return typeof e==`boolean`?e:void 0}function F(e,t){let n=N(e);return n&&t.includes(n)?n:void 0}function I(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function L(e){let t=R(e);return t?M(t.split(/[\\/]/).at(-1)):void 0}function R(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function z(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const _n=[`up`,`down`,`left`,`right`],vn=[`top`,`bottom`];function yn(e){return`${e.command===g.reinstall?`Reinstalled`:`Installed`} ${Cn(e.result??{})??`app`}`}function bn(e){let t=e.result??{};switch(e.command){case g.scroll:return Tn(t);case g.screenshot:return On(t);case g.home:return`Went home`;case g.back:return An(t);case g.appSwitcher:return`Opened app switcher`;case g.orientation:return jn(t);case g.viewport:return Mn(t);case g.clipboard:return Nn(t);case g.keyboard:return Pn(t);case g.tvRemote:return Ln(t);case g.gesture:return Rn(t);case g.swipe:return zn(t);case g.trace:return Vn(`trace`,e);case g.record:return Vn(`recording`,e);default:return}}function xn(e){let t=e.result??{};switch(e.command){case g.scroll:return I({direction:F(t.direction,_n),edge:F(t.edge,vn),passes:z(t.passes),amount:z(t.amount),pixels:z(t.pixels),durationMs:z(t.durationMs),x1:z(t.x1),y1:z(t.y1),x2:z(t.x2),y2:z(t.y2)});case g.screenshot:return I({requestedFileName:kn(t)});case g.back:return I({mode:F(t.mode,d)});case g.orientation:return I({orientation:F(t.orientation,_)});case g.viewport:return I({width:z(t.width),height:z(t.height)});case g.clipboard:return I({action:F(t.action,[`read`,`write`])});case g.keyboard:return In(t);case g.tvRemote:return I({button:F(t.button,He),durationMs:z(t.durationMs)});case g.gesture:case g.swipe:return Bn(t);case g.trace:case g.record:return I({action:F(t.action,[`start`,`stop`]),fileName:Un(e),showTouches:P(t.showTouches)});default:return{}}}function Sn(e,t){if(e.command!==g.screenshot)return t;let n=an(e,t);return n?{...t,requestedFileName:n}:t}function Cn(e){let t=N(e.appName),n=Wn(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??wn(e)}function wn(e){let t=N(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Tn(e){let t=F(e.direction,_n),n=F(e.edge,vn),r=z(e.passes);return n?En(n,r):t?Dn(t,e):`Scrolled`}function En(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Dn(e,t){let n=z(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=z(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function On(e){let t=kn(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function kn(e){return L(e.requestedFileName)??L(e.path)}function An(e){return F(e.mode,d)===`system`?`Went back using system navigation`:`Went back`}function jn(e){let t=F(e.orientation,_);return t?`Rotated to ${t}`:`Changed orientation`}function Mn(e){let t=z(e.width),n=z(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function Nn(e){let t=F(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function Pn(e){let t=R(e.action);if(!t||!Ke(t))return`Used keyboard`;if(t===`dismiss`)return Fn(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=P(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function Fn(e){return P(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function In(e){let t=R(e.action);return I({action:t&&Ke(t)?t:void 0,platform:F(e.platform,[`ios`,`android`]),visible:P(e.visible),wasVisible:P(e.wasVisible),dismissed:P(e.dismissed),attempts:z(e.attempts),mechanism:F(e.mechanism,[`dismissKey`])})}function Ln(e){let t=F(e.button,He);return t?`Pressed TV remote ${t}`:`Used TV remote`}function Rn(e){let t=F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function zn(e){let t=z(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Bn(e){return I({kind:F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:z(e.durationMs),pointerCount:z(e.pointerCount),x1:z(e.x1),y1:z(e.y1),x2:z(e.x2),y2:z(e.y2),count:z(e.count),pauseMs:z(e.pauseMs),pattern:F(e.pattern,[`one-way`,`ping-pong`]),scale:z(e.scale)})}function Vn(e,t){let n=Hn(e,F(t.result?.action,[`start`,`stop`])),r=Un(t);return r?`${n} ${r}`:n}function Hn(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function Un(e){let t=e.result??{};return L(t.requestedFileName)??L(t.outPath)??L(t.path)??L(e.positionals[1])}function Wn(e,t){for(let n of t){let t=N(e[n]);if(t)return t}}function Gn(e){switch(e.command){case g.open:return`Opened ${B(e)??`session`}`;case g.close:return`Closed ${N(e.result?.session)??`session`}`;case g.click:case g.press:return`Tapped ${B(e)??`target`}`;case g.longPress:return`Long pressed ${B(e)??`target`}`;case g.hover:return`Hovered ${B(e)??`target`}`;case g.fill:return`Filled ${B(e)??`target`}`;case g.type:return`Typed text`;case g.install:case g.reinstall:case Le.installSource:return yn(e);default:return bn(e)??`Ran ${e.command}`}}function Kn(e){return I({command:e.command,positionals:tr(e),flags:pr(e),...qn(e),...Jn(e),...Yn(e),...xn(e)})}function qn(e){if(!Xn(e.command))return{};let t=e.result??{};return I({ref:G(t),targetLabel:B(e),selectorChainLength:lr(t.selectorChain)?.length,x:z(t.x),y:z(t.y),x2:z(t.x2),y2:z(t.y2),durationMs:z(t.durationMs)})}function Jn(e){if(!Zn(e.command))return{};let t=e.result??{};return I({platform:F(t.platform,i),target:F(t.target,o),appName:N(t.appName),appBundleId:N(t.appBundleId),bundleId:N(t.bundleId),packageName:N(t.packageName),launchTarget:N(t.launchTarget)})}function Yn(e){let t=e.result??{};return e.command===g.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==g.wait&&e.command!==g.find&&e.command!==g.get&&e.command!==g.is?{}:I({waitedMs:z(t.waitedMs),found:P(t.found)})}function Xn(e){return e===g.click||e===g.press||e===g.longPress||e===g.hover||e===g.focus||e===g.fill}function Zn(e){return e===g.open||e===g.install||e===g.reinstall||e===Le.installSource}function B(e){let t=e.result??{};return Qn(t)??$n(t)??er(t)??sr(e.positionals[0])}function Qn(e){let t=G(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function $n(e){let t=z(e.x),n=z(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function er(e){return N(e.appName)??N(e.appBundleId)??N(e.bundleId)??N(e.packageName)}function tr(e){if(e.positionals.length!==0)return e.command===g.type?[H(`text`)]:e.command===g.fill?nr(e):e.command===g.find?rr(e):e.command===g.clipboard?ir(e):e.command===g.push?ar(e,`app`,`payload`):e.command===g.triggerAppEvent?ar(e,`event`,`payload`):e.positionals.map(V)}function nr(e){let t=H(`text`),n=e.result??{},r=G(n);if(r)return[`@${r}`,t];if(N(n.selector))return[H(`target`),t];let i=z(n.x),a=z(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function rr(e){let t=+!!cr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],H(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,H(`text`)]:[...r,...e.positionals.slice(n).map(or)]:r}function ir(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,H(`text`)]:e.positionals.map(V)}function ar(e,t,n){let[r,i,...a]=e.positionals;return[...r?[H(t)]:[],...i?[H(n)]:[],...a.map(V)]}function or(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:V(e)}function V(e){return sr(e)??H(`arg`)}function sr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function H(e){return`<${e}>`}function cr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function lr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const ur={enums:[{source:`platform`,values:a},{source:`target`,values:o}]},dr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},fr={[g.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Re}]},[g.click]:U(),[g.press]:U(),[g.longPress]:U(),[g.hover]:U(),[g.fill]:hr(),[g.type]:hr(),[g.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[g.gesture]:gr(),[g.swipe]:gr(),[g.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[g.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[g.back]:{enums:[{source:`backMode`,output:`mode`,values:d}]},[g.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:re}]},[g.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[g.boot]:{booleans:[{source:`headless`}]},[g.close]:{booleans:[{source:`shutdown`}]}};function pr(e){let t=e.flags??{},n={},r=Object.hasOwn(fr,e.command)?fr[e.command]:void 0;return W(n,t,ur),W(n,t,r),W(n,t,mr(e.command)),Object.keys(n).length>0?n:void 0}function mr(e){return ee(e)?dr:void 0}function U(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:Be}]}}function hr(){return{numbers:[{source:`delayMs`}]}}function gr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:ie}]}}function W(e,t,n){n&&(_r(e,t,n.booleans??[]),vr(e,t,n.numbers??[]),yr(e,t,n.enums??[]))}function _r(e,t,n){for(let r of n)br(e,r.output??r.source,t[r.source])}function vr(e,t,n){for(let r of n)xr(e,r.output??r.source,t[r.source])}function yr(e,t,n){for(let r of n)Sr(e,r.output??r.source,t[r.source],r.values)}function G(e){let t=N(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function br(e,t,n){typeof n==`boolean`&&(e[t]=n)}function xr(e,t,n){let r=z(n);r!==void 0&&(e[t]=r)}function Sr(e,t,n,r){let i=F(n,r);i!==void 0&&(e[t]=i)}const Cr=65536;function wr(e){return qe(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function K(e,t){let n=Or(e);if(n===void 0)return!1;try{let e=Er(t),r=Buffer.allocUnsafe(Cr),i=0;do if(i=C.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{C.closeSync(n)}}async function Tr(e){let t=await kr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=Er(e=>{n.lineCount===0&&(n.firstLineDigest=wr(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Cr);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function q(e){let t;return K(e,e=>(t=wr(e),!1)),t}function Er(e){let t=new Je(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
1
+ import{C as e,z as t}from"./sdk-contracts.js";import{g as n}from"./sdk-batch-runner.js";import{i as r,r as i,t as a,v as o}from"./sdk-device.js";import{Jn as s,Yn as c,in as l,nn as ee,p as te,x as ne}from"./sdk-batch.js";import{o as re,s as ie,t as u}from"./back-mode.js";import{a as ae}from"./scroll-gesture.js";import{_ as d,c as oe,d as se,g as ce,h as le,i as ue,l as de,m as fe,o as pe,p as f,s as me,u as p,y as he}from"./script.js";import{A as ge,C as _e,D as ve,E as ye,M as be,N as xe,O as Se,S as Ce,T as we,_ as m,a as Te,b as Ee,c as De,i as Oe,n as ke,o as Ae,r as je,t as Me,u as Ne,v as Pe,w as Fe,x as Ie,y as Le}from"./parameterized-recorded-fill.js";import{n as h,t as g}from"./catalog.js";import{t as Re}from"./session.js";import{n as ze}from"./success-text.js";import{t as Be}from"./click-button.js";import"./device.js";import{t as _}from"./device-rotation.js";import{a as v,r as y}from"./diagnostics.js";import{O as Ve}from"./owner-identity.js";import"./file.js";import{t as He}from"./tv-remote.js";import"./diagnostics2.js";import{n as Ue,r as We}from"./session-repair-tombstone.js";import{n as Ge,r as b,t as x}from"./session-paths.js";import{t as Ke}from"./keyboard-actions.js";import S from"node:path";import C from"node:fs";import{createHash as qe}from"node:crypto";import{StringDecoder as Je}from"node:string_decoder";function Ye(e,t={}){let n=[e.command];return e.command===`snapshot`?se(n,e):e.command===`open`?ue(n,e):e.command===`runtime`?oe(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?me(n,e):e.command===`screenshot`?de(n,e):pe(n,e),n.join(` `)}function Xe(e){return e.targetEvidences?[s(e.targetEvidences)]:e.targetEvidence?[c(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??m}function Ze(e,t){let n=w(e),r=typeof t.saveScript==`string`?x(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Le(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function Qe(e){e.scriptPublication=Ie(w(e))}function $e(e){e.scriptPublication=we(w(e))}function et(e,t){e.scriptPublication=ye(w(e),t)}function tt(e){e.scriptPublication=Pe(w(e))}function nt(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function rt(e){return w(e).kind===`repair`}function it(e){return Fe(w(e))}function T(e){return ve(w(e))}function at(e){return Se(w(e))}function ot(e,t){if(t.flags?.noRecord||gt(e,t))return;t.flags&&De(e,t.flags);let n=ct(t),r=dt(e,lt(t,n));n&&ut(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:vt(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),y({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function st(e,t,n,r,i,a){t&&e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function ct(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=xe(e.flags.recordAs),n=be(t);return{literal:Ae({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function lt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:pt(e.positionals,r),result:Me(e.result,n,r),targetEvidence:ke(e.targetEvidence,n,r)}}function ut(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function dt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=je(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?ft(t.targetEvidence,n):E(t.targetEvidence,n),a=t.targetEvidences?{source:E(t.targetEvidences.source,n),destination:E(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function ft(e,t){return e&&(Te(e,t)?void 0:e)}function E(e,t){return!e||!Te(e,t)?e:{...Oe(e,t),verification:`unverifiable`}}function pt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const mt=new Set([`snapshot`,`get`,`is`,`find`]);function ht(e){return e.internal?.replayPlanStep!==!0&&mt.has(e.command)}function gt(e,t){return!t.interactiveObservation||T(e)===void 0?!1:t.flags?.record!==!0}const _t=re();function vt(e){if(!e)return{};let t={};for(let n of _t){let r=e[n];r!==void 0&&(t[n]=r)}return t}function yt(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())ne({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Tt))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function bt(t){for(let n of t){if(xt(n)){St(n);continue}let t=Et(n),r=t??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&ne(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=t;if(!(!i||!l(i)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function xt(e){return Ct(e)!==void 0}function St(t){let n=Ct(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!l(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Ct(e){return e.command===`gesture`?he(e.positionals):void 0}function wt(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Tt(e){if(e.command!==`wait`)return!1;let t=ee(e.positionals);return t?.kind!==`selector`||!l(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Et(e){if(e.command===`get`)return e.positionals[1];if(ce(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Dt(t)&&Dt(n)?void 0:t}}function Dt(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Ot(e){let t=e.scriptPublication??m;return t.kind===`repair`?t.status===`committed`||!_e(t):!1}function kt(e){return!Ce(e.scriptPublication??m)||Ot(e)}var At=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=rt(e),r=t?.publication===`active`,i;try{if(kt(e))return{written:!1};let a=jt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=S.dirname(i);return C.existsSync(o)||C.mkdirSync(o,{recursive:!0}),Pt({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Ee(e.scriptPublication??m)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Mt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=ge(e.scriptPublication??m);if(t)return x(t);let n=b(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${n}-${r}.ad`)}};function jt(e,t){let n=Ft(e,{strictPortableRefs:t.activePublication});return t.activePublication&&yt(n),{script:Gt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Mt(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(y({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:Nt(r,i)};if(o)return{written:!1,error:wt(r,i)};if(r instanceof e)throw r;return{written:!1}}function Nt(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function Pt(t){let{scriptPath:n,script:r,force:i}=t;try{Ve({destination:n,contents:r,publish:i?`replace`:`link-exclusive`})}catch(t){throw t.code===`EEXIST`?new e(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):t}}function Ft(e,t={}){let n=T(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=Rt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&It(n);let o=Wt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&bt(a),a}function It(t){let n=t.command===`gesture`?he(t.positionals??[]):void 0;if(n){Lt(n);return}if(!D(t.command))return;let r=t.command===`get`?t.positionals?.[1]:t.positionals?.[0];if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot write recorded step "${t.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Lt(t){let n=[t.source,t.destination].find(e=>e.startsWith(`@`));if(n)throw new e(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Rt(e){let t=zt(e);if(!(!t||!D(e.command)))return le(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Vt(e,t):e.command===`fill`?Bt(e,t):Ht(e,t)}function zt(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function D(e){return ce(e)||e===`fill`||e===`get`}function Bt(e,t){let n=Ae(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Vt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Ut(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Ht(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Ut(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Wt(e,t){if(!D(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function Gt(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${o(e.device)} device=${fe(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Xe(e)),r.push(Kt(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
+ `)}\n`}function Kt(e){return qt([e.command],e)||Ye(e)}function qt(e,t){if(le(t.command))return Jt(e,t);if(t.command===`fill`)return Yt(e,t);if(t.command===`get`)return Xt(e,t)}function Jt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(f(d(n))),O(e,t),p(e,t),e.join(` `);if(t.positionals.length===1)return e.push(f(n)),p(e,t),e.join(` `)}}function Yt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(f(d(n))),O(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(f(r)),p(e,t),e.join(` `)}function Xt(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(f(n)),e.push(f(d(r))),r.startsWith(`@`)&&O(e,t),e.join(` `)}function O(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(f(n))}const Zt=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Qt={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function $t(e,t){let n=t??{};switch(e.command){case h.devices:return en(n.devices);case h.apps:return tn(n.apps,e.flags?.appsFilter);case h.boot:return nn(`Booted`,n,!0);case h.shutdown:return nn(`Shut down`,n,!1);case h.install:return k(`Installed`,n);case h.reinstall:return k(`Reinstalled`,n);case h.screenshot:return rn(e,n);default:return{}}}function en(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=on(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:hn(`Found ${t.length} ${gn(`device`,t.length)}`,i.map(e=>pn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function tn(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=M(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:hn(`Found ${n.length} ${gn(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function nn(e,t,n){let r=sn(t);if(!r)return{};let i={device:r,...fn(t),booted:n};return{summary:`${e} ${pn(i,!1)}`,details:i}}function k(e,t){let n=M(t.appName),r=M(t.bundleId),i=A(t,[`packageName`,`package`]),a=M(t.platform),o=M(t.launchTarget),s=A(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=mn(n,s);if(!c)return{};let l={};return j(l,`appName`,n),j(l,`bundleId`,r),j(l,`packageName`,i),j(l,`platform`,a),o!==s&&j(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function rn(e,t){let n=an(e,t);return n?{details:{requestedFileName:n}}:{}}function an(e,t){let n=R(e.meta?.clientArtifactPaths?.path)??R(t.path);if(n)return L(n)}function on(e){if(!n(e))return;let t=sn(e);if(t)return{name:t,...fn(e)}}function sn(e){let t=A(e,[`name`,`deviceName`,`device`]);return!t||!cn(e,t)?t:un(e)}function cn(e,t){let n=ln(t);return Zt.some(t=>{let r=M(e[t]);return r!==void 0&&ln(r)===n})}function ln(e){return e.toLowerCase()}function un(e){let t=M(e.appleOs),n=M(e.platform),r=M(e.kind),i=dn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function dn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Qt,n)))return Qt[n]}function fn(e){let t=M(e.platform),n=M(e.appleOs),r=M(e.kind),i=M(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function pn(e,t){let n=M(e.name)??M(e.device)??`device`,r=M(e.platform),i=M(e.appleOs),a=[r,i===r?void 0:i,M(e.kind),M(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function mn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function A(e,t){for(let n of t){let t=M(e[n]);if(t)return t}}function j(e,t,n){n&&(e[t]=n)}function hn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function gn(e,t){return t===1?e:`${e}s`}function M(e){let t=R(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function N(e){return M(e)}function P(e){return typeof e==`boolean`?e:void 0}function F(e,t){let n=N(e);return n&&t.includes(n)?n:void 0}function I(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function L(e){let t=R(e);return t?M(t.split(/[\\/]/).at(-1)):void 0}function R(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function z(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const _n=[`up`,`down`,`left`,`right`],vn=[`top`,`bottom`];function yn(e){return`${e.command===h.reinstall?`Reinstalled`:`Installed`} ${Cn(e.result??{})??`app`}`}function bn(e){let t=e.result??{};switch(e.command){case h.scroll:return Tn(t);case h.screenshot:return On(t);case h.home:return`Went home`;case h.back:return An(t);case h.appSwitcher:return`Opened app switcher`;case h.orientation:return jn(t);case h.viewport:return Mn(t);case h.clipboard:return Nn(t);case h.keyboard:return Pn(t);case h.tvRemote:return Ln(t);case h.gesture:return Rn(t);case h.swipe:return zn(t);case h.trace:return Vn(`trace`,e);case h.record:return Vn(`recording`,e);default:return}}function xn(e){let t=e.result??{};switch(e.command){case h.scroll:return I({direction:F(t.direction,_n),edge:F(t.edge,vn),passes:z(t.passes),amount:z(t.amount),pixels:z(t.pixels),durationMs:z(t.durationMs),x1:z(t.x1),y1:z(t.y1),x2:z(t.x2),y2:z(t.y2)});case h.screenshot:return I({requestedFileName:kn(t)});case h.back:return I({mode:F(t.mode,u)});case h.orientation:return I({orientation:F(t.orientation,_)});case h.viewport:return I({width:z(t.width),height:z(t.height)});case h.clipboard:return I({action:F(t.action,[`read`,`write`])});case h.keyboard:return In(t);case h.tvRemote:return I({button:F(t.button,He),durationMs:z(t.durationMs)});case h.gesture:case h.swipe:return Bn(t);case h.trace:case h.record:return I({action:F(t.action,[`start`,`stop`]),fileName:Un(e),showTouches:P(t.showTouches)});default:return{}}}function Sn(e,t){if(e.command!==h.screenshot)return t;let n=an(e,t);return n?{...t,requestedFileName:n}:t}function Cn(e){let t=N(e.appName),n=Wn(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??wn(e)}function wn(e){let t=N(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Tn(e){let t=F(e.direction,_n),n=F(e.edge,vn),r=z(e.passes);return n?En(n,r):t?Dn(t,e):`Scrolled`}function En(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Dn(e,t){let n=z(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=z(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function On(e){let t=kn(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function kn(e){return L(e.requestedFileName)??L(e.path)}function An(e){return F(e.mode,u)===`system`?`Went back using system navigation`:`Went back`}function jn(e){let t=F(e.orientation,_);return t?P(e.confirmed)===!1?`Requested ${t} (unconfirmed)`:`Rotated to ${t}`:`Changed orientation`}function Mn(e){let t=z(e.width),n=z(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function Nn(e){let t=F(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function Pn(e){let t=R(e.action);if(!t||!Ke(t))return`Used keyboard`;if(t===`dismiss`)return Fn(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=P(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function Fn(e){return P(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function In(e){let t=R(e.action);return I({action:t&&Ke(t)?t:void 0,platform:F(e.platform,[`ios`,`android`]),visible:P(e.visible),wasVisible:P(e.wasVisible),dismissed:P(e.dismissed),attempts:z(e.attempts),mechanism:F(e.mechanism,[`dismissKey`])})}function Ln(e){let t=F(e.button,He);return t?`Pressed TV remote ${t}`:`Used TV remote`}function Rn(e){let t=F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function zn(e){let t=z(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Bn(e){return I({kind:F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:z(e.durationMs),pointerCount:z(e.pointerCount),x1:z(e.x1),y1:z(e.y1),x2:z(e.x2),y2:z(e.y2),count:z(e.count),pauseMs:z(e.pauseMs),pattern:F(e.pattern,[`one-way`,`ping-pong`]),scale:z(e.scale)})}function Vn(e,t){let n=Hn(e,F(t.result?.action,[`start`,`stop`])),r=Un(t);return r?`${n} ${r}`:n}function Hn(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function Un(e){let t=e.result??{};return L(t.requestedFileName)??L(t.outPath)??L(t.path)??L(e.positionals[1])}function Wn(e,t){for(let n of t){let t=N(e[n]);if(t)return t}}function Gn(e){switch(e.command){case h.open:return`Opened ${B(e)??`session`}`;case h.close:return`Closed ${N(e.result?.session)??`session`}`;case h.click:case h.press:return`Tapped ${B(e)??`target`}`;case h.longPress:return`Long pressed ${B(e)??`target`}`;case h.hover:return`Hovered ${B(e)??`target`}`;case h.fill:return`Filled ${B(e)??`target`}`;case h.type:return`Typed text`;case h.install:case h.reinstall:case g.installSource:return yn(e);default:return bn(e)??`Ran ${e.command}`}}function Kn(e){return I({command:e.command,positionals:tr(e),flags:pr(e),...qn(e),...Jn(e),...Yn(e),...xn(e)})}function qn(e){if(!Xn(e.command))return{};let t=e.result??{};return I({ref:G(t),targetLabel:B(e),selectorChainLength:lr(t.selectorChain)?.length,x:z(t.x),y:z(t.y),x2:z(t.x2),y2:z(t.y2),durationMs:z(t.durationMs)})}function Jn(e){if(!Zn(e.command))return{};let t=e.result??{};return I({platform:F(t.platform,r),target:F(t.target,a),appName:N(t.appName),appBundleId:N(t.appBundleId),bundleId:N(t.bundleId),packageName:N(t.packageName),launchTarget:N(t.launchTarget)})}function Yn(e){let t=e.result??{};return e.command===h.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==h.wait&&e.command!==h.find&&e.command!==h.get&&e.command!==h.is?{}:I({waitedMs:z(t.waitedMs),found:P(t.found)})}function Xn(e){return e===h.click||e===h.press||e===h.longPress||e===h.hover||e===h.focus||e===h.fill}function Zn(e){return e===h.open||e===h.install||e===h.reinstall||e===g.installSource}function B(e){let t=e.result??{};return Qn(t)??$n(t)??er(t)??sr(e.positionals[0])}function Qn(e){let t=G(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function $n(e){let t=z(e.x),n=z(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function er(e){return N(e.appName)??N(e.appBundleId)??N(e.bundleId)??N(e.packageName)}function tr(e){if(e.positionals.length!==0)return e.command===h.type?[H(`text`)]:e.command===h.fill?nr(e):e.command===h.find?rr(e):e.command===h.clipboard?ir(e):e.command===h.push?ar(e,`app`,`payload`):e.command===h.triggerAppEvent?ar(e,`event`,`payload`):e.positionals.map(V)}function nr(e){let t=H(`text`),n=e.result??{},r=G(n);if(r)return[`@${r}`,t];if(N(n.selector))return[H(`target`),t];let i=z(n.x),a=z(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function rr(e){let t=+!!cr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],H(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,H(`text`)]:[...r,...e.positionals.slice(n).map(or)]:r}function ir(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,H(`text`)]:e.positionals.map(V)}function ar(e,t,n){let[r,i,...a]=e.positionals;return[...r?[H(t)]:[],...i?[H(n)]:[],...a.map(V)]}function or(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:V(e)}function V(e){return sr(e)??H(`arg`)}function sr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function H(e){return`<${e}>`}function cr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function lr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const ur={enums:[{source:`platform`,values:i},{source:`target`,values:a}]},dr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},fr={[h.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Re}]},[h.click]:U(),[h.press]:U(),[h.longPress]:U(),[h.hover]:U(),[h.fill]:hr(),[h.type]:hr(),[h.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[h.gesture]:gr(),[h.swipe]:gr(),[h.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[h.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[h.back]:{enums:[{source:`backMode`,output:`mode`,values:u}]},[h.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:ie}]},[h.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[h.boot]:{booleans:[{source:`headless`}]},[h.close]:{booleans:[{source:`shutdown`}]}};function pr(e){let t=e.flags??{},n={},r=Object.hasOwn(fr,e.command)?fr[e.command]:void 0;return W(n,t,ur),W(n,t,r),W(n,t,mr(e.command)),Object.keys(n).length>0?n:void 0}function mr(e){return te(e)?dr:void 0}function U(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:Be}]}}function hr(){return{numbers:[{source:`delayMs`}]}}function gr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:ae}]}}function W(e,t,n){n&&(_r(e,t,n.booleans??[]),vr(e,t,n.numbers??[]),yr(e,t,n.enums??[]))}function _r(e,t,n){for(let r of n)br(e,r.output??r.source,t[r.source])}function vr(e,t,n){for(let r of n)xr(e,r.output??r.source,t[r.source])}function yr(e,t,n){for(let r of n)Sr(e,r.output??r.source,t[r.source],r.values)}function G(e){let t=N(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function br(e,t,n){typeof n==`boolean`&&(e[t]=n)}function xr(e,t,n){let r=z(n);r!==void 0&&(e[t]=r)}function Sr(e,t,n,r){let i=F(n,r);i!==void 0&&(e[t]=i)}const Cr=65536;function wr(e){return qe(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function K(e,t){let n=Or(e);if(n===void 0)return!1;try{let e=Er(t),r=Buffer.allocUnsafe(Cr),i=0;do if(i=C.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{C.closeSync(n)}}async function Tr(e){let t=await kr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=Er(e=>{n.lineCount===0&&(n.firstLineDigest=wr(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Cr);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function q(e){let t;return K(e,e=>(t=wr(e),!1)),t}function Er(e){let t=new Je(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
3
3
  `);t!==-1;t=a.indexOf(`
4
- `,o)){if(Dr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||Dr(`${n}${t.end()}`,e)}}}function Dr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Or(e){try{return C.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function kr(e){try{return await C.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Ar=5242880;function jr(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Ar;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Ar}function J(e){return`${e}.1`}function Y(e){return`${e}.window.json`}function Mr(e){let t;for(let n=0;n<3;n+=1){let n=Z(e);try{let t=Nr(e);if(Z(e)===n)return t}catch(r){if(t=r,Z(e)===n)throw r}}throw t??X(e,`the window did not settle while reading`)}function Nr(e){let t=J(e),n=Br(e);if(n===`unverifiable`)throw X(e,`window file is invalid`);if(n===void 0)return Pr(e,t);let r=n.at(-1);if(!r)throw X(e,`window file records no generation`);let i=Ur(e),a=Fr(e,r),o=[],s=Ir({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function Pr(e,t){if(q(t)!==void 0)throw X(e,`a rotated event log exists with no window record`);return{files:Ur(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Fr(e,t){let n=q(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Ir(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=q(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw X(t,`the rotated event log matches no window record`);let c=zr(n);if(c!==s.lineCount)throw X(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw X(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function Lr(e,t){let n=Wr(e);if(!n||n.size<t)return!1;let r=Br(e);if(r===`unverifiable`)return await C.promises.rename(e,J(e)),!0;let i=await Tr(e);if(i.firstLineDigest!==void 0){let t=r??[],n=t.at(-1),a=n&&n.firstLineDigest===i.firstLineDigest?n:{firstLineIndex:n?n.firstLineIndex+n.lineCount:0,lineCount:i.lineCount,firstLineDigest:i.firstLineDigest};await Hr(e,(a===n?t:[...t,a]).slice(-2))}return await C.promises.rename(e,J(e)),!0}function Rr(e,n){if(!(e>=n))throw new t(`COMMAND_FAILED`,`events cursor ${e} precedes the retained event log window; events before cursor ${n} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:e,earliestCursor:n,hint:`Resume with cursor ${n}, the oldest retained event; earlier events are no longer available.`})}function X(e,n){return new t(`COMMAND_FAILED`,`Session event log window cannot be verified: ${n}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:e,hint:`Cursor positions for this session cannot be resolved. Delete ${e}, ${J(e)}, and ${Y(e)} to restart the timeline, or read the files directly.`})}function zr(e){let t=0;return K(e,()=>{t+=1}),t}function Z(e){return[Q(Y(e)),Q(e),Q(J(e))].join(`|`)}function Q(e){try{let t=C.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Br(e){let t;try{t=C.readFileSync(Y(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!r(e)||e.version!==2)return`unverifiable`;let{generations:n}=e;if(!Array.isArray(n)||n.length===0)return`unverifiable`;let i=n.map(Vr);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function Vr(e){if(!r(e))return;let{firstLineIndex:t,lineCount:n,firstLineDigest:i}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(n)||n<0)&&typeof i==`string`&&i.length!==0)return{firstLineIndex:t,lineCount:n,firstLineDigest:i}}async function Hr(e,t){let n=Y(e),r=`${n}.${process.pid}.tmp`;await C.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await C.promises.rename(r,n)}function Ur(e){return Wr(e)!==void 0}function Wr(e){try{let n=C.lstatSync(e);if(n.isSymbolicLink())throw new t(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${e}`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}const $=new Map,Gr=new Set;function Kr(e){return S.join(e,`events.ndjson`)}function qr(e){return e.command!==g.events}function Jr(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Xr(t,`${JSON.stringify(i)}\n`)}async function Yr(e){await(e?$.get(e):Promise.all($.values()))}function Xr(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await Zr(e),await Lr(e,jr()),await C.promises.appendFile(e,t,`utf8`)}).catch(t=>{y({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function Zr(e){let t=S.dirname(e);if(!Gr.has(t))try{await C.promises.mkdir(t,{recursive:!0}),Gr.add(t)}catch(t){throw y({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function Qr(e,t,n){Jr(e,t,{kind:`action.recorded`,requestId:v().requestId,command:n.command,summary:Gn(n),details:Kn(n)})}function $r(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??v().requestId,command:t.command,summary:`Started ${t.command}`}}function ei(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=$t(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ti(e,t={}){let n=ri(t.cursor),r=ii(t.limit),i=Mr(e);Rr(n,i.earliestCursor);let a=ni(i.files,n,r),o=a.lines.flatMap(e=>{let t=ai(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function ni(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(K(a.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),i!==void 0)break}return{lines:r,...i===void 0?{}:{nextCursor:i}}}function ri(e){if(e===void 0||e.trim()===``)return 0;let n=Number(e);if(Number.isInteger(n)&&n>=0)return n;throw new t(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function ii(e){if(e===void 0||typeof e==`string`&&e.trim()===``)return 100;let n=typeof e==`string`?Number(e):e;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new t(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function ai(e){try{let t=oi(JSON.parse(e));return t?si(t):void 0}catch{return}}function oi(e){if(r(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&ci(e.kind))return e}function si(e){let t=r(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...li(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ci(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function li(e){return e===`ok`||e===`error`}const ui=36e5;var di=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new At(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}lookup(e){let t=this.sessions.get(e);return t?{address:e,session:t}:void 0}findByDevice(e){for(let[t,n]of this.sessions)if(n.device.id===e)return{address:t,session:n}}listRefs(){return Array.from(this.sessions,([e,t])=>({address:e,session:t}))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=ot(e,t);if(n){let t=this.resolveStoredSessionName(e);Qr(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){Jr(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ti(this.resolveEventLogPath(e),t)}async flushEvents(e){await Yr(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&y({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:Me(e,void 0)});it(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,ui,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=e.scriptPublication??h;ge(t)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...ze(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=ui,n){try{let r=this.resolveSessionDir(e.name);C.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...at(e)?{sourcePath:at(e)}:{},...n?{commitFailure:n}:{}};C.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){y({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Ue(this.repairTombstonePath(e))}clearRepairTombstone(e){try{C.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return We(this.resolveSessionDir(e))}defaultTracePath(e){let t=b(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){if(!Ge(e))throw new t(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(e)}: a session name cannot be empty, ".", or "..".`);return S.join(this.sessionsDir,b(e))}resolveDaemonStateDir(){return S.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return C.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return S.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return S.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Kr(this.resolveSessionDir(e))}static expandHome(e,t){return x(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};export{Qe as _,tr as a,st as c,nt as d,rt as f,T as g,et as h,qr as i,tt as l,$e as m,ei as n,Sn as o,it as p,$r as r,ht as s,di as t,Ze as u};
4
+ `,o)){if(Dr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||Dr(`${n}${t.end()}`,e)}}}function Dr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Or(e){try{return C.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function kr(e){try{return await C.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Ar=5242880;function jr(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Ar;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Ar}function J(e){return`${e}.1`}function Y(e){return`${e}.window.json`}function Mr(e){let t;for(let n=0;n<3;n+=1){let n=Z(e);try{let t=Nr(e);if(Z(e)===n)return t}catch(r){if(t=r,Z(e)===n)throw r}}throw t??X(e,`the window did not settle while reading`)}function Nr(e){let t=J(e),n=Br(e);if(n===`unverifiable`)throw X(e,`window file is invalid`);if(n===void 0)return Pr(e,t);let r=n.at(-1);if(!r)throw X(e,`window file records no generation`);let i=Ur(e),a=Fr(e,r),o=[],s=Ir({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function Pr(e,t){if(q(t)!==void 0)throw X(e,`a rotated event log exists with no window record`);return{files:Ur(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Fr(e,t){let n=q(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Ir(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=q(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw X(t,`the rotated event log matches no window record`);let c=zr(n);if(c!==s.lineCount)throw X(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw X(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function Lr(e,t){let n=Wr(e);if(!n||n.size<t)return!1;let r=Br(e);if(r===`unverifiable`)return await C.promises.rename(e,J(e)),!0;let i=await Tr(e);if(i.firstLineDigest!==void 0){let t=r??[],n=t.at(-1),a=n&&n.firstLineDigest===i.firstLineDigest?n:{firstLineIndex:n?n.firstLineIndex+n.lineCount:0,lineCount:i.lineCount,firstLineDigest:i.firstLineDigest};await Hr(e,(a===n?t:[...t,a]).slice(-2))}return await C.promises.rename(e,J(e)),!0}function Rr(t,n){if(!(t>=n))throw new e(`COMMAND_FAILED`,`events cursor ${t} precedes the retained event log window; events before cursor ${n} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:t,earliestCursor:n,hint:`Resume with cursor ${n}, the oldest retained event; earlier events are no longer available.`})}function X(t,n){return new e(`COMMAND_FAILED`,`Session event log window cannot be verified: ${n}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:t,hint:`Cursor positions for this session cannot be resolved. Delete ${t}, ${J(t)}, and ${Y(t)} to restart the timeline, or read the files directly.`})}function zr(e){let t=0;return K(e,()=>{t+=1}),t}function Z(e){return[Q(Y(e)),Q(e),Q(J(e))].join(`|`)}function Q(e){try{let t=C.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Br(e){let t;try{t=C.readFileSync(Y(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!n(e)||e.version!==2)return`unverifiable`;let{generations:r}=e;if(!Array.isArray(r)||r.length===0)return`unverifiable`;let i=r.map(Vr);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function Vr(e){if(!n(e))return;let{firstLineIndex:t,lineCount:r,firstLineDigest:i}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(r)||r<0)&&typeof i==`string`&&i.length!==0)return{firstLineIndex:t,lineCount:r,firstLineDigest:i}}async function Hr(e,t){let n=Y(e),r=`${n}.${process.pid}.tmp`;await C.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await C.promises.rename(r,n)}function Ur(e){return Wr(e)!==void 0}function Wr(t){try{let n=C.lstatSync(t);if(n.isSymbolicLink())throw new e(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${t}`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}const $=new Map,Gr=new Set;function Kr(e){return S.join(e,`events.ndjson`)}function qr(e){return e.command!==h.events}function Jr(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Xr(e,`${JSON.stringify(i)}\n`)}async function Yr(e){await(e?$.get(e):Promise.all($.values()))}function Xr(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await Zr(e),await Lr(e,jr()),await C.promises.appendFile(e,t,`utf8`)}).catch(t=>{y({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function Zr(e){let t=S.dirname(e);if(!Gr.has(t))try{await C.promises.mkdir(t,{recursive:!0}),Gr.add(t)}catch(t){throw y({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function Qr(e,t,n){Jr(e,t,{kind:`action.recorded`,requestId:v().requestId,command:n.command,summary:Gn(n),details:Kn(n)})}function $r(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??v().requestId,command:t.command,summary:`Started ${t.command}`}}function ei(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=$t(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ti(e,t={}){let n=ri(t.cursor),r=ii(t.limit),i=Mr(e);Rr(n,i.earliestCursor);let a=ni(i.files,n,r),o=a.lines.flatMap(e=>{let t=ai(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function ni(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(K(a.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),i!==void 0)break}return{lines:r,...i===void 0?{}:{nextCursor:i}}}function ri(t){if(t===void 0||t.trim()===``)return 0;let n=Number(t);if(Number.isInteger(n)&&n>=0)return n;throw new e(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function ii(t){if(t===void 0||typeof t==`string`&&t.trim()===``)return 100;let n=typeof t==`string`?Number(t):t;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new e(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function ai(e){try{let t=oi(JSON.parse(e));return t?si(t):void 0}catch{return}}function oi(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&ci(e.kind))return e}function si(e){let t=n(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...li(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ci(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function li(e){return e===`ok`||e===`error`}const ui=36e5;var di=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new At(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}lookup(e){let t=this.sessions.get(e);return t?{address:e,session:t}:void 0}findByDevice(e){for(let[t,n]of this.sessions)if(n.device.id===e)return{address:t,session:n}}listRefs(){return Array.from(this.sessions,([e,t])=>({address:e,session:t}))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=ot(e,t);if(n){let t=this.resolveStoredSessionName(e);Qr(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){Jr(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ti(this.resolveEventLogPath(e),t)}async flushEvents(e){await Yr(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&y({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:Ne(e,void 0)});it(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,ui,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=e.scriptPublication??m;_e(t)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...ze(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=ui,n){try{let r=this.resolveSessionDir(e.name);C.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...at(e)?{sourcePath:at(e)}:{},...n?{commitFailure:n}:{}};C.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){y({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Ue(this.repairTombstonePath(e))}clearRepairTombstone(e){try{C.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return We(this.resolveSessionDir(e))}defaultTracePath(e){let t=b(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(t){if(!Ge(t))throw new e(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(t)}: a session name cannot be empty, ".", or "..".`);return S.join(this.sessionsDir,b(t))}resolveDaemonStateDir(){return S.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return C.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return S.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return S.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Kr(this.resolveSessionDir(e))}static expandHome(e,t){return x(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};export{Qe as _,tr as a,st as c,nt as d,rt as f,T as g,et as h,qr as i,tt as l,$e as m,ei as n,Sn as o,it as p,$r as r,ht as s,di as t,Ze as u};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{$n as t,Hn as n,In as r,Kn as i,Vn as a,Wn as o,Zn as s}from"./sdk-batch.js";import{D as c,O as l,k as u,n as d}from"./runtime.js";import{i as f}from"./rect-center.js";import{o as p}from"./tree.js";function m(e){return e.matchedRefs.length===0?{path:2,outcome:`unverifiable`,reason:`selector-miss`}:e.identitySetRefs.length===0?{path:3,outcome:`unverifiable`,reason:`identity-set-empty`}:e.identitySetRefs.length===1?e.identitySetRefs[0]===e.winnerRef?{path:4,outcome:`verified`}:{path:5,outcome:`unverifiable`,reason:`unique-but-wrong`}:e.siblingMatchRefs.length===1?e.siblingMatchRefs[0]===e.winnerRef?{path:6,outcome:`verified`}:{path:6,outcome:`unverifiable`,reason:`signal-isolated-wrong`}:e.regionMemberRefs!==void 0&&e.regionMemberRefs.length>0&&e.viewportCandidateRef!==void 0?e.viewportCandidateRef===e.winnerRef?{path:6,outcome:`verified`}:{path:6,outcome:`unverifiable`,reason:`signal-isolated-wrong`}:{path:6,outcome:`unverifiable`,reason:`no-signal-isolation`}}function h(t,n={}){let r=n.plural===!0?`do`:`does`;return{resolveInput:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} ${r} not resolve input artifacts`)},reserveOutput:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} ${r} not reserve output artifacts`)},createTempFile:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} ${r} not create temporary files`)}}}function g(e,t={}){return{artifacts:h(e,t),policy:d()}}function _(e,t={}){let n=t.mode??`action`,{node:i,preActionNodes:a}=e;if(typeof i.index!=`number`)return;let o=l(a),s=r(x(i),a);if(n===`landmark`&&s.id===void 0&&s.label===void 0)return;let u=c(i,o,8),d=u.chain,f=S(a,i),p=C(i,o),m=T(i),h=+(d.length>0),g=e=>{let t=d.slice(0,e),n=E({nodes:a,byIndex:o,node:i,identity:s,ancestry:t,sibling:f,scrollRegion:p});return{candidate:{...s,ancestry:t,sibling:f,viewportOrder:n.viewportOrder,...p?{scrollRegion:p}:{},...m?{rect:m}:{},verification:`verified`},domain:n}};for(let e=d.length;e>=h;--e){let{candidate:t,domain:r}=g(e);if(y(t))return t.verification=v({node:i,domain:r,mode:n,brokenWalk:u.broken}),t;if(e===h)return b(t)}}function v(e){return e.brokenWalk?`unverifiable`:e.mode===`landmark`?`verified`:O({node:e.node,domain:e.domain})}function y(e){return t(s({...e,verification:`unverifiable`}))<=i}function b(e){return e.verification=`unverifiable`,t(s(e))>4096&&delete e.rect,e}const x=n;function S(e,t){return o(e,t)}function C(e,t){let n=p(e,t);if(!n)return;let r=x(n);return{role:r.role,...r.id===void 0?r.label===void 0?{}:{label:r.label}:{id:r.id}}}function w(e,t){return!e&&!t?!0:!e||!t?!1:a(e,t)}function T(e){let t=e.rect;if(t)return{x:t.x,y:t.y,width:t.width,height:t.height}}function E(e){let{nodes:t,byIndex:n,node:r,identity:i,ancestry:a,sibling:o,scrollRegion:s}=e,c=u(t,n,i,a),l=c.filter(e=>S(t,e)===o),d=c.length>0?c.filter(e=>w(C(e,n),s)):void 0,f=d?D(d):[];return{identitySet:c,siblingMatches:l,regionMembers:d,orderedRegion:f,viewportOrder:Math.max(f.findIndex(e=>e.index===r.index),0)}}function D(e){return e.map((e,t)=>({node:e,documentOrder:t,center:f(e.rect)})).sort((e,t)=>!e.center&&!t.center?e.documentOrder-t.documentOrder:e.center?t.center?e.center.y===t.center.y?e.center.x===t.center.x?e.documentOrder-t.documentOrder:e.center.x-t.center.x:e.center.y-t.center.y:-1:1).map(e=>e.node)}function O(e){let{node:t,domain:n}=e,r=t.ref,i=n.identitySet.map(e=>e.ref);return m({winnerRef:r,matchedRefs:i,identitySetRefs:i,siblingMatchRefs:n.siblingMatches.map(e=>e.ref),regionMemberRefs:n.regionMembers?.map(e=>e.ref),viewportCandidateRef:n.orderedRegion[n.viewportOrder]?.ref}).outcome}export{D as a,m as c,_ as i,C as n,w as o,S as r,g as s,x as t};
1
+ import{C as e}from"./sdk-contracts.js";import{Gn as t,Hn as n,Ln as r,Qn as i,Un as a,er as o,qn as s}from"./sdk-batch.js";import{E as c,F as l,N as u,P as d}from"./runtime.js";import{i as f}from"./rect-center.js";import{o as p}from"./tree.js";function m(e){return e.matchedRefs.length===0?{path:2,outcome:`unverifiable`,reason:`selector-miss`}:e.identitySetRefs.length===0?{path:3,outcome:`unverifiable`,reason:`identity-set-empty`}:e.identitySetRefs.length===1?e.identitySetRefs[0]===e.winnerRef?{path:4,outcome:`verified`}:{path:5,outcome:`unverifiable`,reason:`unique-but-wrong`}:e.siblingMatchRefs.length===1?e.siblingMatchRefs[0]===e.winnerRef?{path:6,outcome:`verified`}:{path:6,outcome:`unverifiable`,reason:`signal-isolated-wrong`}:e.regionMemberRefs!==void 0&&e.regionMemberRefs.length>0&&e.viewportCandidateRef!==void 0?e.viewportCandidateRef===e.winnerRef?{path:6,outcome:`verified`}:{path:6,outcome:`unverifiable`,reason:`signal-isolated-wrong`}:{path:6,outcome:`unverifiable`,reason:`no-signal-isolation`}}function h(t,n={}){let r=n.plural===!0?`do`:`does`;return{resolveInput:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} ${r} not resolve input artifacts`)},reserveOutput:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} ${r} not reserve output artifacts`)},createTempFile:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} ${r} not create temporary files`)}}}function g(e,t={}){return{artifacts:h(e,t),policy:c()}}function _(e,t={}){let n=t.mode??`action`,{node:i,preActionNodes:a}=e;if(typeof i.index!=`number`)return;let o=d(a),s=r(x(i),a);if(n===`landmark`&&s.id===void 0&&s.label===void 0)return;let c=u(i,o,8),l=c.chain,f=S(a,i),p=C(i,o),m=T(i),h=+(l.length>0),g=e=>{let t=l.slice(0,e),n=E({nodes:a,byIndex:o,node:i,identity:s,ancestry:t,sibling:f,scrollRegion:p});return{candidate:{...s,ancestry:t,sibling:f,viewportOrder:n.viewportOrder,...p?{scrollRegion:p}:{},...m?{rect:m}:{},verification:`verified`},domain:n}};for(let e=l.length;e>=h;--e){let{candidate:t,domain:r}=g(e);if(y(t))return t.verification=v({node:i,domain:r,mode:n,brokenWalk:c.broken}),t;if(e===h)return b(t)}}function v(e){return e.brokenWalk?`unverifiable`:e.mode===`landmark`?`verified`:O({node:e.node,domain:e.domain})}function y(e){return o(i({...e,verification:`unverifiable`}))<=s}function b(e){return e.verification=`unverifiable`,o(i(e))>4096&&delete e.rect,e}const x=a;function S(e,n){return t(e,n)}function C(e,t){let n=p(e,t);if(!n)return;let r=x(n);return{role:r.role,...r.id===void 0?r.label===void 0?{}:{label:r.label}:{id:r.id}}}function w(e,t){return!e&&!t?!0:!e||!t?!1:n(e,t)}function T(e){let t=e.rect;if(t)return{x:t.x,y:t.y,width:t.width,height:t.height}}function E(e){let{nodes:t,byIndex:n,node:r,identity:i,ancestry:a,sibling:o,scrollRegion:s}=e,c=l(t,n,i,a),u=c.filter(e=>S(t,e)===o),d=c.length>0?c.filter(e=>w(C(e,n),s)):void 0,f=d?D(d):[];return{identitySet:c,siblingMatches:u,regionMembers:d,orderedRegion:f,viewportOrder:Math.max(f.findIndex(e=>e.index===r.index),0)}}function D(e){return e.map((e,t)=>({node:e,documentOrder:t,center:f(e.rect)})).sort((e,t)=>!e.center&&!t.center?e.documentOrder-t.documentOrder:e.center?t.center?e.center.y===t.center.y?e.center.x===t.center.x?e.documentOrder-t.documentOrder:e.center.x-t.center.x:e.center.y-t.center.y:-1:1).map(e=>e.node)}function O(e){let{node:t,domain:n}=e,r=t.ref,i=n.identitySet.map(e=>e.ref);return m({winnerRef:r,matchedRefs:i,identitySetRefs:i,siblingMatchRefs:n.siblingMatches.map(e=>e.ref),regionMemberRefs:n.regionMembers?.map(e=>e.ref),viewportCandidateRef:n.orderedRegion[n.viewportOrder]?.ref}).outcome}export{D as a,m as c,_ as i,C as n,w as o,S as r,g as s,x as t};