agent-device 0.21.12 → 0.21.14

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 (317) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.12.apk → agent-device-android-ime-helper-0.21.14.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.14.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.12.manifest.json → agent-device-android-ime-helper-0.21.14.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.14.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.14.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.12.manifest.json → agent-device-android-snapshot-helper-0.21.14.manifest.json} +6 -6
  7. package/apple/macos-helper/Package.swift +4 -0
  8. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +3 -6
  9. package/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/ScreenshotResponseTests.swift +15 -0
  10. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +47 -1
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +122 -42
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/Info.plist +23 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +17 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAppScreenCapture.swift +21 -13
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +1 -162
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +0 -9
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +0 -56
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +0 -48
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +0 -50
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +33 -586
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +40 -24
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift +2 -3
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +0 -36
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +630 -0
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +34 -2256
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -338
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -12
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+GestureExecution.swift +160 -0
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +0 -24
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +0 -142
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +90 -39
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+MainThreadWork.swift +78 -106
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +23 -2
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +162 -113
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +0 -209
  36. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +86 -10
  37. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollDragExecution.swift +271 -0
  38. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +1 -200
  39. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +20 -227
  40. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +78 -295
  41. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift +40 -27
  42. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +0 -78
  43. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +85 -581
  44. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCaptureTarget.swift +106 -0
  45. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotExecution.swift +142 -0
  46. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +49 -78
  47. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +0 -44
  48. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +73 -114
  49. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +1 -12
  50. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +11 -94
  51. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +2 -10
  52. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +1 -1
  53. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +0 -35
  54. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +0 -31
  55. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +2 -18
  56. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +34 -52
  57. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -22
  58. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +135 -0
  59. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +22 -6
  60. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +140 -20
  61. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotCoordinateSpace.swift +16 -19
  62. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotGeometry.swift +21 -9
  63. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +59 -10
  64. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationInvariant.swift +12 -10
  65. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +13 -8
  66. package/dist/src/absence-observation-errors.js +1 -1
  67. package/dist/src/adapter.js +1 -1
  68. package/dist/src/adb-executor.js +1 -1
  69. package/dist/src/adb-failure.js +1 -1
  70. package/dist/src/adb-transport.js +1 -1
  71. package/dist/src/agent-browser-provider.js +1 -1
  72. package/dist/src/agent-browser-tool.js +1 -1
  73. package/dist/src/agent-device-client.js +2 -2
  74. package/dist/src/ai-sdk.js +1 -1
  75. package/dist/src/alert-runtime.js +1 -1
  76. package/dist/src/android-adb.d.ts +1 -1
  77. package/dist/src/app-catalog.js +1 -1
  78. package/dist/src/app-deployment-resolution.js +1 -1
  79. package/dist/src/app-inventory.js +1 -1
  80. package/dist/src/app-launch.js +2 -2
  81. package/dist/src/app-lifecycle.js +1 -1
  82. package/dist/src/app-lifecycle2.js +1 -1
  83. package/dist/src/app-log-files.js +1 -1
  84. package/dist/src/app-log-runtime2.js +3 -3
  85. package/dist/src/app-resolution.js +2 -2
  86. package/dist/src/apple-runner-platform.js +1 -1
  87. package/dist/src/application-lifecycle-interaction.js +1 -1
  88. package/dist/src/archive.js +1 -1
  89. package/dist/src/artifact-download.js +1 -1
  90. package/dist/src/auth-session.js +1 -1
  91. package/dist/src/auth.js +1 -1
  92. package/dist/src/back-mode.js +1 -1
  93. package/dist/src/backend-snapshot-options.js +1 -1
  94. package/dist/src/boot-diagnostics.js +1 -1
  95. package/dist/src/capture-disclosure.js +1 -1
  96. package/dist/src/capture.js +1 -1
  97. package/dist/src/cli-config.js +1 -1
  98. package/dist/src/cli-help.js +8 -7
  99. package/dist/src/cli-runner.js +1 -1
  100. package/dist/src/cli.js +4 -4
  101. package/dist/src/click-button.js +1 -1
  102. package/dist/src/client-metro.js +1 -1
  103. package/dist/src/client-types.d.ts +4 -5
  104. package/dist/src/clipboard-shell-response.js +1 -1
  105. package/dist/src/code-signature.js +1 -1
  106. package/dist/src/command-schema.js +3 -3
  107. package/dist/src/command-tools.js +3 -3
  108. package/dist/src/connection-runtime.js +1 -1
  109. package/dist/src/connection.js +1 -1
  110. package/dist/src/contracts.js +1 -1
  111. package/dist/src/daemon-client-lifecycle.js +1 -1
  112. package/dist/src/daemon-resolution.js +1 -1
  113. package/dist/src/daemon.js +1 -1
  114. package/dist/src/debug-symbols-facade.js +1 -1
  115. package/dist/src/device-claim-rule.js +2 -2
  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/device-shell.js +1 -1
  122. package/dist/src/device2.js +1 -1
  123. package/dist/src/devicectl.js +1 -1
  124. package/dist/src/diagnostics.js +1 -1
  125. package/dist/src/dispatch-resolve.js +1 -1
  126. package/dist/src/display-inventory.js +1 -1
  127. package/dist/src/doctor-facade.js +1 -1
  128. package/dist/src/doctor2.js +1 -1
  129. package/dist/src/engine-eval-script.js +1 -1
  130. package/dist/src/error.js +1 -1
  131. package/dist/src/exec.js +1 -1
  132. package/dist/src/file.js +1 -1
  133. package/dist/src/find.js +1 -1
  134. package/dist/src/format.js +1 -1
  135. package/dist/src/gesture-plan-types.d.ts +38 -0
  136. package/dist/src/gesture-plan.js +1 -1
  137. package/dist/src/gesture-runtime.js +1 -1
  138. package/dist/src/harmonyos.js +1 -1
  139. package/dist/src/helper.js +2 -2
  140. package/dist/src/host.js +1 -1
  141. package/dist/src/human-control-contract.js +1 -1
  142. package/dist/src/human-control.js +1 -1
  143. package/dist/src/index.js +1 -1
  144. package/dist/src/input-actions.js +1 -1
  145. package/dist/src/input-actions2.js +1 -1
  146. package/dist/src/install-artifact-facade.js +1 -1
  147. package/dist/src/install-source-network-transport.js +1 -1
  148. package/dist/src/install-source2.js +1 -1
  149. package/dist/src/interaction-positionals.js +1 -1
  150. package/dist/src/interaction-ref-policy.js +1 -1
  151. package/dist/src/interaction2.js +1 -1
  152. package/dist/src/interactor-operation-binding.js +1 -1
  153. package/dist/src/interactor-operation-catalog.js +1 -1
  154. package/dist/src/interactor.js +4 -4
  155. package/dist/src/interactor2.js +1 -1
  156. package/dist/src/interactors.js +1 -1
  157. package/dist/src/internal/bin.js +1 -1
  158. package/dist/src/internal/daemon.js +2 -2
  159. package/dist/src/internal/png-worker.js +1 -1
  160. package/dist/src/internal/run-script-http-child.js +1 -1
  161. package/dist/src/inventory.js +1 -1
  162. package/dist/src/inventory2.js +1 -1
  163. package/dist/src/inventory3.js +1 -1
  164. package/dist/src/inventory5.js +1 -1
  165. package/dist/src/ios-snapshot-acquisition.js +1 -1
  166. package/dist/src/ios-snapshot-runtime.js +1 -1
  167. package/dist/src/lease.js +1 -1
  168. package/dist/src/limrun-download-file.js +1 -1
  169. package/dist/src/limrun-runtime-dependencies.js +1 -1
  170. package/dist/src/limrun.d.ts +435 -4
  171. package/dist/src/linux.js +1 -1
  172. package/dist/src/local-interactor-operation-set.js +1 -1
  173. package/dist/src/location-coordinates.js +1 -1
  174. package/dist/src/managed-device-scope.js +1 -1
  175. package/dist/src/mechanics.js +5 -5
  176. package/dist/src/mobile-snapshot-semantics.js +1 -1
  177. package/dist/src/multitouch-support.js +1 -1
  178. package/dist/src/native-build-cache.js +1 -0
  179. package/dist/src/observation.js +1 -1
  180. package/dist/src/parameterized-recorded-fill.js +1 -1
  181. package/dist/src/perf-facade.js +1 -2
  182. package/dist/src/perf-runtime-operation-builder.js +1 -1
  183. package/dist/src/perf-runtime-plan.js +1 -1
  184. package/dist/src/perf-target.js +2 -0
  185. package/dist/src/perf.js +1 -1
  186. package/dist/src/physical-device-apps.js +1 -0
  187. package/dist/src/physical-device-control.js +1 -1
  188. package/dist/src/platform-request-scope.js +1 -1
  189. package/dist/src/platform-runtime-host.js +1 -1
  190. package/dist/src/platform-runtime-managed-owner.js +1 -1
  191. package/dist/src/platform-runtime-open-target.js +1 -1
  192. package/dist/src/platform-runtime-operation-host.js +2 -2
  193. package/dist/src/platform-runtime-runtime-hints.js +1 -1
  194. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  195. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  196. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  197. package/dist/src/platform-runtime-unavailable.js +1 -1
  198. package/dist/src/platform-runtime.js +1 -1
  199. package/dist/src/platform-runtime2.js +1 -1
  200. package/dist/src/png-crop-bytes.js +1 -1
  201. package/dist/src/png-size.js +1 -1
  202. package/dist/src/png-worker-client.js +1 -1
  203. package/dist/src/png.js +1 -1
  204. package/dist/src/prepare-kind.js +1 -1
  205. package/dist/src/provider-session-ownership.js +1 -1
  206. package/dist/src/provider-webdriver.js +1 -1
  207. package/dist/src/proxy.js +1 -1
  208. package/dist/src/quality-warnings.js +1 -1
  209. package/dist/src/react-native.js +1 -1
  210. package/dist/src/record-runtime.js +1 -1
  211. package/dist/src/recording.js +1 -1
  212. package/dist/src/register-builtins.js +1 -1
  213. package/dist/src/registry.js +35 -35
  214. package/dist/src/remote-config2.js +1 -1
  215. package/dist/src/replay-divergence.js +1 -1
  216. package/dist/src/replay.js +1 -1
  217. package/dist/src/reporting.js +1 -1
  218. package/dist/src/request-admission.js +1 -1
  219. package/dist/src/request-cancel.js +1 -1
  220. package/dist/src/request-runtime-binding.js +1 -1
  221. package/dist/src/retry.js +1 -1
  222. package/dist/src/runner-cache-metadata.js +1 -1
  223. package/dist/src/runner-client.js +1 -1
  224. package/dist/src/runner-dev-tools-security.js +1 -1
  225. package/dist/src/runner-device-readiness.js +1 -1
  226. package/dist/src/runner-disposal.js +1 -1
  227. package/dist/src/runner-error-classification.js +3 -0
  228. package/dist/src/runner-operations-facade.js +1 -1
  229. package/dist/src/runner-presentation.js +1 -1
  230. package/dist/src/runner.js +1 -1
  231. package/dist/src/runtime-transport-hints.js +1 -1
  232. package/dist/src/runtime.js +3 -3
  233. package/dist/src/runtime10.js +2 -2
  234. package/dist/src/runtime2.js +2 -2
  235. package/dist/src/runtime3.js +1 -1
  236. package/dist/src/runtime4.js +4 -4
  237. package/dist/src/runtime5.js +1 -1
  238. package/dist/src/runtime6.js +1 -1
  239. package/dist/src/runtime7.js +1 -1
  240. package/dist/src/runtime8.js +1 -1
  241. package/dist/src/runtime9.js +1 -1
  242. package/dist/src/screen-recording-admission-ledger.js +1 -1
  243. package/dist/src/screen-recording-completion.js +1 -1
  244. package/dist/src/screen-recording-options.js +1 -1
  245. package/dist/src/screen-recording-resource-recovery.js +1 -1
  246. package/dist/src/screen-recording-transport.js +1 -1
  247. package/dist/src/screenshot-density.js +1 -1
  248. package/dist/src/screenshot-image.js +1 -1
  249. package/dist/src/screenshot-runtime.js +1 -1
  250. package/dist/src/screenshot.js +1 -1
  251. package/dist/src/screenshot3.js +1 -1
  252. package/dist/src/script.js +1 -1
  253. package/dist/src/scroll-command.d.ts +377 -0
  254. package/dist/src/scroll-command.js +1 -1
  255. package/dist/src/scroll-gesture.js +1 -1
  256. package/dist/src/sdk-batch-runner.js +2 -2
  257. package/dist/src/sdk-batch.js +2 -2
  258. package/dist/src/sdk-contracts.d.ts +28 -0
  259. package/dist/src/sdk-contracts.js +1 -1
  260. package/dist/src/sdk-device.js +1 -1
  261. package/dist/src/sdk-io.js +1 -1
  262. package/dist/src/sdk-remote-config.js +1 -1
  263. package/dist/src/sdk-selectors.d.ts +23 -726
  264. package/dist/src/selection.js +0 -0
  265. package/dist/src/selector-runtime.js +1 -1
  266. package/dist/src/semantic-index.js +1 -1
  267. package/dist/src/server.js +1 -1
  268. package/dist/src/session-allocation.js +1 -1
  269. package/dist/src/session-observation.js +1 -1
  270. package/dist/src/session-routing.js +1 -1
  271. package/dist/src/session-runtime-admission.js +1 -1
  272. package/dist/src/session-snapshot.js +1 -1
  273. package/dist/src/session-store.js +2 -2
  274. package/dist/src/session2.js +3 -3
  275. package/dist/src/settings.js +1 -1
  276. package/dist/src/simctl-facade.js +1 -1
  277. package/dist/src/simctl.js +1 -1
  278. package/dist/src/simulator-state.js +1 -1
  279. package/dist/src/simulator.js +1 -1
  280. package/dist/src/snapshot-runtime-binding.js +1 -1
  281. package/dist/src/snapshot-runtime.js +1 -1
  282. package/dist/src/snapshot-state.js +1 -1
  283. package/dist/src/snapshot2.js +1 -1
  284. package/dist/src/snapshot3.js +1 -1
  285. package/dist/src/snapshot4.js +1 -1
  286. package/dist/src/src.js +1 -1
  287. package/dist/src/src7.js +1 -1
  288. package/dist/src/src8.js +2 -2
  289. package/dist/src/string-enum.js +1 -1
  290. package/dist/src/takeover.js +1 -1
  291. package/dist/src/text-entry-focus.js +1 -1
  292. package/dist/src/tool-provider-facade.js +1 -1
  293. package/dist/src/tool-provider.js +2 -2
  294. package/dist/src/tool-provider2.js +1 -1
  295. package/dist/src/touch-runtime.js +1 -1
  296. package/dist/src/transport.js +1 -1
  297. package/dist/src/tree.js +1 -1
  298. package/dist/src/tv-remote.js +1 -1
  299. package/dist/src/type-text-runtime.js +1 -1
  300. package/dist/src/update-check.js +1 -1
  301. package/dist/src/verified-file.js +1 -1
  302. package/dist/src/version.js +1 -1
  303. package/dist/src/video.js +1 -1
  304. package/dist/src/viewport.js +1 -1
  305. package/dist/src/web.js +1 -1
  306. package/dist/src/web2.js +1 -1
  307. package/dist/src/webdriver-source.js +1 -1
  308. package/package.json +3 -2
  309. package/server.json +2 -2
  310. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.12.apk.sha256 +0 -1
  311. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.12.apk +0 -0
  312. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.12.apk.sha256 +0 -1
  313. package/dist/src/app-inventory.d.ts +0 -4
  314. package/dist/src/apps-simctl.js +0 -1
  315. package/dist/src/cloud-artifacts.d.ts +0 -61
  316. package/dist/src/runner-contract.js +0 -3
  317. package/dist/src/snapshot-process.js +0 -1
@@ -1 +1 @@
1
- import{D as e,L as t,S as n,p as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./snapshot-capture-annotations.js";import{i as a}from"./snapshot-diagnostics.js";import{f as o}from"./android-input-ownership.js";import{b as s}from"./sdk-device.js";import{s as c}from"./session-store.js";import{a as l,f as u,j as d,k as f,o as p,s as m}from"./session-snapshot.js";import{n as h}from"./success-text.js";import{r as g}from"./diagnostics.js";import"./diagnostics2.js";import{i as _,s as v}from"./android-system-chrome.js";import{r as y}from"./request-cancel.js";import"./request.js";import{a as b,i as x,r as S,t as C}from"./screenshot-runtime.js";import{a as w}from"./session-routing.js";import{s as T,t as E}from"./quality-warnings.js";import{i as D,r as O}from"./capture-disclosure.js";import{n as k,o as A,r as j}from"./snapshot-runtime-binding.js";import M from"node:path";import{promises as N}from"node:fs";import P from"node:os";function F(e){return{captureFailed:!0,error:e}}function I(e){return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:`unavailable`}}function L(e,t){let n={path:e,overlayRefsRequested:!0,overlayRefSource:`session-snapshot`};return R(t)?{...n,overlayRefsAnnotated:!0,overlayRefs:t}:{...n,overlayRefsAnnotated:!1,overlayRefs:[]}}function R(e){return e.length>0}function z(e,t){return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:`session-snapshot`,overlayAnnotationError:t}}function B(e){return`captureFailed`in e?{overlayRefCount:void 0,overlayRefsAnnotated:void 0}:{overlayRefCount:`overlayRefs`in e?e.overlayRefs.length:0,overlayRefsAnnotated:e.overlayRefsAnnotated}}function ee(e){return v(e)===`accessibility-timeout`}async function V(e){if(e.command!==`snapshot`||e.device.platform!==`android`)return;let n=t(e.error);if(ee(n))return{ok:!1,error:{...n,details:{...n.details??{},androidSnapshotTimeoutScreenshot:await H(e)}}}}async function H(n){try{let t=await x({device:n.device,overlayRefs:!1,inspectFacts:n.inspectFacts,bindDevice:n.bindDevice});if(!t.ok)throw new e(`UNSUPPORTED_OPERATION`,`The target does not support screenshot capture, so no timeout evidence was taken.`);let r=await N.mkdtemp(M.join(P.tmpdir(),`agent-device-android-snapshot-timeout-`)),i=M.join(r,`snapshot-timeout-overlay-refs.png`);await t.runtime.captureScreenshot({outPath:i,options:{appBundleId:n.session?.appBundleId,stabilize:!1,surface:n.session?.surface},execution:S(f(n.logPath,{screenshotNoStabilize:!0},n.session?.appBundleId,n.session?.trace?.outPath))}),await N.access(i);let a=await U(i,n.session);return g({level:`warn`,phase:`android_snapshot_timeout_screenshot_captured`,data:{path:i,...B(a)}}),a}catch(e){let n=t(e);return g({level:`warn`,phase:`android_snapshot_timeout_screenshot_failed`,data:{error:n.message}}),F(n.message)}}async function U(e,n){if(!n?.snapshot)return I(e);try{return L(e,await b({screenshotPath:e,snapshot:n.snapshot}))}catch(n){let r=t(n);return g({level:`warn`,phase:`android_snapshot_timeout_screenshot_overlay_failed`,data:{path:e,error:r.message}}),z(e,r.message)}}function W(e){let{verdict:t,appBundleId:n,latch:r}=e;return!t||t.backend===`android-helper`?{latch:r}:t.state===`healthy`?{latch:void 0}:t.state!==`recovered`||t.reasonCode===`requested-backend`?{latch:r}:t.reasonCode===`deferred`?r!==void 0&&r.appBundleId===n?{latch:r}:{warning:E(t.backend),latch:{appBundleId:n}}:{latch:{appBundleId:n}}}function G(e){let{session:t,data:n,verdict:r,internalObservation:i}=e;if(i||!t)return n;let a=W({verdict:r,appBundleId:t.appBundleId,latch:t.recoveredSnapshotWarningLatch});return t.recoveredSnapshotWarningLatch=a.latch,a.warning?{...n,warnings:[a.warning,...h(n)]}:n}async function K(e){let t=await k(e,e.command);if(!t.ok)return t.response;let{session:n,device:r,snapshotScope:i}=t;return await A(n,r,async()=>{let{req:a,sessionName:s,logPath:c,sessionStore:l}=e,u={},d=q({req:a,sessionName:s,logPath:c,sessionStore:l,session:n,device:r,snapshotScope:i,capturedQuality:u,captureSnapshotData:t.captureSnapshot,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice}),f;try{f=await e.execute({runtime:d,sessionName:s,req:a,snapshotScope:i})}catch(t){let i=await V({error:t,command:e.command,logPath:c,session:n,device:r,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!i)throw t;return i}te({req:a,sessionName:s,sessionStore:l,result:f.record});let p=G({session:l.get(s),data:f.data,verdict:u.value,internalObservation:a.internal?.observationOnly===!0});return{ok:!0,data:o(f.data,p)}},e.platformResourceCleanup)}function q(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,session:a,device:o,snapshotScope:s}=e;return u({backend:$({req:t,logPath:r,session:a,device:o,snapshotScope:s,capturedQuality:e.capturedQuality,captureSnapshotData:e.captureSnapshotData,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice}),...D(`snapshot`),signal:y(t.meta?.requestId),sessions:p({sessionName:n,getSession:()=>i.get(n),recordOptions:{includeSnapshot:!0},setRecord:e=>{let r=ne(e),a=i.get(n);i.set(n,J({current:a,sessionName:n,sessionScope:w(t),device:o,record:r,refScopedSnapshot:Y(t),issuesRefsToClient:t.command===`snapshot`&&t.internal?.observationOnly!==!0}))}})})}function J(e){let{current:t,sessionName:n,sessionScope:r,device:i,record:a,refScopedSnapshot:o}=e,s=X(t,a,o),c=s?t.snapshot:a.snapshot,u=j({session:t,sessionName:n,sessionScope:r,device:i,snapshot:c,appBundleId:a.appBundleId});return l(u,{scopeSource:Q({current:t,keepCurrentSnapshot:s,refScopedSnapshot:o}),keptCurrentSnapshot:s,previousGeneration:t?.snapshotGeneration}),Z(u,s,e.issuesRefsToClient),a.appName&&(u.appName=a.appName),u}function Y(e){return e.flags?.snapshotScope?.trim().startsWith(`@`)===!0}function X(e,t,n){return n&&t.snapshot?.nodes.length===0&&e?.snapshot!==void 0}function Z(e,t,n){!t&&n&&d(e)}function Q(e){let{current:t,keepCurrentSnapshot:n,refScopedSnapshot:r}=e;if(r)return n?t?.snapshotScopeSource:t?.snapshotScopeSource??t?.snapshot}function $(e){let{req:t,logPath:n,session:r,device:o,snapshotScope:c}=e;return{platform:s(o),captureSnapshot:async(s,l)=>{let u=await m({device:o,session:r,flags:t.flags,outPath:l?.outPath??t.flags?.out,logPath:n,snapshotScope:c,signal:s.signal,captureData:e.captureSnapshotData,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice}),d=i(u);e.capturedQuality.value=d.quality;let f=a(r);return{snapshot:u.snapshot,...d,...f?{snapshotDiagnostics:f}:{},appName:r?.appBundleId?r.appName??r.appBundleId:void 0,appBundleId:r?.appBundleId}}}}function te(e){let t=e.sessionStore.get(e.sessionName);t&&e.sessionStore.recordAction(t,{command:e.req.command,positionals:e.req.positionals??[],flags:e.req.flags??{},result:re(e.result),interactiveObservation:c(e.req)})}function ne(t){if(!t.snapshot)throw new e(`UNKNOWN`,`snapshot runtime did not produce session state`);return t}function re(e){return e.kind===`snapshot`?{nodes:e.nodes,truncated:e.truncated}:{mode:e.mode,baselineInitialized:e.baselineInitialized,summary:e.summary}}async function ie(e){let t=e.session;if(!t||!T(e.verdict)||e.req.internal?.observationOnly===!0)return;let n=await ae({...e,session:t});if(n!==void 0)return{path:n,artifact:{field:`fallbackScreenshotPath`,artifactType:`screenshot`,path:n,fileName:`snapshot-fallback.png`}}}async function ae(e){let{req:t,session:n}=e;try{let r=await x({device:n.device,overlayRefs:!1,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return r.ok?(await C({session:n,sessionName:e.sessionName,captureScreenshot:r.runtime.captureScreenshot,dispatchContext:f(e.logPath,t.flags,n.appBundleId,n.trace?.outPath,t.meta?.requestId,t.meta)})).path:void 0}catch{return}}async function oe(e){let t={},i=await K({...e,command:`snapshot`,execute:async({runtime:i,sessionName:a,req:s,snapshotScope:c})=>{let l=await i.capture.snapshot({session:a,...n(s.flags,r),scope:c});l.targetActivation&&!t.state&&(t.state={targetActivation:l.targetActivation});let u=se(s,e.sessionStore.get(a)),d=_(l.nodes),f=o(l,d===l.nodes?l:{...l,nodes:d}),p=await ie({req:s,session:e.sessionStore.get(a),sessionName:a,logPath:e.logPath,verdict:l.snapshotQuality,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice}),m=o(f,p?{...f,fallbackScreenshotPath:p.path,artifacts:[p.artifact]}:f);return{data:u===void 0?m:o(m,{...m,refsGeneration:u}),record:{kind:`snapshot`,nodes:l.nodes.length,truncated:l.truncated}}}});return O(i,t.state)}function se(e,t){return e.internal?.observationOnly===!0?void 0:t?.snapshotGeneration}export{K as n,oe as t};
1
+ import{C as e,O as t,R as n,p as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./snapshot-capture-annotations.js";import{i as a}from"./snapshot-diagnostics.js";import{f as o}from"./android-input-ownership.js";import{b as s}from"./sdk-device.js";import{s as c}from"./session-store.js";import{L as l,a as u,f as d,o as f,s as p,z as m}from"./session-snapshot.js";import{n as h}from"./success-text.js";import{r as g}from"./diagnostics.js";import"./diagnostics2.js";import{i as _,s as v}from"./android-system-chrome.js";import{r as y}from"./request-cancel.js";import"./request.js";import{a as b,i as x,r as S,t as C}from"./screenshot-runtime.js";import{a as w}from"./session-routing.js";import{s as T,t as E}from"./quality-warnings.js";import{i as D,r as O}from"./capture-disclosure.js";import{n as k,o as A,r as j}from"./snapshot-runtime-binding.js";import M from"node:path";import{promises as N}from"node:fs";import P from"node:os";function F(e){return{captureFailed:!0,error:e}}function I(e){return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:`unavailable`}}function L(e,t){let n={path:e,overlayRefsRequested:!0,overlayRefSource:`session-snapshot`};return R(t)?{...n,overlayRefsAnnotated:!0,overlayRefs:t}:{...n,overlayRefsAnnotated:!1,overlayRefs:[]}}function R(e){return e.length>0}function z(e,t){return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:`session-snapshot`,overlayAnnotationError:t}}function B(e){return`captureFailed`in e?{overlayRefCount:void 0,overlayRefsAnnotated:void 0}:{overlayRefCount:`overlayRefs`in e?e.overlayRefs.length:0,overlayRefsAnnotated:e.overlayRefsAnnotated}}function ee(e){return v(e)===`accessibility-timeout`}async function V(e){if(e.command!==`snapshot`||e.device.platform!==`android`)return;let t=n(e.error);if(ee(t))return{ok:!1,error:{...t,details:{...t.details??{},androidSnapshotTimeoutScreenshot:await H(e)}}}}async function H(e){try{let n=await x({device:e.device,overlayRefs:!1,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!n.ok)throw new t(`UNSUPPORTED_OPERATION`,`The target does not support screenshot capture, so no timeout evidence was taken.`);let r=await N.mkdtemp(M.join(P.tmpdir(),`agent-device-android-snapshot-timeout-`)),i=M.join(r,`snapshot-timeout-overlay-refs.png`);await n.runtime.captureScreenshot({outPath:i,options:{appBundleId:e.session?.appBundleId,stabilize:!1,surface:e.session?.surface},execution:S(l(e.logPath,{screenshotNoStabilize:!0},e.session?.appBundleId,e.session?.trace?.outPath))}),await N.access(i);let a=await U(i,e.session);return g({level:`warn`,phase:`android_snapshot_timeout_screenshot_captured`,data:{path:i,...B(a)}}),a}catch(e){let t=n(e);return g({level:`warn`,phase:`android_snapshot_timeout_screenshot_failed`,data:{error:t.message}}),F(t.message)}}async function U(e,t){if(!t?.snapshot)return I(e);try{return L(e,await b({screenshotPath:e,snapshot:t.snapshot}))}catch(t){let r=n(t);return g({level:`warn`,phase:`android_snapshot_timeout_screenshot_overlay_failed`,data:{path:e,error:r.message}}),z(e,r.message)}}function W(e){let{verdict:t,appBundleId:n,latch:r}=e;return!t||t.backend===`android-helper`?{latch:r}:t.state===`healthy`?{latch:void 0}:t.state!==`recovered`||t.reasonCode===`requested-backend`?{latch:r}:t.reasonCode===`deferred`?r!==void 0&&r.appBundleId===n?{latch:r}:{warning:E(t.backend),latch:{appBundleId:n}}:{latch:{appBundleId:n}}}function G(e){let{session:t,data:n,verdict:r,internalObservation:i}=e;if(i||!t)return n;let a=W({verdict:r,appBundleId:t.appBundleId,latch:t.recoveredSnapshotWarningLatch});return t.recoveredSnapshotWarningLatch=a.latch,a.warning?{...n,warnings:[a.warning,...h(n)]}:n}async function K(e){let t=await k(e,e.command);if(!t.ok)return t.response;let{session:n,device:r,snapshotScope:i}=t;return await A(n,r,async()=>{let{req:a,sessionName:s,logPath:c,sessionStore:l}=e,u={},d=q({req:a,sessionName:s,logPath:c,sessionStore:l,session:n,device:r,snapshotScope:i,capturedQuality:u,captureSnapshotData:t.captureSnapshot,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice}),f;try{f=await e.execute({runtime:d,sessionName:s,req:a,snapshotScope:i})}catch(t){let i=await V({error:t,command:e.command,logPath:c,session:n,device:r,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!i)throw t;return i}te({req:a,sessionName:s,sessionStore:l,result:f.record});let p=G({session:l.get(s),data:f.data,verdict:u.value,internalObservation:a.internal?.observationOnly===!0});return{ok:!0,data:o(f.data,p)}},e.platformResourceCleanup)}function q(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,session:a,device:o,snapshotScope:s}=e;return d({backend:$({req:t,logPath:r,session:a,device:o,snapshotScope:s,capturedQuality:e.capturedQuality,captureSnapshotData:e.captureSnapshotData,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice}),...D(`snapshot`),signal:y(t.meta?.requestId),sessions:f({sessionName:n,getSession:()=>i.get(n),recordOptions:{includeSnapshot:!0},setRecord:e=>{let r=ne(e),a=i.get(n);i.set(n,J({current:a,sessionName:n,sessionScope:w(t),device:o,record:r,refScopedSnapshot:Y(t),issuesRefsToClient:t.command===`snapshot`&&t.internal?.observationOnly!==!0}))}})})}function J(e){let{current:t,sessionName:n,sessionScope:r,device:i,record:a,refScopedSnapshot:o}=e,s=X(t,a,o),c=s?t.snapshot:a.snapshot,l=j({session:t,sessionName:n,sessionScope:r,device:i,snapshot:c,appBundleId:a.appBundleId});return u(l,{scopeSource:Q({current:t,keepCurrentSnapshot:s,refScopedSnapshot:o}),keptCurrentSnapshot:s,previousGeneration:t?.snapshotGeneration}),Z(l,s,e.issuesRefsToClient),a.appName&&(l.appName=a.appName),l}function Y(e){return e.flags?.snapshotScope?.trim().startsWith(`@`)===!0}function X(e,t,n){return n&&t.snapshot?.nodes.length===0&&e?.snapshot!==void 0}function Z(e,t,n){!t&&n&&m(e)}function Q(e){let{current:t,keepCurrentSnapshot:n,refScopedSnapshot:r}=e;if(r)return n?t?.snapshotScopeSource:t?.snapshotScopeSource??t?.snapshot}function $(e){let{req:t,logPath:n,session:r,device:o,snapshotScope:c}=e;return{platform:s(o),captureSnapshot:async(s,l)=>{let u=await p({device:o,session:r,flags:t.flags,outPath:l?.outPath??t.flags?.out,logPath:n,snapshotScope:c,signal:s.signal,captureData:e.captureSnapshotData,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice}),d=i(u);e.capturedQuality.value=d.quality;let f=a(r);return{snapshot:u.snapshot,...d,...f?{snapshotDiagnostics:f}:{},appName:r?.appBundleId?r.appName??r.appBundleId:void 0,appBundleId:r?.appBundleId}}}}function te(e){let t=e.sessionStore.get(e.sessionName);t&&e.sessionStore.recordAction(t,{command:e.req.command,positionals:e.req.positionals??[],flags:e.req.flags??{},result:re(e.result),interactiveObservation:c(e.req)})}function ne(e){if(!e.snapshot)throw new t(`UNKNOWN`,`snapshot runtime did not produce session state`);return e}function re(e){return e.kind===`snapshot`?{nodes:e.nodes,truncated:e.truncated}:{mode:e.mode,baselineInitialized:e.baselineInitialized,summary:e.summary}}async function ie(e){let t=e.session;if(!t||!T(e.verdict)||e.req.internal?.observationOnly===!0)return;let n=await ae({...e,session:t});if(n!==void 0)return{path:n,artifact:{field:`fallbackScreenshotPath`,artifactType:`screenshot`,path:n,fileName:`snapshot-fallback.png`}}}async function ae(e){let{req:t,session:n}=e;try{let r=await x({device:n.device,overlayRefs:!1,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return r.ok?(await C({session:n,sessionName:e.sessionName,captureScreenshot:r.runtime.captureScreenshot,dispatchContext:l(e.logPath,t.flags,n.appBundleId,n.trace?.outPath,t.meta?.requestId,t.meta)})).path:void 0}catch{return}}async function oe(t){let n={},i=await K({...t,command:`snapshot`,execute:async({runtime:i,sessionName:a,req:s,snapshotScope:c})=>{let l=await i.capture.snapshot({session:a,...e(s.flags,r),scope:c});l.targetActivation&&(n.targetActivation??=l.targetActivation);let u=se(s,t.sessionStore.get(a)),d=_(l.nodes),f=o(l,d===l.nodes?l:{...l,nodes:d}),p=await ie({req:s,session:t.sessionStore.get(a),sessionName:a,logPath:t.logPath,verdict:l.snapshotQuality,inspectFacts:t.inspectFacts,bindDevice:t.bindDevice}),m=o(f,p?{...f,fallbackScreenshotPath:p.path,artifacts:[p.artifact]}:f);return{data:u===void 0?m:o(m,{...m,refsGeneration:u}),record:{kind:`snapshot`,nodes:l.nodes.length,truncated:l.truncated}}}});return O(i,n)}function se(e,t){return e.internal?.observationOnly===!0?void 0:t?.snapshotGeneration}export{K as n,oe as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{C as t,h as n,m as r,w as i}from"./sdk-contracts.js";import"./capture.js";import{r as a}from"./snapshot-capture-annotations.js";import{c as o,m as s,n as c,s as l}from"./android-input-ownership.js";import{Ir as u,Mr as d,Pr as f,Ur as p,Vr as m}from"./sdk-batch.js";import{t as h}from"./snapshot-desktop-projection.js";import{a as g}from"./ios-snapshot-planning.js";function _(e,t,n){if(n?.(e.length+t.length)===!1)return;let r=v(t);if(r.length===0)return 0;let i=1/0,a=-1/0;for(let e of r)i=Math.min(i,e.x),a=Math.max(a,e.endX);let o=v(e).filter(e=>e.x<a&&e.endX>i);if(o.length===0)return 0;let s=[...r.flatMap(e=>[e.x,e.endX]),...o.flatMap(e=>[Math.max(e.x,i),Math.min(e.endX,a)])];if(n?.(r.length+o.length+s.length)===!1)return;r.sort(y),o.sort(y);let c=[...new Set(s)].sort((e,t)=>e-t),l=[],u=[],d=0,f=0,p=0,m=0;for(let e=0;e<c.length-1;e+=1){let t=c[e],i=c[e+1];for(l=l.filter(e=>e.endX>t),u=u.filter(e=>e.endX>t);d<r.length&&r[d].x<=t;)l.push(r[d]),d+=1;for(;f<o.length&&o[f].x<=t;)u.push(o[f]),f+=1;if(n?.(1+l.length+u.length)===!1)return;let a=b(l),s=b(u),h=i-t;p+=h*x(a),m+=h*S(a,s)}return p<=0?0:m/p}function v(e){return e.filter(p).map(e=>({...e,endX:e.x+e.width}))}function y(e,t){return e.x-t.x||e.endX-t.endX}function b(e){let t=e.map(e=>({start:e.y,end:e.y+e.height})).sort((e,t)=>e.start-t.start||e.end-t.end),n=[];for(let e of t){let t=n.at(-1);!t||e.start>t.end?n.push({...e}):t.end=Math.max(t.end,e.end)}return n}function x(e){return e.reduce((e,t)=>e+t.end-t.start,0)}function S(e,t){let n=0,r=0,i=0;for(;r<e.length&&i<t.length;){let a=e[r],o=t[i];n+=Math.max(0,Math.min(a.end,o.end)-Math.max(a.start,o.start)),a.end<=o.end?r+=1:i+=1}return n}function C(e,t=new Map){if(t.size===0)return new Set;let n=D(e),r=O(e,n),i={remaining:Math.max(1024,e.length*128),exhausted:!1},a=w(n,{footprints:r,siblingOrders:t,budget:i});return i.exhausted?new Set:L(a,n)}function w(e,t){let n=new Set;for(let r of e.values())for(let e of r)if(T(e,r,t)&&n.add(e.index),t.budget.exhausted)return n;return n}function T(e,t,n){let r=n.siblingOrders.get(e.index),i=n.footprints.get(e.index);if(!r||!i)return!1;for(let e of t){if(!F(n.budget))return!1;if(E(r,i,e,n))return!0}return!1}function E(e,t,n,r){let i=r.siblingOrders.get(n.index),a=r.footprints.get(n.index);if(!i||!a?.hasAction||i.group!==e.group||i.order<=e.order)return!1;let o=P(a,`paint`,r.budget),s=P(t,`show`,r.budget);if(r.budget.exhausted)return!1;let c=_(o,s,e=>I(r.budget,e));return c!==void 0&&c>=.9}function D(e){let t=new Map;for(let n of e){if(typeof n.parentIndex!=`number`)continue;let e=t.get(n.parentIndex)??[];e.push(n),t.set(n.parentIndex,e)}return t}function O(e,t){let n=new Map;for(let r=e.length-1;r>=0;--r){let i=e[r],a=t.get(i.index)??[],o=a.flatMap(e=>n.get(e.index)??[]);n.set(i.index,k(i,a.length,o))}return n}function k(e,t,n){let r=j(e,t),i=r??M(e);return{...i?{showRect:i}:{},showChildren:r?[]:n,...r?{paintRect:r}:{},paintChildren:r?[]:n,hasAction:e.hittable===!0||n.some(A)}}function A(e){return e.hasAction}function j(e,t){if(p(e.rect))return e.hittable===!0||m(e.type)||t===0&&N(e)?e.rect:void 0}function M(e){return p(e.rect)&&N(e)?e.rect:void 0}function N(e){return!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim())}function P(e,t,n){let r=[],i=[e];for(;i.length>0;){if(!F(n))return r;let e=i.pop(),a=t===`paint`?e.paintRect:e.showRect;a&&r.push(a),i.push(...t===`paint`?e.paintChildren:e.showChildren)}return r}function F(e){return I(e,1)}function I(e,t){return t>e.remaining?(e.exhausted=!0,!1):(e.remaining-=t,!0)}function L(e,t){let n=new Set,r=[...e];for(;r.length>0;){let e=r.pop();if(!n.has(e)){n.add(e);for(let n of t.get(e)??[])r.push(n.index)}}return n}function R(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;r.length>0&&e<=r.at(-1).depth;)r.pop();let o=i,s=typeof a.parentIndex==`number`?t.get(a.parentIndex):void 0,c=typeof s==`number`&&s<o?s:r.at(-1)?.index;n.push({...a,index:o,depth:e,parentIndex:c}),r.push({depth:e,index:o})}return n}function z(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t.at(-1);)t.pop();let i=u(r.type??``),a=f(d(r));if((i===`group`||i===`ioscontentgroup`)&&!a){t.push(e);continue}let o=Math.max(0,e-t.length);n.push({...r,depth:o})}return n}var B=e({buildSnapshotState:()=>V});function V(e,o){let s=e?.nodes??[],c=o?.snapshotRaw,u=H(e,s,c===!0),d=R(c?u:z(u)),f=o?.snapshotScope&&G(e?.backend)?h(d,o.snapshotScope):d,p=a(e).quality;return{nodes:r(c?f:l(f,U(e?.backend))),truncated:e?.truncated,createdAt:Date.now(),...i(e),...p?{snapshotQuality:p}:{},...e.comparisonIdentity?{comparisonKey:g(e.comparisonIdentity)}:{},...e.systemSurface?{iosSystemSurfaceBundleId:e.systemSurface.bundleId}:{},...e.targetActivation?{targetActivation:e.targetActivation}:{},...e.keyboard?{keyboard:e.keyboard}:{},presentationKey:n(t(o)),comparisonSafe:K(e?.backend,o)}}function H(e,t,n){return e.backend===`android`&&!n?W(e,t):t}function U(e){return e===`android`?{isAdditionalOverlayNode:c}:{}}function W(e,t){let n=s(e),r=C(n?.nodes??t,n?.androidSiblingOrderByNodeIndex);return o(t,e=>{let t=n?.sourceIndexByNodeIndex.get(e.index)??e.index;return r.has(t)})}function G(e){return e===void 0||e===`linux-atspi`||e===`harmonyos-arkui`||e===`web`}function K(e,t){return e===`android`&&t?.snapshotInteractiveOnly!==!0&&typeof t?.snapshotDepth!=`number`&&!t?.snapshotScope}export{B as n,V as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{T as t,h as n,m as r,w as i}from"./sdk-contracts.js";import"./capture.js";import{r as a}from"./snapshot-capture-annotations.js";import{c as o,m as s,n as c,s as l}from"./android-input-ownership.js";import{Ir as u,Mr as d,Pr as f,Vr as p,Wr as m}from"./sdk-batch.js";import{t as h}from"./snapshot-desktop-projection.js";import{a as g}from"./ios-snapshot-planning.js";function _(e,t,n){if(n?.(e.length+t.length)===!1)return;let r=v(t);if(r.length===0)return 0;let i=1/0,a=-1/0;for(let e of r)i=Math.min(i,e.x),a=Math.max(a,e.endX);let o=v(e).filter(e=>e.x<a&&e.endX>i);if(o.length===0)return 0;let s=[...r.flatMap(e=>[e.x,e.endX]),...o.flatMap(e=>[Math.max(e.x,i),Math.min(e.endX,a)])];if(n?.(r.length+o.length+s.length)===!1)return;r.sort(y),o.sort(y);let c=[...new Set(s)].sort((e,t)=>e-t),l=[],u=[],d=0,f=0,p=0,m=0;for(let e=0;e<c.length-1;e+=1){let t=c[e],i=c[e+1];for(l=l.filter(e=>e.endX>t),u=u.filter(e=>e.endX>t);d<r.length&&r[d].x<=t;)l.push(r[d]),d+=1;for(;f<o.length&&o[f].x<=t;)u.push(o[f]),f+=1;if(n?.(1+l.length+u.length)===!1)return;let a=b(l),s=b(u),h=i-t;p+=h*x(a),m+=h*S(a,s)}return p<=0?0:m/p}function v(e){return e.filter(m).map(e=>({...e,endX:e.x+e.width}))}function y(e,t){return e.x-t.x||e.endX-t.endX}function b(e){let t=e.map(e=>({start:e.y,end:e.y+e.height})).sort((e,t)=>e.start-t.start||e.end-t.end),n=[];for(let e of t){let t=n.at(-1);!t||e.start>t.end?n.push({...e}):t.end=Math.max(t.end,e.end)}return n}function x(e){return e.reduce((e,t)=>e+t.end-t.start,0)}function S(e,t){let n=0,r=0,i=0;for(;r<e.length&&i<t.length;){let a=e[r],o=t[i];n+=Math.max(0,Math.min(a.end,o.end)-Math.max(a.start,o.start)),a.end<=o.end?r+=1:i+=1}return n}function C(e,t=new Map){if(t.size===0)return new Set;let n=D(e),r=O(e,n),i={remaining:Math.max(1024,e.length*128),exhausted:!1},a=w(n,{footprints:r,siblingOrders:t,budget:i});return i.exhausted?new Set:L(a,n)}function w(e,t){let n=new Set;for(let r of e.values())for(let e of r)if(T(e,r,t)&&n.add(e.index),t.budget.exhausted)return n;return n}function T(e,t,n){let r=n.siblingOrders.get(e.index),i=n.footprints.get(e.index);if(!r||!i)return!1;for(let e of t){if(!F(n.budget))return!1;if(E(r,i,e,n))return!0}return!1}function E(e,t,n,r){let i=r.siblingOrders.get(n.index),a=r.footprints.get(n.index);if(!i||!a?.hasAction||i.group!==e.group||i.order<=e.order)return!1;let o=P(a,`paint`,r.budget),s=P(t,`show`,r.budget);if(r.budget.exhausted)return!1;let c=_(o,s,e=>I(r.budget,e));return c!==void 0&&c>=.9}function D(e){let t=new Map;for(let n of e){if(typeof n.parentIndex!=`number`)continue;let e=t.get(n.parentIndex)??[];e.push(n),t.set(n.parentIndex,e)}return t}function O(e,t){let n=new Map;for(let r=e.length-1;r>=0;--r){let i=e[r],a=t.get(i.index)??[],o=a.flatMap(e=>n.get(e.index)??[]);n.set(i.index,k(i,a.length,o))}return n}function k(e,t,n){let r=j(e,t),i=r??M(e);return{...i?{showRect:i}:{},showChildren:r?[]:n,...r?{paintRect:r}:{},paintChildren:r?[]:n,hasAction:e.hittable===!0||n.some(A)}}function A(e){return e.hasAction}function j(e,t){if(m(e.rect))return e.hittable===!0||p(e.type)||t===0&&N(e)?e.rect:void 0}function M(e){return m(e.rect)&&N(e)?e.rect:void 0}function N(e){return!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim())}function P(e,t,n){let r=[],i=[e];for(;i.length>0;){if(!F(n))return r;let e=i.pop(),a=t===`paint`?e.paintRect:e.showRect;a&&r.push(a),i.push(...t===`paint`?e.paintChildren:e.showChildren)}return r}function F(e){return I(e,1)}function I(e,t){return t>e.remaining?(e.exhausted=!0,!1):(e.remaining-=t,!0)}function L(e,t){let n=new Set,r=[...e];for(;r.length>0;){let e=r.pop();if(!n.has(e)){n.add(e);for(let n of t.get(e)??[])r.push(n.index)}}return n}function R(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;r.length>0&&e<=r.at(-1).depth;)r.pop();let o=i,s=typeof a.parentIndex==`number`?t.get(a.parentIndex):void 0,c=typeof s==`number`&&s<o?s:r.at(-1)?.index;n.push({...a,index:o,depth:e,parentIndex:c}),r.push({depth:e,index:o})}return n}function z(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t.at(-1);)t.pop();let i=u(r.type??``),a=f(d(r));if((i===`group`||i===`ioscontentgroup`)&&!a){t.push(e);continue}let o=Math.max(0,e-t.length);n.push({...r,depth:o})}return n}var B=e({buildSnapshotState:()=>V});function V(e,o){let s=e?.nodes??[],c=o?.snapshotRaw,u=H(e,s,c===!0),d=R(c?u:z(u)),f=o?.snapshotScope&&G(e?.backend)?h(d,o.snapshotScope):d,p=a(e).quality;return{nodes:r(c?f:l(f,U(e?.backend))),truncated:e?.truncated,createdAt:Date.now(),...t(e),...p?{snapshotQuality:p}:{},...e.comparisonIdentity?{comparisonKey:g(e.comparisonIdentity)}:{},...e.systemSurface?{iosSystemSurfaceBundleId:e.systemSurface.bundleId}:{},...e.targetActivation?{targetActivation:e.targetActivation}:{},...e.keyboard?{keyboard:e.keyboard}:{},presentationKey:n(i(o)),comparisonSafe:K(e?.backend,o)}}function H(e,t,n){return e.backend===`android`&&!n?W(e,t):t}function U(e){return e===`android`?{isAdditionalOverlayNode:c}:{}}function W(e,t){let n=s(e),r=C(n?.nodes??t,n?.androidSiblingOrderByNodeIndex);return o(t,e=>{let t=n?.sourceIndexByNodeIndex.get(e.index)??e.index;return r.has(t)})}function G(e){return e===void 0||e===`linux-atspi`||e===`harmonyos-arkui`||e===`web`}function K(e,t){return e===`android`&&t?.snapshotInteractiveOnly!==!0&&typeof t?.snapshotDepth!=`number`&&!t?.snapshotScope}export{B as n,V as t};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{t}from"./ttl-memo.js";import{m as n,x as r,y as i}from"./host-file.js";import{runHarmonyHdc as a,runHarmonyShell as o}from"./hdc.js";import s from"node:path";import{randomUUID as c}from"node:crypto";const l=t({ttlMs:2e3,scheduleExpiry:!0});async function u(e,t={}){let l=`/data/local/tmp/agent-device-layout-${c()}.json`,u=await n(`agent-device-harmony-layout-`),d=s.join(u,`layout.json`);try{return await o(e,[`uitest`,`dumpLayout`,`-p`,l],{timeoutMs:3e4}),await a(e,[`file`,`recv`,l,d],{timeoutMs:15e3}),m(p(await i(d)),t)}finally{await o(e,[`rm`,`-f`,l],{allowFailure:!0}).catch(()=>{}),await r(u)}}async function d(t){let n=t.id,r=l.get(n);if(r)return r;let i=(await u(t)).nodes.find(e=>e.type===`Application`&&e.rect)?.rect;if(!i||i.width<=0||i.height<=0)throw new e(`COMMAND_FAILED`,`HarmonyOS snapshot did not expose an application viewport`);return l.set(n,i),i}function f(e){l.delete(e.id)}function p(t){try{let e=JSON.parse(t);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`layout root is not an object`);return e}catch(t){throw new e(`COMMAND_FAILED`,`HarmonyOS uitest returned an invalid layout JSON document`,{cause:t instanceof Error?t.message:String(t)})}}function m(e,t){let{nodes:n,truncated:r,analysis:i}=h(e,{maxNodes:5e3,maxDepth:t.depth??1/0,interactiveOnly:t.interactiveOnly===!0});return{nodes:n,...r?{truncated:!0}:{},analysis:i}}function h(e,t){let n=[],r=0,i=0,a=!1,o=(e,s,c)=>{r+=1,i=Math.max(i,s);let l=c;if(n.length>=t.maxNodes)a=!0;else{let r=g(e.attributes??{},n.length,s,c);l=!t.interactiveOnly||r.hittable===!0?n.push(r)-1:c}if(s<t.maxDepth)for(let t of e.children??[])o(t,s+1,l)};return o(e,0),{nodes:n,truncated:a,analysis:{rawNodeCount:r,maxDepth:i}}}function g(e,t,n,r){let i=_(e,`text`)??_(e,`originalText`),a=_(e,`description`),o=_(e,`id`)??_(e,`key`),s=v(_(e,`bounds`));return{index:t,type:_(e,`type`)===`root`?`Application`:_(e,`type`),...a?{label:a}:{},...i?{value:i}:{},...o?{identifier:o}:{},...s?{rect:s}:{},enabled:_(e,`enabled`)!==`false`,focused:_(e,`focused`)===`true`,visibleToUser:_(e,`visible`)!==`false`,hittable:_(e,`clickable`)===`true`,depth:n,...r===void 0?{}:{parentIndex:r}}}function _(e,t){let n=e[t];return typeof n==`string`?n:void 0}function v(e){if(!e)return;let t=/^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(e);if(!t)return;let[,n,r,i,a]=t,o=Number(n),s=Number(r),c=Number(i)-o,l=Number(a)-s;return c>=0&&l>=0?{x:o,y:s,width:c,height:l}:void 0}export{f as invalidateHarmonyGestureViewport,d as readHarmonyGestureViewport,u as snapshotHarmony};
1
+ import{O as e}from"./sdk-contracts.js";import{t}from"./ttl-memo.js";import{m as n,x as r,y as i}from"./host-file.js";import{runHarmonyHdc as a,runHarmonyShell as o}from"./hdc.js";import s from"node:path";import{randomUUID as c}from"node:crypto";const l=t({ttlMs:2e3,scheduleExpiry:!0});async function u(e,t={}){let l=`/data/local/tmp/agent-device-layout-${c()}.json`,u=await n(`agent-device-harmony-layout-`),d=s.join(u,`layout.json`);try{return await o(e,[`uitest`,`dumpLayout`,`-p`,l],{timeoutMs:3e4}),await a(e,[`file`,`recv`,l,d],{timeoutMs:15e3}),m(p(await i(d)),t)}finally{await o(e,[`rm`,`-f`,l],{allowFailure:!0}).catch(()=>{}),await r(u)}}async function d(t){let n=t.id,r=l.get(n);if(r)return r;let i=(await u(t)).nodes.find(e=>e.type===`Application`&&e.rect)?.rect;if(!i||i.width<=0||i.height<=0)throw new e(`COMMAND_FAILED`,`HarmonyOS snapshot did not expose an application viewport`);return l.set(n,i),i}function f(e){l.delete(e.id)}function p(t){try{let e=JSON.parse(t);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`layout root is not an object`);return e}catch(t){throw new e(`COMMAND_FAILED`,`HarmonyOS uitest returned an invalid layout JSON document`,{cause:t instanceof Error?t.message:String(t)})}}function m(e,t){let{nodes:n,truncated:r,analysis:i}=h(e,{maxNodes:5e3,maxDepth:t.depth??1/0,interactiveOnly:t.interactiveOnly===!0});return{nodes:n,...r?{truncated:!0}:{},analysis:i}}function h(e,t){let n=[],r=0,i=0,a=!1,o=(e,s,c)=>{r+=1,i=Math.max(i,s);let l=c;if(n.length>=t.maxNodes)a=!0;else{let r=g(e.attributes??{},n.length,s,c);l=!t.interactiveOnly||r.hittable===!0?n.push(r)-1:c}if(s<t.maxDepth)for(let t of e.children??[])o(t,s+1,l)};return o(e,0),{nodes:n,truncated:a,analysis:{rawNodeCount:r,maxDepth:i}}}function g(e,t,n,r){let i=_(e,`text`)??_(e,`originalText`),a=_(e,`description`),o=_(e,`id`)??_(e,`key`),s=v(_(e,`bounds`));return{index:t,type:_(e,`type`)===`root`?`Application`:_(e,`type`),...a?{label:a}:{},...i?{value:i}:{},...o?{identifier:o}:{},...s?{rect:s}:{},enabled:_(e,`enabled`)!==`false`,focused:_(e,`focused`)===`true`,visibleToUser:_(e,`visible`)!==`false`,hittable:_(e,`clickable`)===`true`,depth:n,...r===void 0?{}:{parentIndex:r}}}function _(e,t){let n=e[t];return typeof n==`string`?n:void 0}function v(e){if(!e)return;let t=/^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(e);if(!t)return;let[,n,r,i,a]=t,o=Number(n),s=Number(r),c=Number(i)-o,l=Number(a)-s;return c>=0&&l>=0?{x:o,y:s,width:c,height:l}:void 0}export{f as invalidateHarmonyGestureViewport,d as readHarmonyGestureViewport,u as snapshotHarmony};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import{d as n}from"./owner-identity.js";import"./diagnostics2.js";import"./process.js";import{c as r}from"./host-file.js";import{n as i,t as a}from"./tool-provider2.js";import o from"node:path";import{fileURLToPath as s}from"node:url";const c={"push button":`Button`,"toggle button":`Button`,"push button menu":`Button`,label:`StaticText`,static:`StaticText`,caption:`StaticText`,text:`TextField`,entry:`TextField`,"password text":`TextField`,"spin button":`TextField`,terminal:`TextArea`,"document text":`TextArea`,paragraph:`TextArea`,frame:`Window`,window:`Window`,dialog:`Dialog`,alert:`Alert`,"file chooser":`Dialog`,"color chooser":`Dialog`,"font chooser":`Dialog`,panel:`Group`,filler:`Group`,section:`Group`,form:`Group`,grouping:`Group`,"layered pane":`Group`,"glass pane":`Group`,"root pane":`Group`,"option pane":`Group`,"internal frame":`Group`,"desktop frame":`Group`,"block quote":`Group`,article:`Group`,comment:`Group`,landmark:`Group`,log:`Group`,marquee:`Group`,math:`Group`,notification:`Group`,"content deletion":`Group`,"content insertion":`Group`,mark:`Group`,suggestion:`Group`,"scroll pane":`ScrollArea`,"scroll bar":`ScrollBar`,"menu bar":`MenuBar`,menu:`Menu`,"popup menu":`Menu`,"menu item":`MenuItem`,"check menu item":`MenuItem`,"radio menu item":`MenuItem`,"tearoff menu item":`MenuItem`,"check box":`CheckBox`,"radio button":`RadioButton`,switch:`Switch`,"combo box":`ComboBox`,"page tab":`Tab`,"page tab list":`TabList`,table:`Table`,"tree table":`Table`,"table cell":`Cell`,"table row":`Row`,"table column header":`Cell`,"table row header":`Cell`,"column header":`Cell`,"row header":`Cell`,list:`List`,"list item":`ListItem`,"list box":`List`,tree:`Tree`,"tree item":`TreeItem`,"description list":`List`,"description term":`ListItem`,"description value":`ListItem`,"tool bar":`Toolbar`,"status bar":`StatusBar`,"info bar":`StatusBar`,slider:`Slider`,"progress bar":`ProgressBar`,"level bar":`ProgressBar`,image:`Image`,icon:`Image`,animation:`Image`,canvas:`Image`,"drawing area":`Image`,video:`Video`,audio:`Audio`,link:`Link`,hyperlink:`Link`,separator:`Separator`,application:`Application`,"tool tip":`Tooltip`,timer:`Timer`,heading:`Heading`,footnote:`Footnote`,"title bar":`TitleBar`,"date editor":`DateEditor`,rating:`Slider`};function l(e){let t=e.toLowerCase().trim();return c[t]||t.split(/[\s_-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}const u=`atspi-dump.py`;let d=null;function f(){if(d)return d;let t=o.dirname(s(import.meta.url));for(let e=0;e<6;e++){let e=o.join(t,`linux`,u);if(r(e))return d=e,e;t=o.dirname(t)}throw new e(`TOOL_MISSING`,`Cannot find ${u}. Ensure the agent-device package is installed correctly.`)}async function p(t,r={}){let o=a().accessibility;if(o)return await o.captureTree(t,r);if(n()!==`linux`)throw new e(`UNSUPPORTED_PLATFORM`,`AT-SPI2 bridge is only available on Linux`);if(!await a().whichCommand(`python3`))throw new e(`TOOL_MISSING`,`python3 is required for AT-SPI2 accessibility snapshots on Linux.`);let s=r.maxNodes??1500,c=r.maxDepth??12,u=r.maxApps??24,d=[f(),`--surface`,t,`--max-nodes`,String(s),`--max-depth`,String(c),`--max-apps`,String(u)],p=await i(`python3`,d,{allowFailure:!0,timeoutMs:3e4,signal:r.signal});if(p.exitCode!==0){let t=p.stderr.trim();throw t.includes(`No module named`)||t.includes(`gi.require_version`)?new e(`TOOL_MISSING`,`AT-SPI2 Python bindings not found. Install python3-gi and gir1.2-atspi-2.0.`,{cause:t}):new e(`COMMAND_FAILED`,`AT-SPI2 snapshot failed (exit ${p.exitCode}): ${t||p.stdout}`)}let m;try{m=JSON.parse(p.stdout)}catch{throw new e(`COMMAND_FAILED`,`AT-SPI2 snapshot returned invalid JSON: ${p.stdout.slice(0,200)}`)}if(m.error)throw new e(`COMMAND_FAILED`,`AT-SPI2: ${m.error}`);return{nodes:(m.nodes??[]).map(e=>({index:e.index,type:l(e.role),role:e.role,label:e.label??void 0,value:e.value??void 0,rect:e.rect??void 0,enabled:e.enabled??void 0,selected:e.selected??void 0,hittable:e.hittable??void 0,depth:e.depth,parentIndex:e.parentIndex??void 0,pid:e.pid??void 0,appName:e.appName??void 0,windowTitle:e.windowTitle??void 0})),truncated:m.truncated,surface:t}}function m(e){return e===`desktop`?`desktop`:e===`frontmost-app`||e===`app`?`frontmost-app`:(e===`menubar`&&t({level:`warn`,phase:`linux_snapshot`,data:{message:`menubar surface is not supported on Linux, falling back to desktop`}}),`desktop`)}async function h(e,t){let n=await p(m(e),{signal:t});return{nodes:n.nodes,truncated:n.truncated}}async function g(e,t,n){let{nodes:r}=await h(n),i=r.filter(n=>{let r=n.rect;return r?e>=r.x&&t>=r.y&&e<=r.x+r.width&&t<=r.y+r.height:!1}).sort((e,t)=>{let n=e.depth??0,r=t.depth??0;return n===r?_(e.rect)-_(t.rect):r-n});for(let e of i){let t=v(e);if(t.trim())return t}return``}function _(e){return(e?.width??0)*(e?.height??0)}function v(e){for(let t of[e.value,e.label,e.identifier])if(typeof t==`string`&&t.length>0)return t;return``}export{g as readLinuxTextAtPoint,h as snapshotLinux};
1
+ import{O as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import{d as n}from"./owner-identity.js";import"./diagnostics2.js";import"./process.js";import{c as r}from"./host-file.js";import{n as i,t as a}from"./tool-provider2.js";import o from"node:path";import{fileURLToPath as s}from"node:url";const c={"push button":`Button`,"toggle button":`Button`,"push button menu":`Button`,label:`StaticText`,static:`StaticText`,caption:`StaticText`,text:`TextField`,entry:`TextField`,"password text":`TextField`,"spin button":`TextField`,terminal:`TextArea`,"document text":`TextArea`,paragraph:`TextArea`,frame:`Window`,window:`Window`,dialog:`Dialog`,alert:`Alert`,"file chooser":`Dialog`,"color chooser":`Dialog`,"font chooser":`Dialog`,panel:`Group`,filler:`Group`,section:`Group`,form:`Group`,grouping:`Group`,"layered pane":`Group`,"glass pane":`Group`,"root pane":`Group`,"option pane":`Group`,"internal frame":`Group`,"desktop frame":`Group`,"block quote":`Group`,article:`Group`,comment:`Group`,landmark:`Group`,log:`Group`,marquee:`Group`,math:`Group`,notification:`Group`,"content deletion":`Group`,"content insertion":`Group`,mark:`Group`,suggestion:`Group`,"scroll pane":`ScrollArea`,"scroll bar":`ScrollBar`,"menu bar":`MenuBar`,menu:`Menu`,"popup menu":`Menu`,"menu item":`MenuItem`,"check menu item":`MenuItem`,"radio menu item":`MenuItem`,"tearoff menu item":`MenuItem`,"check box":`CheckBox`,"radio button":`RadioButton`,switch:`Switch`,"combo box":`ComboBox`,"page tab":`Tab`,"page tab list":`TabList`,table:`Table`,"tree table":`Table`,"table cell":`Cell`,"table row":`Row`,"table column header":`Cell`,"table row header":`Cell`,"column header":`Cell`,"row header":`Cell`,list:`List`,"list item":`ListItem`,"list box":`List`,tree:`Tree`,"tree item":`TreeItem`,"description list":`List`,"description term":`ListItem`,"description value":`ListItem`,"tool bar":`Toolbar`,"status bar":`StatusBar`,"info bar":`StatusBar`,slider:`Slider`,"progress bar":`ProgressBar`,"level bar":`ProgressBar`,image:`Image`,icon:`Image`,animation:`Image`,canvas:`Image`,"drawing area":`Image`,video:`Video`,audio:`Audio`,link:`Link`,hyperlink:`Link`,separator:`Separator`,application:`Application`,"tool tip":`Tooltip`,timer:`Timer`,heading:`Heading`,footnote:`Footnote`,"title bar":`TitleBar`,"date editor":`DateEditor`,rating:`Slider`};function l(e){let t=e.toLowerCase().trim();return c[t]||t.split(/[\s_-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}const u=`atspi-dump.py`;let d=null;function f(){if(d)return d;let t=o.dirname(s(import.meta.url));for(let e=0;e<6;e++){let e=o.join(t,`linux`,u);if(r(e))return d=e,e;t=o.dirname(t)}throw new e(`TOOL_MISSING`,`Cannot find ${u}. Ensure the agent-device package is installed correctly.`)}async function p(t,r={}){let o=a().accessibility;if(o)return await o.captureTree(t,r);if(n()!==`linux`)throw new e(`UNSUPPORTED_PLATFORM`,`AT-SPI2 bridge is only available on Linux`);if(!await a().whichCommand(`python3`))throw new e(`TOOL_MISSING`,`python3 is required for AT-SPI2 accessibility snapshots on Linux.`);let s=r.maxNodes??1500,c=r.maxDepth??12,u=r.maxApps??24,d=[f(),`--surface`,t,`--max-nodes`,String(s),`--max-depth`,String(c),`--max-apps`,String(u)],p=await i(`python3`,d,{allowFailure:!0,timeoutMs:3e4,signal:r.signal});if(p.exitCode!==0){let t=p.stderr.trim();throw t.includes(`No module named`)||t.includes(`gi.require_version`)?new e(`TOOL_MISSING`,`AT-SPI2 Python bindings not found. Install python3-gi and gir1.2-atspi-2.0.`,{cause:t}):new e(`COMMAND_FAILED`,`AT-SPI2 snapshot failed (exit ${p.exitCode}): ${t||p.stdout}`)}let m;try{m=JSON.parse(p.stdout)}catch{throw new e(`COMMAND_FAILED`,`AT-SPI2 snapshot returned invalid JSON: ${p.stdout.slice(0,200)}`)}if(m.error)throw new e(`COMMAND_FAILED`,`AT-SPI2: ${m.error}`);return{nodes:(m.nodes??[]).map(e=>({index:e.index,type:l(e.role),role:e.role,label:e.label??void 0,value:e.value??void 0,rect:e.rect??void 0,enabled:e.enabled??void 0,selected:e.selected??void 0,hittable:e.hittable??void 0,depth:e.depth,parentIndex:e.parentIndex??void 0,pid:e.pid??void 0,appName:e.appName??void 0,windowTitle:e.windowTitle??void 0})),truncated:m.truncated,surface:t}}function m(e){return e===`desktop`?`desktop`:e===`frontmost-app`||e===`app`?`frontmost-app`:(e===`menubar`&&t({level:`warn`,phase:`linux_snapshot`,data:{message:`menubar surface is not supported on Linux, falling back to desktop`}}),`desktop`)}async function h(e,t){let n=await p(m(e),{signal:t});return{nodes:n.nodes,truncated:n.truncated}}async function g(e,t,n){let{nodes:r}=await h(n),i=r.filter(n=>{let r=n.rect;return r?e>=r.x&&t>=r.y&&e<=r.x+r.width&&t<=r.y+r.height:!1}).sort((e,t)=>{let n=e.depth??0,r=t.depth??0;return n===r?_(e.rect)-_(t.rect):r-n});for(let e of i){let t=v(e);if(t.trim())return t}return``}function _(e){return(e?.width??0)*(e?.height??0)}function v(e){for(let t of[e.value,e.label,e.identifier])if(typeof t==`string`&&t.length>0)return t;return``}export{g as readLinuxTextAtPoint,h as snapshotLinux};
@@ -1 +1 @@
1
- import{D as e,o as t}from"./sdk-contracts.js";import{f as n,l as r,u as i,w as a}from"./sdk-device.js";import{$ as o,Ht as s,Ir as c,Rt as l,Vt as u,et as d,nt as f,on as p,pr as m,sn as h,tt as g}from"./sdk-batch.js";import"./session-store.js";import{M as _,g as v,k as y,m as b,p as x,r as S,s as C}from"./session-snapshot.js";import{k as w}from"./runtime.js";import{i as ee,r as T}from"./success-text.js";import"./alert-contract.js";import{b as te,c as ne,f as re,g as E,h as ie,m as ae,p as oe,r as D,t as O}from"./location-coordinates.js";import{a as se,t as k}from"./absence-observation-errors.js";import{r as A}from"./diagnostics.js";import"./diagnostics2.js";import{h as j}from"./screenshot-runtime.js";import{n as M,t as N}from"./capture-disclosure.js";import{n as P,t as F}from"./snapshot-runtime.js";import{a as I,i as L,o as R}from"./snapshot-runtime-binding.js";import{a as z,c as B,f as V,g as H,h as U,m as W,o as G,p as K,s as ce,t as le}from"./selector-runtime.js";async function ue(e){let{device:t,action:n,inspectFacts:r,bindDevice:i}=e,a={command:`alert`,device:t,inspectFacts:r,bindDevice:i,...e.session?{}:{readiness:{}}};if(n===`wait`){let e=await v({...a,use:f});if(e.type===`response`)return{ok:!1,response:e.response};let t=e.runtime;return{ok:!0,execute:e=>fe(t,e)}}if(n===`accept`){let e=await v({...a,use:o});if(e.type===`response`)return{ok:!1,response:e.response};let t=e.runtime;return{ok:!0,execute:e=>pe(t,e)}}if(n===`dismiss`){let e=await v({...a,use:d});if(e.type===`response`)return{ok:!1,response:e.response};let t=e.runtime;return{ok:!0,execute:e=>me(t,e)}}let s=await v({...a,use:g});if(s.type===`response`)return{ok:!1,response:s.response};let c=s.runtime;return{ok:!0,execute:e=>de(c,e)}}async function de(e,t){return await e.operations.readAlert(t)}async function fe(e,t){return await e.operations.awaitAlert(t)}async function pe(e,t){return await e.operations.acceptAlert(t)}async function me(e,t){return await e.operations.dismissAlert(t)}async function he(e){let{req:t,logPath:n,sessionStore:r,session:i,device:a,inspectFacts:o,bindDevice:s}=e,c=await ue({device:a,action:_e(t.positionals?.[0]),session:i,inspectFacts:o,bindDevice:s});if(!c.ok)return c.response;i&&j(t)===`may-invalidate`&&_(i);let l=y(n,t.flags,i?.appBundleId,i?.trace?.outPath),u=await c.execute({timeoutMs:h(t.positionals?.[1])??1e4,...ge(i),execution:b(l)});return L(r,i,t,u),{ok:!0,data:u}}function ge(e){return{...e?.appBundleId===void 0?{}:{appBundleId:e.appBundleId},...e?.surface===void 0?{}:{surface:e.surface}}}function _e(e){return e===`accept`||e===`dismiss`||e===`wait`?e:`get`}function ve(e){let n=e.positionals?.[0]?.toLowerCase(),r=e.positionals?.[1]?.toLowerCase(),i=e.positionals?.[2]?.toLowerCase();if(n===`clear-app-state`)return{ok:!0,parsed:{leg:`write`,args:{setting:n,state:`clear`,appBundleId:r===`clear`?e.positionals?.[2]:e.positionals?.[1]}}};let a=l(e.positionals);if(a.kind===`read`)return{ok:!0,parsed:{leg:`read`,setting:a.setting}};if(!n||!r||n===`permission`&&!i||n===`location`&&r===`set`&&(!e.positionals?.[2]||!e.positionals?.[3])||n===`reset-keychain`&&e.positionals?.[2]!==void 0)return t(`INVALID_ARGS`,ne);let o=r;if(n===`text-size`){let e=te(r);if(e===void 0)return t(`INVALID_ARGS`,ie(r));o=e}return{ok:!0,parsed:{leg:`write`,args:{setting:n,state:o,permissionTarget:i,permissionMode:e.positionals?.[3],latitude:e.positionals?.[2],longitude:e.positionals?.[3]}}}}function q(e){if(e.setting===`permission`)return{permissionTarget:e.permissionTarget,permissionMode:e.permissionMode};if(e.setting===`location`&&e.state===`set`)return{latitude:O(e.latitude,`latitude`),longitude:O(e.longitude,`longitude`)}}function ye(e,t,n){let{setting:r,state:i}=e;return r===`clear-app-state`?{setting:`clear-app-state`,state:`clear`,appBundleId:t,platform:n}:r===`location`&&i===`set`?{setting:r,state:i,latitude:e.latitude,longitude:e.longitude,platform:n}:r===`permission`?{setting:r,state:i,permissionTarget:e.permissionTarget,permissionMode:e.permissionMode,platform:n}:{setting:r,state:i,appBundleId:t,platform:n}}function be(e){return typeof e.message==`string`&&e.message.length>0?e.message:void 0}async function xe(e,t,n){let{setting:r,state:i}=t,a=await e.operations.setSetting(t);return a&&typeof a==`object`?ee({setting:r,state:i,...a},be(a)??n):{setting:r,state:i,...T(n)}}async function Se(e){return e.parsed.leg===`read`?await Ce(e,e.parsed.setting):await we(e,e.parsed.args)}async function Ce(e,t){let{req:n,logPath:r,sessionStore:i,session:a,device:o,inspectFacts:s,bindDevice:c}=e,l=J(o,t);if(l!==void 0)return l;let d=await v({command:`settings ${t}`,device:o,use:u,inspectFacts:s,bindDevice:c,...a?{}:{readiness:{}}});if(d.type===`response`)return d.response;A({level:`debug`,phase:`settings_read`,data:{setting:t,platform:o.platform}});let f=y(r,n.flags,a?.appBundleId,a?.trace?.outPath),p=await d.runtime.operations.readSetting({setting:t,execution:b(f)}),m={...p,...T(re(p))};return L(i,a,n,m),{ok:!0,data:m}}async function we(e,t){let{req:n,logPath:r,sessionStore:i,session:a,device:o,inspectFacts:c,bindDevice:l}=e,{setting:u,state:d}=t,f=J(o,u);if(f!==void 0)return f;let p=await v({command:`settings`,device:o,use:s,inspectFacts:c,bindDevice:l,...a?{}:{readiness:{}}}),m=Te(n,t,a);if(p.type===`response`)return p.response;let h=Ee(t,m);if(h!==void 0)return h;a&&_(a),A({level:`debug`,phase:`settings_apply`,data:ye(t,m,o.platform)});let g=await xe(p.runtime,De(t,m,y(r,n.flags,m,a?.trace?.outPath)),oe(u,d,m));return L(i,a,n,g),{ok:!0,data:g}}function J(e,o){if(n(e)&&!E(o))return t(`INVALID_ARGS`,ae(o));if(o===`text-size`&&r(e.platform)&&!i(e))return t(`UNSUPPORTED_OPERATION`,D.message,{deviceKind:e.kind,appleOs:a(e),reason:D.reason},{hint:D.hint})}function Te(e,t,n){return t.appBundleId??e.internal?.settingsAppBundleId??n?.appBundleId}function Ee(e,n){if(e.setting===`clear-app-state`&&!n)return t(`INVALID_ARGS`,`settings clear-app-state requires an app id when no app is bound to the session`)}function De(e,t,n){let r=q(e);return{setting:e.setting,state:e.state,...t===void 0?{}:{appBundleId:t},...r===void 0?{}:{options:r},execution:b(n)}}async function Oe(e){return await P({...e,command:`diff`,execute:async({runtime:e,sessionName:t,req:n,snapshotScope:r})=>{let i=await e.capture.diffSnapshot({session:t,interactiveOnly:n.flags?.snapshotInteractiveOnly,depth:n.flags?.snapshotDepth,scope:r,raw:n.flags?.snapshotRaw});return{data:i,record:{kind:`diff`,mode:`snapshot`,baselineInitialized:i.baselineInitialized,summary:i.summary}}}})}function ke(e){return e!==`sleep`}const Ae=[`application`,`window`,`tabbar`,`scrollbar`,`image`],je=new Set([`tab bar`]);async function Me(e,n){if(n.ok||!Ne(n.error.details?.reason)||n.error.details?.captureStalled===!0||n.error.details?.captureTruncated===!0)return n;let r=await Pe(e).catch(()=>null);return r?t(n.error.code,`${n.error.message}. Current surface: ${r.summary}.`,{...n.error.details??{},currentSurface:r.details}):n}function Ne(e){return e===w.targetAbsent||e===w.stableTimeout}async function Pe(e){let t={...e.req.flags,snapshotInteractiveOnly:!0},n=await C({device:e.device,session:e.session,flags:t,logPath:e.logPath??``,captureData:async()=>await e.capture(x({flags:t,logPath:e.logPath??``,meta:e.req.meta,session:e.session,snapshotScope:void 0}))});N(e.activationProof,n.snapshot);let r=[...n.snapshot.nodes].sort(Fe),i=Y(r,6,{includeIdentifiers:!0});if(i.length===0)return null;let a=Y(r.filter(e=>!Q(e)),4,{includeIdentifiers:!1}),o=Y(r.filter(Le),4,{includeIdentifiers:!0});return{summary:(a.length>0?a:i.slice(0,4)).join(`, `),details:{labels:i,...o.length>0?{buttons:o}:{}}}}function Y(e,t,n){let r=new Set,i=[];for(let a of e){let e=Z(a,n);if(!(!e||r.has(e))&&(r.add(e),i.push(e),i.length>=t))break}return i}function Fe(e,t){return X(e)-X(t)||Ie(e,t)}function X(e){let t=!!Z(e,{includeIdentifiers:!1});return(Q(e)?2:0)+ +!t}function Ie(e,t){return e.rect&&t.rect?e.rect.y-t.rect.y||e.rect.x-t.rect.x:e.rect?-1:t.rect?1:(e.depth??0)-(t.depth??0)||e.index-t.index}function Z(e,t){let n=(t.includeIdentifiers?[e.label,e.value,e.identifier]:[e.label,e.value]).map(e=>typeof e==`string`?e.trim():``).find(e=>e.length>0);return n?n.replaceAll(/\s+/g,` `).slice(0,80):``}function Q(e){let t=c(`${e.type??``} ${e.role??``} ${e.subrole??``}`),n=`${e.label??``} ${e.value??``}`.trim().toLowerCase();return Ae.some(e=>t.includes(e))||je.has(n)||n.endsWith(`.fill`)}function Le(e){let t=`${e.type??``} ${e.role??``} ${e.subrole??``}`;return c(t).includes(`button`)}async function Re(e){let{req:t,sessionName:n,sessionStore:r}=e,i=ze(t);if(`ok`in i)return i;let a=i,{session:o,device:s}=await I(r,n,t.flags),c=await Be(e,a,o,s);if(c&&`ok`in c)return c;let l=c,u=t.internal?.replayLandmarkGuard,d=Ve(a,o);if(`ok`in d)return d;let{waitParsed:f,staleRefsWarning:p}=d;return e.consumedSnapshot??={},e.activationProof??={},a.kind===`sleep`?await $(e,f,o,s,l,p,u):M({response:await R(o,s,()=>$(e,f,o,s,l,p,u),e.platformResourceCleanup),consumedTree:le(e),activationProof:e.activationProof})}function ze(e){let n=p(e.positionals??[]);if(!n)return t(`INVALID_ARGS`,`wait requires a duration or text`);if(n.kind===`invalid`)return t(`INVALID_ARGS`,n.message);if(n.kind!==`absent`)return n;let r=se({depth:e.flags?.snapshotDepth,scope:e.flags?.snapshotScope});if(!r)return n;let i=k(r,`wait`);return t(i.code,i.message,i.details)}async function Be(e,t,n,r){if(!ke(t.kind))return;let i=await V({command:`wait`,device:r,session:n,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return i.ok?i.operations:i.response}function Ve(e,t){if(e.kind!==`ref`)return{waitParsed:e};let n=H(e.rawRef);return n.ok?{waitParsed:{...e,rawRef:n.ref},staleRefsWarning:S({session:t,ref:n.ref,mintedGeneration:n.generation})}:n.response}async function $(e,t,n,r,i,a,o){let{req:s,sessionName:c,sessionStore:l}=e,u=B({...e,session:n,device:r,bound:i}),d=await ce(async()=>{let e=await u.selectors.wait({session:c,requestId:s.meta?.requestId,target:He(t,n,o)}),r=G(e);K(l,c,s,W(e),r,`landmark`);let i=U(e);return a?{...i,warning:a}:i}),f=i?await Me({req:s,logPath:e.logPath,session:n,device:r,capture:i.capture,activationProof:e.activationProof},d):d;return await z(e,f,`wait`)}function He(e,t,n){switch(e.kind){case`sleep`:return{kind:`sleep`,durationMs:e.durationMs};case`selector`:return{kind:`selector`,selector:e.selectorExpression,timeoutMs:e.timeoutMs,...n?{recordedLandmark:n}:{}};case`absent`:return{kind:`absent`,selector:e.selectorExpression,timeoutMs:e.timeoutMs};case`ref`:return We(e,t);case`stable`:return{kind:`stable`,quietMs:e.quietMs,timeoutMs:e.timeoutMs};case`text`:return Ge(e);default:return Ue(e)}}function Ue(e){throw Error(`Unsupported wait positional target: ${String(e)}`)}function We(t,n){if(!n?.snapshot)throw new e(`INVALID_ARGS`,`Ref wait requires an existing snapshot in session.`);return{kind:`ref`,ref:t.rawRef,timeoutMs:t.timeoutMs}}function Ge(t){let n=m(t.text);if(!n.ok)throw new e(n.code,n.message);return{kind:`text`,text:n.text,timeoutMs:t.timeoutMs}}const Ke={snapshot:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>await F({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o}),diff:async({req:e,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformResourceCleanup:s})=>e.positionals?.[0]===`snapshot`?await Oe({req:e,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformResourceCleanup:s}):t(`INVALID_ARGS`,`diff currently supports only: diff snapshot`),wait:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>await Re({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o}),alert:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>{let{session:s,device:c}=await I(r,t,e.flags);return await R(s,c,async()=>await he({req:e,logPath:n,sessionStore:r,session:s,device:c,inspectFacts:i,bindDevice:a}),o)},settings:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>{let s=ve(e);if(!s.ok)return s;let{session:c,device:l}=await I(r,t,e.flags);return await R(c,l,async()=>await Se({req:e,logPath:n,sessionStore:r,session:c,device:l,parsed:s.parsed,inspectFacts:i,bindDevice:a}),o)}};async function qe(e){let t=e.req.command,n=Ke[t];return n?await n(e):null}export{qe as handleSnapshotCommands};
1
+ import{O as e,o as t}from"./sdk-contracts.js";import{f as n,l as r,u as i,w as a}from"./sdk-device.js";import{$ as o,Ht as s,Ir as c,Rt as l,Vt as u,et as d,nt as f,on as p,pr as m,sn as h,tt as g}from"./sdk-batch.js";import"./session-store.js";import{B as _,L as v,g as y,m as b,p as x,r as S,s as C}from"./session-snapshot.js";import{k as w}from"./runtime.js";import{i as ee,r as T}from"./success-text.js";import"./alert-contract.js";import{b as te,c as ne,f as re,g as E,h as ie,m as ae,p as oe,r as D,t as O}from"./location-coordinates.js";import{a as se,t as k}from"./absence-observation-errors.js";import{r as A}from"./diagnostics.js";import"./diagnostics2.js";import{h as j}from"./screenshot-runtime.js";import{n as M,t as N}from"./capture-disclosure.js";import{n as P,t as F}from"./snapshot-runtime.js";import{a as I,i as L,o as R}from"./snapshot-runtime-binding.js";import{a as z,c as B,f as V,g as H,h as U,m as W,o as G,p as K,s as ce,t as le}from"./selector-runtime.js";async function ue(e){let{device:t,action:n,inspectFacts:r,bindDevice:i}=e,a={command:`alert`,device:t,inspectFacts:r,bindDevice:i,readiness:!e.session};if(n===`wait`){let e=await y({...a,use:f});if(e.type===`response`)return{ok:!1,response:e.response};let t=e.runtime;return{ok:!0,execute:e=>fe(t,e)}}if(n===`accept`){let e=await y({...a,use:o});if(e.type===`response`)return{ok:!1,response:e.response};let t=e.runtime;return{ok:!0,execute:e=>pe(t,e)}}if(n===`dismiss`){let e=await y({...a,use:d});if(e.type===`response`)return{ok:!1,response:e.response};let t=e.runtime;return{ok:!0,execute:e=>me(t,e)}}let s=await y({...a,use:g});if(s.type===`response`)return{ok:!1,response:s.response};let c=s.runtime;return{ok:!0,execute:e=>de(c,e)}}async function de(e,t){return await e.operations.readAlert(t)}async function fe(e,t){return await e.operations.awaitAlert(t)}async function pe(e,t){return await e.operations.acceptAlert(t)}async function me(e,t){return await e.operations.dismissAlert(t)}async function he(e){let{req:t,logPath:n,sessionStore:r,session:i,device:a,inspectFacts:o,bindDevice:s}=e,c=await ue({device:a,action:_e(t.positionals?.[0]),session:i,inspectFacts:o,bindDevice:s});if(!c.ok)return c.response;i&&j(t)===`may-invalidate`&&_(i);let l=v(n,t.flags,i?.appBundleId,i?.trace?.outPath),u=await c.execute({timeoutMs:h(t.positionals?.[1])??1e4,...ge(i),execution:b(l)});return L(r,i,t,u),{ok:!0,data:u}}function ge(e){return{...e?.appBundleId===void 0?{}:{appBundleId:e.appBundleId},...e?.surface===void 0?{}:{surface:e.surface}}}function _e(e){return e===`accept`||e===`dismiss`||e===`wait`?e:`get`}function ve(e){let n=e.positionals?.[0]?.toLowerCase(),r=e.positionals?.[1]?.toLowerCase(),i=e.positionals?.[2]?.toLowerCase();if(n===`clear-app-state`)return{ok:!0,parsed:{leg:`write`,args:{setting:n,state:`clear`,appBundleId:r===`clear`?e.positionals?.[2]:e.positionals?.[1]}}};let a=l(e.positionals);if(a.kind===`read`)return{ok:!0,parsed:{leg:`read`,setting:a.setting}};if(!n||!r||n===`permission`&&!i||n===`location`&&r===`set`&&(!e.positionals?.[2]||!e.positionals?.[3])||n===`reset-keychain`&&e.positionals?.[2]!==void 0)return t(`INVALID_ARGS`,ne);let o=r;if(n===`text-size`){let e=te(r);if(e===void 0)return t(`INVALID_ARGS`,ie(r));o=e}return{ok:!0,parsed:{leg:`write`,args:{setting:n,state:o,permissionTarget:i,permissionMode:e.positionals?.[3],latitude:e.positionals?.[2],longitude:e.positionals?.[3]}}}}function q(e){if(e.setting===`permission`)return{permissionTarget:e.permissionTarget,permissionMode:e.permissionMode};if(e.setting===`location`&&e.state===`set`)return{latitude:O(e.latitude,`latitude`),longitude:O(e.longitude,`longitude`)}}function ye(e,t,n){let{setting:r,state:i}=e;return r===`clear-app-state`?{setting:`clear-app-state`,state:`clear`,appBundleId:t,platform:n}:r===`location`&&i===`set`?{setting:r,state:i,latitude:e.latitude,longitude:e.longitude,platform:n}:r===`permission`?{setting:r,state:i,permissionTarget:e.permissionTarget,permissionMode:e.permissionMode,platform:n}:{setting:r,state:i,appBundleId:t,platform:n}}function be(e){return typeof e.message==`string`&&e.message.length>0?e.message:void 0}async function xe(e,t,n){let{setting:r,state:i}=t,a=await e.operations.setSetting(t);return a&&typeof a==`object`?ee({setting:r,state:i,...a},be(a)??n):{setting:r,state:i,...T(n)}}async function Se(e){return e.parsed.leg===`read`?await Ce(e,e.parsed.setting):await we(e,e.parsed.args)}async function Ce(e,t){let{req:n,logPath:r,sessionStore:i,session:a,device:o,inspectFacts:s,bindDevice:c}=e,l=J(o,t);if(l!==void 0)return l;let d=await y({command:`settings ${t}`,device:o,use:u,inspectFacts:s,bindDevice:c,readiness:!a});if(d.type===`response`)return d.response;A({level:`debug`,phase:`settings_read`,data:{setting:t,platform:o.platform}});let f=v(r,n.flags,a?.appBundleId,a?.trace?.outPath),p=await d.runtime.operations.readSetting({setting:t,execution:b(f)}),m={...p,...T(re(p))};return L(i,a,n,m),{ok:!0,data:m}}async function we(e,t){let{req:n,logPath:r,sessionStore:i,session:a,device:o,inspectFacts:c,bindDevice:l}=e,{setting:u,state:d}=t,f=J(o,u);if(f!==void 0)return f;let p=await y({command:`settings`,device:o,use:s,inspectFacts:c,bindDevice:l,readiness:!a}),m=Te(n,t,a);if(p.type===`response`)return p.response;let h=Ee(t,m);if(h!==void 0)return h;a&&_(a),A({level:`debug`,phase:`settings_apply`,data:ye(t,m,o.platform)});let g=await xe(p.runtime,De(t,m,v(r,n.flags,m,a?.trace?.outPath)),oe(u,d,m));return L(i,a,n,g),{ok:!0,data:g}}function J(e,o){if(n(e)&&!E(o))return t(`INVALID_ARGS`,ae(o));if(o===`text-size`&&r(e.platform)&&!i(e))return t(`UNSUPPORTED_OPERATION`,D.message,{deviceKind:e.kind,appleOs:a(e),reason:D.reason},{hint:D.hint})}function Te(e,t,n){return t.appBundleId??e.internal?.settingsAppBundleId??n?.appBundleId}function Ee(e,n){if(e.setting===`clear-app-state`&&!n)return t(`INVALID_ARGS`,`settings clear-app-state requires an app id when no app is bound to the session`)}function De(e,t,n){let r=q(e);return{setting:e.setting,state:e.state,...t===void 0?{}:{appBundleId:t},...r===void 0?{}:{options:r},execution:b(n)}}async function Oe(e){return await P({...e,command:`diff`,execute:async({runtime:e,sessionName:t,req:n,snapshotScope:r})=>{let i=await e.capture.diffSnapshot({session:t,interactiveOnly:n.flags?.snapshotInteractiveOnly,depth:n.flags?.snapshotDepth,scope:r,raw:n.flags?.snapshotRaw});return{data:i,record:{kind:`diff`,mode:`snapshot`,baselineInitialized:i.baselineInitialized,summary:i.summary}}}})}function ke(e){return e!==`sleep`}const Ae=[`application`,`window`,`tabbar`,`scrollbar`,`image`],je=new Set([`tab bar`]);async function Me(e,n){if(n.ok||!Ne(n.error.details?.reason)||n.error.details?.captureStalled===!0||n.error.details?.captureTruncated===!0)return n;let r=await Pe(e).catch(()=>null);return r?t(n.error.code,`${n.error.message}. Current surface: ${r.summary}.`,{...n.error.details??{},currentSurface:r.details}):n}function Ne(e){return e===w.targetAbsent||e===w.stableTimeout}async function Pe(e){let t={...e.req.flags,snapshotInteractiveOnly:!0},n=await C({device:e.device,session:e.session,flags:t,logPath:e.logPath??``,captureData:async()=>await e.capture(x({flags:t,logPath:e.logPath??``,meta:e.req.meta,session:e.session,snapshotScope:void 0}))});N(e.captureProof,n.snapshot);let r=[...n.snapshot.nodes].sort(Fe),i=Y(r,6,{includeIdentifiers:!0});if(i.length===0)return null;let a=Y(r.filter(e=>!Q(e)),4,{includeIdentifiers:!1}),o=Y(r.filter(Le),4,{includeIdentifiers:!0});return{summary:(a.length>0?a:i.slice(0,4)).join(`, `),details:{labels:i,...o.length>0?{buttons:o}:{}}}}function Y(e,t,n){let r=new Set,i=[];for(let a of e){let e=Z(a,n);if(!(!e||r.has(e))&&(r.add(e),i.push(e),i.length>=t))break}return i}function Fe(e,t){return X(e)-X(t)||Ie(e,t)}function X(e){let t=!!Z(e,{includeIdentifiers:!1});return(Q(e)?2:0)+ +!t}function Ie(e,t){return e.rect&&t.rect?e.rect.y-t.rect.y||e.rect.x-t.rect.x:e.rect?-1:t.rect?1:(e.depth??0)-(t.depth??0)||e.index-t.index}function Z(e,t){let n=(t.includeIdentifiers?[e.label,e.value,e.identifier]:[e.label,e.value]).map(e=>typeof e==`string`?e.trim():``).find(e=>e.length>0);return n?n.replaceAll(/\s+/g,` `).slice(0,80):``}function Q(e){let t=c(`${e.type??``} ${e.role??``} ${e.subrole??``}`),n=`${e.label??``} ${e.value??``}`.trim().toLowerCase();return Ae.some(e=>t.includes(e))||je.has(n)||n.endsWith(`.fill`)}function Le(e){let t=`${e.type??``} ${e.role??``} ${e.subrole??``}`;return c(t).includes(`button`)}async function Re(e){let{req:t,sessionName:n,sessionStore:r}=e,i=ze(t);if(`ok`in i)return i;let a=i,{session:o,device:s}=await I(r,n,t.flags),c=await Be(e,a,o,s);if(c&&`ok`in c)return c;let l=c,u=t.internal?.replayLandmarkGuard,d=Ve(a,o);if(`ok`in d)return d;let{waitParsed:f,staleRefsWarning:p}=d;return e.consumedSnapshot??={},e.captureProof??={},a.kind===`sleep`?await $(e,f,o,s,l,p,u):M({response:await R(o,s,()=>$(e,f,o,s,l,p,u),e.platformResourceCleanup),consumedTree:le(e),captureProof:e.captureProof})}function ze(e){let n=p(e.positionals??[]);if(!n)return t(`INVALID_ARGS`,`wait requires a duration or text`);if(n.kind===`invalid`)return t(`INVALID_ARGS`,n.message);if(n.kind!==`absent`)return n;let r=se({depth:e.flags?.snapshotDepth,scope:e.flags?.snapshotScope});if(!r)return n;let i=k(r,`wait`);return t(i.code,i.message,i.details)}async function Be(e,t,n,r){if(!ke(t.kind))return;let i=await V({command:`wait`,device:r,session:n,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return i.ok?i.operations:i.response}function Ve(e,t){if(e.kind!==`ref`)return{waitParsed:e};let n=H(e.rawRef);return n.ok?{waitParsed:{...e,rawRef:n.ref},staleRefsWarning:S({session:t,ref:n.ref,mintedGeneration:n.generation})}:n.response}async function $(e,t,n,r,i,a,o){let{req:s,sessionName:c,sessionStore:l}=e,u=B({...e,session:n,device:r,bound:i}),d=await ce(async()=>{let e=await u.selectors.wait({session:c,requestId:s.meta?.requestId,target:He(t,n,o)}),r=G(e);K(l,c,s,W(e),r,`landmark`);let i=U(e);return a?{...i,warning:a}:i}),f=i?await Me({req:s,logPath:e.logPath,session:n,device:r,capture:i.capture,captureProof:e.captureProof},d):d;return await z(e,f,`wait`)}function He(e,t,n){switch(e.kind){case`sleep`:return{kind:`sleep`,durationMs:e.durationMs};case`selector`:return{kind:`selector`,selector:e.selectorExpression,timeoutMs:e.timeoutMs,...n?{recordedLandmark:n}:{}};case`absent`:return{kind:`absent`,selector:e.selectorExpression,timeoutMs:e.timeoutMs};case`ref`:return We(e,t);case`stable`:return{kind:`stable`,quietMs:e.quietMs,timeoutMs:e.timeoutMs};case`text`:return Ge(e);default:return Ue(e)}}function Ue(e){throw Error(`Unsupported wait positional target: ${String(e)}`)}function We(t,n){if(!n?.snapshot)throw new e(`INVALID_ARGS`,`Ref wait requires an existing snapshot in session.`);return{kind:`ref`,ref:t.rawRef,timeoutMs:t.timeoutMs}}function Ge(t){let n=m(t.text);if(!n.ok)throw new e(n.code,n.message);return{kind:`text`,text:n.text,timeoutMs:t.timeoutMs}}const Ke={snapshot:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>await F({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o}),diff:async({req:e,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformResourceCleanup:s})=>e.positionals?.[0]===`snapshot`?await Oe({req:e,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformResourceCleanup:s}):t(`INVALID_ARGS`,`diff currently supports only: diff snapshot`),wait:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>await Re({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o}),alert:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>{let{session:s,device:c}=await I(r,t,e.flags);return await R(s,c,async()=>await he({req:e,logPath:n,sessionStore:r,session:s,device:c,inspectFacts:i,bindDevice:a}),o)},settings:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformResourceCleanup:o})=>{let s=ve(e);if(!s.ok)return s;let{session:c,device:l}=await I(r,t,e.flags);return await R(c,l,async()=>await Se({req:e,logPath:n,sessionStore:r,session:c,device:l,parsed:s.parsed,inspectFacts:i,bindDevice:a}),o)}};async function qe(e){let t=e.req.command,n=Ke[t];return n?await n(e):null}export{qe as handleSnapshotCommands};
package/dist/src/src.js CHANGED
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{D as t}from"./sdk-contracts.js";import{Qt as n}from"./sdk-batch.js";import{c as r,i,s as a}from"./request-cancellation.js";import{t as o}from"./api.js";import{a as s,i as c,l,n as u,o as d,s as f,t as p}from"./device-session.js";import{scryptSync as m}from"node:crypto";const h=`agent-device-cli`;function g(e){return{apiKey:e.apiKey,defaultHeaders:{"x-agent-device-client":h,"x-agent-device-version":e.clientVersion}}}function _(e){if(e.runtimeInstance!==void 0){let t=e.runtimeInstance.trim();if(!t)throw TypeError(`Limrun runtimeInstance must be a non-empty string`);return t}let t=JSON.stringify({provider:`limrun`,region:e.region?.trim().toLowerCase()||`default`,apiKey:e.apiKey});return`principal-${m(t,`agent-device:limrun-runtime-owner:v1`,32,{N:16384,r:8,p:1,maxmem:67108864}).toString(`hex`)}`}function v(e,t,r){let a=new y(e,t);if(!r?.includePlatformModule)return a;let o=n(i,_(e));if(o.kind!==`provider-runtime`)throw TypeError(`Invalid Limrun runtime owner`);return Object.freeze({runtime:a,platformModule:Object.freeze({owner:o,loadRuntime:async e=>await b(a,o.instance,e)})})}var y=class{limrun;sessions=new Map;appAliases=new Map;options;dependencies;provider=i;leaseLifecycle={allocate:async(e,t)=>await this.allocate(e,t),release:async e=>await this.release(e)};appCatalog=async(e,t)=>{let{assertLimrunUploadedAppAccess:n,listLimrunAppAssets:r}=await import(`./app-catalog.js`);return n(e.publicNetworkOnly),(await r(this.limrun,e.platform,t)).map(e=>e.name)};recoverExpiredLease=async e=>{if(e.leaseProvider!==this.provider||!r(e.backend))throw new t(`UNSUPPORTED_OPERATION`,`Limrun cannot recover this expired lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend});await this.release(e)};deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider||!e.leaseId)return null;let t=this.sessions.get(e.leaseId);return t?e.platform&&e.platform!==t.platform?[]:[t.device]:null};constructor(e,t){this.options=e,this.dependencies=t,this.limrun=new o(g({apiKey:e.apiKey,clientVersion:t.clientVersion}))}ownsDevice(e){return a(e.id)!==void 0}hasLiveSession(e){return this.getSessionForDevice(e)!==void 0}getInteractor(e,t){let n=this.getSessionForDevice(e);if(n)return n.platform===`ios`?u(n):f(n)}getDeviceSession(e){let t=this.getSessionForDevice(e);return t?p(t):void 0}async installApp(e,t,n,r,i,a){return await this.installInstallablePath(e,n,{...r,appIdentifierHint:r?.appIdentifierHint??t,packageNameHint:r?.packageNameHint??t},i,a)}async installInstallablePath(e,t,n,r,i){let a=this.getSessionForDevice(e);if(a)return a.platform===`ios`?await c(this.limrun,a,t,n,r,i):await l(this.limrun,a,t,n,r,i)}async configurePortReverse(e){let t=this.requireAndroidPortReverseSession(e.leaseId);if(t)return await d(t,e),x(e)}async shutdown(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(async e=>await this.terminateSession(e))),this.sessions.clear(),this.appAliases.clear()}async allocate(e,t){if(e.leaseProvider!==this.provider)return;let n=r(e.backend);if(!n)return;let i=this.sessions.get(e.leaseId);if(i)return{limrunInstanceId:i.instanceId,device:i.device};let{allocateLimrunAndroidSession:a,allocateLimrunIosSession:o,resolvePreinstalledAppId:s,resolveRequestedLimrunAppAsset:c}=await import(`./session-allocation.js`),l=await c(this.limrun,n,t),u=n===`ios`?await o(this.sessionAllocationParams(e,l)):await a(this.sessionAllocationParams(e,l));if(l)try{let t=await s(u,l);this.appAliases.set(e.leaseId,{assetName:l.name,installedAppId:t})}catch(e){throw await this.terminateSession(u),e}return this.sessions.set(e.leaseId,u),{limrunInstanceId:u.instanceId,device:u.device}}sessionAllocationParams(e,t){return{limrun:this.limrun,lease:e,metadata:this.buildInstanceMetadata(e),region:this.options.region,app:t,dependencies:this.dependencies}}buildInstanceMetadata(e){return{displayName:`agent-device-${e.tenantId}-${e.runId}`,labels:{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId,provider:e.leaseProvider??`limrun`,source:h}}}async release(e){let t=this.sessions.get(e.leaseId);return t?(await this.terminateSession(t),this.sessions.delete(e.leaseId),this.appAliases.delete(e.leaseId),{limrunInstanceId:t.instanceId}):await this.releaseRecoveredSession(e)}async releaseRecoveredSession(e){let t=r(e.backend);if(!t)return;let n=`provider=${i},leaseId=${e.leaseId}`,a=(t===`ios`?await this.limrun.iosInstances.list({labelSelector:n}):await this.limrun.androidInstances.list({labelSelector:n})).getPaginatedItems().map(e=>e.metadata.id);for(let e of a)t===`ios`?await this.limrun.iosInstances.delete(e):await this.limrun.androidInstances.delete(e);if(a.length!==0)return{limrunInstanceId:a[0],limrunInstanceCount:a.length}}async terminateSession(e){if(e.client.disconnect(),e.platform===`ios`){await this.limrun.iosInstances.delete(e.instanceId);return}await s(e),await this.limrun.androidInstances.delete(e.instanceId)}getSessionForDevice(e){let t=a(e.id);if(!t)return;let n=this.sessions.get(t.leaseId);return n?.platform===t.platform?n:void 0}resolveAppReference(e,t){let n=a(e.id);if(!n)return t;let r=this.appAliases.get(n.leaseId);return r?.assetName===t?r.installedAppId:t}currentAppLogReader(e){let t=this.getSessionForDevice(e);if(!t)return;let n=p(t);return{platform:t.platform,leaseId:t.lease.leaseId,instanceId:t.instanceId,readLogs:async(e,t)=>n.platform===`ios`?await n.readLogs(e,t):await n.readLogs(t),[Symbol.asyncDispose]:async()=>void 0}}async reconnectAppLogReader(e,t){let{reconnectLimrunAppLogReader:n}=await import(`./app-log-reconnect.js`);return await n({limrun:this.limrun,descriptor:e,dependencies:this.dependencies,signal:t})}requireAndroidPortReverseSession(e){let t=this.sessions.get(e);if(!t||t.platform===`android`)return t;throw S(`port reverse`,`Direct Limrun iOS sessions cannot reach local host ports; use a bridge public URL.`)}};async function b(e,n,r){let{createLimrunPlatformRuntimeOwner:i}=await import(`./app-log-runtime2.js`);return i({host:r,runtimeInstance:n,ownsDevice:t=>e.ownsDevice(t),hasLiveSession:t=>e.hasLiveSession(t),getInteractor:(t,n)=>e.getInteractor(t,n),getDeviceSession:t=>e.getDeviceSession(t),resolveAppReference:(t,n)=>e.resolveAppReference(t,n),openCurrent:async t=>e.currentAppLogReader(t),reconnect:async(t,n)=>await e.reconnectAppLogReader(t,n),listApps:async(n,r,i)=>{i.throwIfAborted();let a=e.getDeviceSession(n);if(!a)throw new t(`DEVICE_NOT_FOUND`,`Limrun app inventory session is unavailable`,{deviceId:n.id});return(await a.listApps(r)).map(e=>({id:e.id,name:e.name??e.id}))},getAppState:async(n,r)=>{r.throwIfAborted();let i=e.getDeviceSession(n);if(i?.platform!==`android`)throw new t(`UNSUPPORTED_OPERATION`,`Limrun Android appstate requires an active provider session`);let a=await i.getForegroundApp(r);return r.throwIfAborted(),{package:a?.appId,activity:a?.activity}},deployApp:async(t,n,r,i)=>await e.installApp(t,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r,i),deployMaterializedApp:async(t,n,r,i)=>await e.installInstallablePath(t,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r,i),configurePortReverse:async t=>await e.configurePortReverse(t)})}function x(e){return{leaseId:e.leaseId,devicePort:e.devicePort,hostPort:e.hostPort,name:e.name}}function S(e,n){throw new t(`UNSUPPORTED_OPERATION`,n,{command:e})}async function C(e){let n=new o({...g(e),timeout:15e3,maxRetries:0}),r={limit:1,...e.region?{region:e.region}:{}};try{e.platform===`android`?await n.androidInstances.list(r):await n.iosInstances.list(r)}catch(e){let n=w(e);throw n===401||n===403?new t(`UNAUTHORIZED`,`Limrun rejected connection verification.`,{status:n,hint:`Check LIMRUN_API_KEY and its organization access.`}):new t(`COMMAND_FAILED`,`Limrun connection verification failed.`,{hint:`Check Limrun service access, LIMRUN_REGION, and network connectivity, then retry.`},e)}let i=e.platform===`android`?`Android`:`iOS`,a=e.platform===`android`?`emulator`:`simulator`;return{provider:`limrun`,service:`Limrun`,verificationMessage:`Credentials and ${i} instance access verified.`,device:{status:`deferred`,name:`Provider-selected ${i} ${a}`,platform:e.platform},app:{status:`missing`,message:`Run apps to choose an uploaded asset before allocation.`}}}function w(e){if(!e||typeof e!=`object`)return;let t=e.status;return typeof t==`number`?t:void 0}var T=e({LIMRUN_PROVIDER:()=>i,createLimrunRuntime:()=>v,verifyLimrunConnection:()=>C});export{C as n,v as r,T as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{O as t}from"./sdk-contracts.js";import{Qt as n}from"./sdk-batch.js";import{c as r,i,s as a}from"./request-cancellation.js";import{t as o}from"./api.js";import{a as s,i as c,l,n as u,o as d,s as f,t as p}from"./device-session.js";import{scryptSync as m}from"node:crypto";const h=`agent-device-cli`;function g(e){return{apiKey:e.apiKey,defaultHeaders:{"x-agent-device-client":h,"x-agent-device-version":e.clientVersion}}}function _(e){if(e.runtimeInstance!==void 0){let t=e.runtimeInstance.trim();if(!t)throw TypeError(`Limrun runtimeInstance must be a non-empty string`);return t}let t=JSON.stringify({provider:`limrun`,region:e.region?.trim().toLowerCase()||`default`,apiKey:e.apiKey});return`principal-${m(t,`agent-device:limrun-runtime-owner:v1`,32,{N:16384,r:8,p:1,maxmem:67108864}).toString(`hex`)}`}function v(e,t,r){let a=new y(e,t);if(!r?.includePlatformModule)return a;let o=n(i,_(e));if(o.kind!==`provider-runtime`)throw TypeError(`Invalid Limrun runtime owner`);return Object.freeze({runtime:a,platformModule:Object.freeze({owner:o,loadRuntime:async e=>await b(a,o.instance,e)})})}var y=class{limrun;sessions=new Map;appAliases=new Map;options;dependencies;provider=i;leaseLifecycle={allocate:async(e,t)=>await this.allocate(e,t),release:async e=>await this.release(e)};appCatalog=async(e,t)=>{let{assertLimrunUploadedAppAccess:n,listLimrunAppAssets:r}=await import(`./app-catalog.js`);return n(e.publicNetworkOnly),(await r(this.limrun,e.platform,t)).map(e=>e.name)};recoverExpiredLease=async e=>{if(e.leaseProvider!==this.provider||!r(e.backend))throw new t(`UNSUPPORTED_OPERATION`,`Limrun cannot recover this expired lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend});await this.release(e)};deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider||!e.leaseId)return null;let t=this.sessions.get(e.leaseId);return t?e.platform&&e.platform!==t.platform?[]:[t.device]:null};constructor(e,t){this.options=e,this.dependencies=t,this.limrun=new o(g({apiKey:e.apiKey,clientVersion:t.clientVersion}))}ownsDevice(e){return a(e.id)!==void 0}hasLiveSession(e){return this.getSessionForDevice(e)!==void 0}getInteractor(e,t){let n=this.getSessionForDevice(e);if(n)return n.platform===`ios`?u(n):f(n)}getDeviceSession(e){let t=this.getSessionForDevice(e);return t?p(t):void 0}async installApp(e,t,n,r,i,a){return await this.installInstallablePath(e,n,{...r,appIdentifierHint:r?.appIdentifierHint??t,packageNameHint:r?.packageNameHint??t},i,a)}async installInstallablePath(e,t,n,r,i){let a=this.getSessionForDevice(e);if(a)return a.platform===`ios`?await c(this.limrun,a,t,n,r,i):await l(this.limrun,a,t,n,r,i)}async configurePortReverse(e){let t=this.requireAndroidPortReverseSession(e.leaseId);if(t)return await d(t,e),x(e)}async shutdown(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(async e=>await this.terminateSession(e))),this.sessions.clear(),this.appAliases.clear()}async allocate(e,t){if(e.leaseProvider!==this.provider)return;let n=r(e.backend);if(!n)return;let i=this.sessions.get(e.leaseId);if(i)return{limrunInstanceId:i.instanceId,device:i.device};let{allocateLimrunAndroidSession:a,allocateLimrunIosSession:o,resolvePreinstalledAppId:s,resolveRequestedLimrunAppAsset:c}=await import(`./session-allocation.js`),l=await c(this.limrun,n,t),u=n===`ios`?await o(this.sessionAllocationParams(e,l)):await a(this.sessionAllocationParams(e,l));if(l)try{let t=await s(u,l);this.appAliases.set(e.leaseId,{assetName:l.name,installedAppId:t})}catch(e){throw await this.terminateSession(u),e}return this.sessions.set(e.leaseId,u),{limrunInstanceId:u.instanceId,device:u.device}}sessionAllocationParams(e,t){return{limrun:this.limrun,lease:e,metadata:this.buildInstanceMetadata(e),region:this.options.region,app:t,dependencies:this.dependencies}}buildInstanceMetadata(e){return{displayName:`agent-device-${e.tenantId}-${e.runId}`,labels:{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId,provider:e.leaseProvider??`limrun`,source:h}}}async release(e){let t=this.sessions.get(e.leaseId);return t?(await this.terminateSession(t),this.sessions.delete(e.leaseId),this.appAliases.delete(e.leaseId),{limrunInstanceId:t.instanceId}):await this.releaseRecoveredSession(e)}async releaseRecoveredSession(e){let t=r(e.backend);if(!t)return;let n=`provider=${i},leaseId=${e.leaseId}`,a=(t===`ios`?await this.limrun.iosInstances.list({labelSelector:n}):await this.limrun.androidInstances.list({labelSelector:n})).getPaginatedItems().map(e=>e.metadata.id);for(let e of a)t===`ios`?await this.limrun.iosInstances.delete(e):await this.limrun.androidInstances.delete(e);if(a.length!==0)return{limrunInstanceId:a[0],limrunInstanceCount:a.length}}async terminateSession(e){if(e.client.disconnect(),e.platform===`ios`){await this.limrun.iosInstances.delete(e.instanceId);return}await s(e),await this.limrun.androidInstances.delete(e.instanceId)}getSessionForDevice(e){let t=a(e.id);if(!t)return;let n=this.sessions.get(t.leaseId);return n?.platform===t.platform?n:void 0}resolveAppReference(e,t){let n=a(e.id);if(!n)return t;let r=this.appAliases.get(n.leaseId);return r?.assetName===t?r.installedAppId:t}currentAppLogReader(e){let t=this.getSessionForDevice(e);if(!t)return;let n=p(t);return{platform:t.platform,leaseId:t.lease.leaseId,instanceId:t.instanceId,readLogs:async(e,t)=>n.platform===`ios`?await n.readLogs(e,t):await n.readLogs(t),[Symbol.asyncDispose]:async()=>void 0}}async reconnectAppLogReader(e,t){let{reconnectLimrunAppLogReader:n}=await import(`./app-log-reconnect.js`);return await n({limrun:this.limrun,descriptor:e,dependencies:this.dependencies,signal:t})}requireAndroidPortReverseSession(e){let t=this.sessions.get(e);if(!t||t.platform===`android`)return t;throw S(`port reverse`,`Direct Limrun iOS sessions cannot reach local host ports; use a bridge public URL.`)}};async function b(e,n,r){let{createLimrunPlatformRuntimeOwner:i}=await import(`./app-log-runtime2.js`);return i({host:r,runtimeInstance:n,ownsDevice:t=>e.ownsDevice(t),hasLiveSession:t=>e.hasLiveSession(t),getInteractor:(t,n)=>e.getInteractor(t,n),getDeviceSession:t=>e.getDeviceSession(t),resolveAppReference:(t,n)=>e.resolveAppReference(t,n),openCurrent:async t=>e.currentAppLogReader(t),reconnect:async(t,n)=>await e.reconnectAppLogReader(t,n),listApps:async(n,r,i)=>{i.throwIfAborted();let a=e.getDeviceSession(n);if(!a)throw new t(`DEVICE_NOT_FOUND`,`Limrun app inventory session is unavailable`,{deviceId:n.id});return(await a.listApps(r)).map(e=>({id:e.id,name:e.name??e.id}))},getAppState:async(n,r)=>{r.throwIfAborted();let i=e.getDeviceSession(n);if(i?.platform!==`android`)throw new t(`UNSUPPORTED_OPERATION`,`Limrun Android appstate requires an active provider session`);let a=await i.getForegroundApp(r);return r.throwIfAborted(),{package:a?.appId,activity:a?.activity}},deployApp:async(t,n,r,i)=>await e.installApp(t,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r,i),deployMaterializedApp:async(t,n,r,i)=>await e.installInstallablePath(t,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r,i),configurePortReverse:async t=>await e.configurePortReverse(t)})}function x(e){return{leaseId:e.leaseId,devicePort:e.devicePort,hostPort:e.hostPort,name:e.name}}function S(e,n){throw new t(`UNSUPPORTED_OPERATION`,n,{command:e})}async function C(e){let n=new o({...g(e),timeout:15e3,maxRetries:0}),r={limit:1,...e.region?{region:e.region}:{}};try{e.platform===`android`?await n.androidInstances.list(r):await n.iosInstances.list(r)}catch(e){let n=w(e);throw n===401||n===403?new t(`UNAUTHORIZED`,`Limrun rejected connection verification.`,{status:n,hint:`Check LIMRUN_API_KEY and its organization access.`}):new t(`COMMAND_FAILED`,`Limrun connection verification failed.`,{hint:`Check Limrun service access, LIMRUN_REGION, and network connectivity, then retry.`},e)}let i=e.platform===`android`?`Android`:`iOS`,a=e.platform===`android`?`emulator`:`simulator`;return{provider:`limrun`,service:`Limrun`,verificationMessage:`Credentials and ${i} instance access verified.`,device:{status:`deferred`,name:`Provider-selected ${i} ${a}`,platform:e.platform},app:{status:`missing`,message:`Run apps to choose an uploaded asset before allocation.`}}}function w(e){if(!e||typeof e!=`object`)return;let t=e.status;return typeof t==`number`?t:void 0}var T=e({LIMRUN_PROVIDER:()=>i,createLimrunRuntime:()=>v,verifyLimrunConnection:()=>C});export{C as n,v as r,T as t};
package/dist/src/src7.js CHANGED
@@ -1,2 +1,2 @@
1
- import{D as e}from"./sdk-contracts.js";import{E as t}from"./sdk-device.js";import{Yt as n,en as r}from"./sdk-batch.js";import{t as i}from"./audio-probe-runtime.js";import{a,n as o,t as s}from"./durable-resource.js";import{n as c}from"./async-lifecycle.js";import{n as l,t as u}from"./audio-probe-result.js";import d from"node:fs/promises";function f(e,t){if(e.resourceKind!==t.resourceKind)return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Durable resource kind ${e.resourceKind} does not match ${t.resourceKind}`};if(e.descriptor.version!==t.version)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported ${t.resourceKind} descriptor version: ${e.descriptor.version}`,version:e.descriptor.version};try{let n=t.decode(e.descriptor.body);return n.status===`decoded`?n:{status:`unreattachable`,reason:`descriptor-invalid`,message:n.message}}catch(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e instanceof Error?e.message:`Descriptor codec rejected the body`}}}function p(e,t){return Object.freeze({pendingHandle:new c(e),envelope:t})}function m(e){return Object.freeze({appLogReattach:async({envelope:t})=>{let n=f(t,e.codec);return n.status===`unreattachable`?n:await e.reattach(n.descriptor,h(t))},appLogCleanup:async({envelope:t})=>{let n=f(t,e.codec);return n.status===`decoded`?await e.cleanup(n.descriptor,h(t)):{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message}}})}function h(e){return Object.freeze({sessionId:e.sessionId,fence:e.fence})}function g(e){if(typeof e!=`object`||!e||Array.isArray(e))return{status:`invalid`,message:`App-log process marker must be an object`};let t=e;return!Number.isInteger(t.pid)||Number(t.pid)<=0?{status:`invalid`,message:`App-log process marker pid must be a positive integer`}:typeof t.startTime!=`string`||t.startTime.trim().length===0?{status:`invalid`,message:`App-log process marker startTime must be a non-empty string`}:typeof t.command!=`string`||t.command.trim().length===0?{status:`invalid`,message:`App-log process marker command must be a non-empty string`}:{status:`decoded`,marker:Object.freeze({pid:Number(t.pid),startTime:t.startTime,command:t.command})}}function _(e){let t,n,r,i=()=>n??=e.forceCleanup();return Object.freeze({inspect:()=>e.inspect(),finish:()=>t??=e.finish(),forceCleanup:i,[Symbol.asyncDispose]:async()=>{r??=i().then(ee),await r}})}function v(e){return _({inspect:e.inspect,finish:e.finish,forceCleanup:async()=>{let t=await e.finish();return t.status===`completed`?{status:`cleaned`}:{status:`cleanup-pending`,reason:t.reason,message:t.message}}})}function ee(t){if(!s(t))throw new e(`COMMAND_FAILED`,t.message??`Durable resource cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:t.reason===`ownership-fence-lost`?`Use the current resource owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}const te=e=>b(e.backend)&&(e.source===`system-audio`||e.source===`media-elements`)&&x(e.sourceCount,0)&&re(e.notes)&&b(e.statusPath)&&x(e.startedAt,1)&&x(e.durationMs,1)&&x(e.bucketMs,1),y=Object.freeze({resourceKind:i,version:1,encode:e=>({...e,notes:[...e.notes],marker:{...e.marker}}),decode:e=>{let t=te(e)?ne(e.marker):`invalid`;if(t===`invalid`)return{status:`invalid`,message:`Audio probe descriptor body is invalid`};let n=e;return{status:`decoded`,descriptor:Object.freeze({backend:n.backend,source:n.source,sourceCount:n.sourceCount,notes:Object.freeze([...n.notes]),statusPath:n.statusPath,startedAt:n.startedAt,durationMs:n.durationMs,bucketMs:n.bucketMs,marker:t})}}});function ne(e){if(typeof e!=`object`||!e)return`invalid`;let t=e;return!x(t.pid,1)||!b(t.startTime)||!b(t.command)?`invalid`:Object.freeze({pid:t.pid,startTime:t.startTime,command:t.command})}function b(e){return typeof e==`string`&&e.length>0}function x(e,t){return typeof e==`number`&&Number.isInteger(e)&&e>=t}function re(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}async function S(e){try{let t=await d.readFile(e.statusPath,`utf8`);return l(JSON.parse(t),{source:e.source,backend:e.backend,durationMs:e.durationMs,elapsedMs:Date.now()-e.startedAt,bucketMs:e.bucketMs,activeFallback:!0,sourceCount:e.sourceCount,notes:[...e.notes]})}catch(e){if(e.code===`ENOENT`)return;throw e}}function C(e,t,n){let r=Math.min(e.durationMs,Math.max(0,Date.now()-e.startedAt));return{...t??u({source:e.source,backend:e.backend,durationMs:e.durationMs,bucketMs:e.bucketMs,sourceCount:e.sourceCount,notes:[...e.notes]}),state:`stopped`,active:!1,elapsedMs:r,stoppedAt:new Date().toISOString(),reason:n}}function ie(e){let{host:t}=e;return Object.freeze({audioProbeReattach:async e=>{let n=f(e.envelope,y);if(n.status!==`decoded`)return n;let r=n.descriptor,i=await t.inspectProcess(r.marker);if(i===`owned-alive`)return{status:`unreattachable`,reason:`transport-not-reattachable`};if(i===`ownership-lost`)return{status:`unreattachable`,reason:`ownership-fence-lost`};let a=await S(r);return a===void 0||a.state!==`stopped`?{status:`missing`}:{status:`completed`,result:C(r,a,`daemon-recovery`)}},audioProbeCleanup:async e=>{let n=f(e.envelope,y);if(n.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message};let r=n.descriptor,i=await t.inspectProcess(r.marker);if(i===`ownership-lost`)return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(i===`missing`)return{status:`already-missing`};let a=await t.terminateProcess(r.marker);return a===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:{status:a===`terminated`?`cleaned`:`already-missing`}}})}async function ae(n){let{host:r,device:s,owner:l,input:u}=n,f=Date.now(),p=r.info,m=Object.freeze([...p.notes(s)]),h=Object.freeze({source:p.source,backend:p.backend,sourceCount:p.sourceCount,notes:m,statusPath:u.statusPath,startedAt:f,durationMs:u.durationMs,bucketMs:u.bucketMs});await d.rm(u.statusPath,{force:!0});let g=await r.start({durationMs:u.durationMs,bucketMs:u.bucketMs,statusPath:u.statusPath});g.wait.catch(()=>{});let _=g.marker;try{if(_===void 0)throw new e(`COMMAND_FAILED`,`failed to start host audio probe: the helper process exposed no exact identity, so the capture could not be recovered after daemon loss and was terminated`);await ue(h,g)}catch(e){throw await g.terminate().catch(()=>{}),e}return Object.freeze({pendingHandle:new c(oe(h,g)),envelope:o({resourceKind:i,sessionId:u.sessionId,device:t(s),owner:l,fence:u.fence,lifecycle:`open`,descriptor:a(y,{backend:p.backend,source:p.source,sourceCount:p.sourceCount,notes:m,statusPath:u.statusPath,startedAt:f,durationMs:u.durationMs,bucketMs:u.bucketMs,marker:_})})})}function oe(e,t){let n,r,i,a;t.wait.then(e=>{a={message:se(e)}},e=>{a={message:e instanceof Error?e.message:`audio probe helper wait failed`}});let o=()=>n??=(async()=>{let n=await S(e);if(n?.state!==`stopped`&&a)throw w(a);return await t.terminate().catch(()=>{}),await t.wait.catch(()=>{}),{status:`completed`,result:C(e,n,`stopped`)}})(),s=()=>r??=n?n.then(async()=>({status:`cleaned`}),async()=>await T(t)):T(t);return Object.freeze({inspect:()=>e,status:async()=>{let t=await S(e);if(t?.state===`stopped`)return t;if(a)throw w(a);return t??C(e,void 0,`not-started`)},finish:o,forceCleanup:s,[Symbol.asyncDispose]:async()=>{i??=s().then(ce),await i}})}function se(e){return e.stderr?.trim()||e.stdout?.trim()||`audio probe helper exited with code ${e.exitCode??1}`}function w(t){return new e(`COMMAND_FAILED`,`host audio probe helper exited before completing the capture: ${t.message}`,{hint:`Keep audio-probe.resource.json; stop resolves the record through descriptor cleanup.`})}async function T(e){try{return await e.terminate(),await e.wait.catch(()=>{}),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:e instanceof Error?e.message:`Audio probe termination failed`}}}function ce(t){if(!s(t))throw new e(`COMMAND_FAILED`,t.message??`Audio probe cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`})}function le(e){let{host:t,device:n,owner:r}=e,i=ie({host:t});return Object.freeze({audioProbeStart:async e=>await ae({host:t,device:n,owner:r,input:e}),audioProbeReattach:i.audioProbeReattach,audioProbeCleanup:i.audioProbeCleanup})}async function ue(t,n){let r=Date.now()+5e3;for(;Date.now()<r;){if(await S(t))return;let r=await Promise.race([n.wait.then(e=>e,e=>e),de(100).then(()=>void 0)]);if(r instanceof Error)throw r;if(r){let t=r,n=t.stderr?.trim()||t.stdout?.trim()||`host audio probe helper exited with code ${t.exitCode??1}`;throw new e(`COMMAND_FAILED`,`failed to start host audio probe: ${n}`)}}throw new e(`COMMAND_FAILED`,`failed to start host audio probe`)}function de(e){return new Promise(t=>setTimeout(t,e))}async function E(e,t){let n=await O(e,t);if(n.status===`missing`)return{status:`missing`};if(n.status===`invalid`)return{status:`unreattachable`,reason:`ownership-fence-lost`,message:n.message};let r=await e.processes.inspect(n.marker);return r===`missing`?(t&&await e.processes.clearMarker(t),{status:`missing`}):r===`ownership-lost`?{status:`unreattachable`,reason:`ownership-fence-lost`}:{status:`unreattachable`,reason:`transport-not-reattachable`}}async function D(e,t){if(!t)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`App-log process marker path is missing`};let n=await O(e,t);if(n.status===`missing`)return{status:`already-missing`};if(n.status===`invalid`)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message};let r=await e.processes.inspect(n.marker);if(r===`ownership-lost`)return k();if(r===`missing`)return await e.processes.clearMarker(t),{status:`already-missing`};let i=await e.processes.terminate(n.marker);return i===`ownership-lost`?k():(await e.processes.clearMarker(t),{status:i===`terminated`?`cleaned`:`already-missing`})}async function O(e,t){return t?await e.processes.readMarker(t):{status:`invalid`,message:`App-log process marker path is missing`}}function k(){return{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function fe(e){let t=e.initialProcess;for(;!e.stopped();){if(t){await pe(e,t),t=void 0,await be(e);continue}let n=await xe(e);if(n.status===`stopped`)return;n.status!==`waiting`&&(t=n.process)}}async function pe(e,t){let{process:n}=t;e.setActive(n);try{e.setState(`active`),await me(e,t)}finally{await A(e,n)}}async function me(e,t){let n=he(t.process);try{await ge(e,t,n),await ve(e,t.process,n),await ye(n.outcome)}finally{n.controller.abort()}}function he(e){let t=new AbortController,n=!1,r=()=>{n=!0,t.abort()};return{controller:t,outcome:e.wait.then(()=>(r(),{status:`exited`}),e=>(r(),{status:`failed`,error:e})),settled:()=>n}}async function ge(e,t,n){for(;!e.stopped()&&!n.settled();){if(!await _e(e,n))return;let r=await e.resolvePid();if(e.stopped())return;if(r!==t.pid){await t.process.terminate();return}}}async function _e(e,t){try{await e.sleep(500,t.controller.signal)}catch(e){if(!t.settled())throw e}return!t.settled()}async function ve(e,t,n){e.stopped()&&!n.settled()&&await t.terminate()}async function ye(e){let t=await e;if(t.status===`failed`)throw t.error}async function be(e){e.stopped()||(e.setState(`recovering`),await e.sleep(500))}async function xe(e){let t=await e.resolvePid();if(e.stopped())return{status:`stopped`};if(!t)return e.setState(`recovering`),await e.sleep(1e3),{status:`waiting`};let n=await e.startProcess(t);return e.setActive(n),e.stopped()?(await Se(e,n),{status:`stopped`}):{status:`started`,process:{pid:t,process:n}}}async function Se(e,t){try{await t.terminate(),await t.wait}finally{await A(e,t)}}async function A(e,t){try{await t[Symbol.asyncDispose]()}finally{e.setActive(void 0)}}async function Ce(e){let t=await e.resolvePid(e.setupSignal);e.setupSignal.throwIfAborted();let n=await e.host.outputs.openAppend(e.outputPath),r=`recovering`,i=!1,a;try{if(e.setupSignal.throwIfAborted(),t){e.setupSignal.throwIfAborted();let i=new AbortController,o=()=>i.abort(e.setupSignal.reason);e.setupSignal.addEventListener(`abort`,o,{once:!0});try{a=await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath},i.signal)}finally{e.setupSignal.removeEventListener(`abort`,o)}e.setupSignal.throwIfAborted(),r=`active`}}catch(e){throw await j([async()=>await a?.terminate(),async()=>{await a?.wait},async()=>await a?.[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()]),e}let o=fe({initialProcess:a&&t?{pid:t,process:a}:void 0,stopped:()=>i,setActive:e=>{a=e},setState:e=>{r=e},resolvePid:async()=>await e.resolvePid(),startProcess:async t=>await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath}),sleep:async(t,n)=>await e.host.clock.sleep(t,n)}).catch(()=>{r=`failed`}),s,c=async()=>s??=we({options:e,monitor:o,active:()=>a,stop:()=>{i=!0},setState:e=>{r=e},output:n}),l=e.host.clock.now();return v({inspect:()=>({backend:e.backend,state:r,startedAt:l}),finish:c})}async function we(e){return e.stop(),(await j([async()=>await e.active()?.terminate(),async()=>await e.monitor,async()=>await e.output[Symbol.asyncDispose]()])).length>0?(e.setState(`failed`),{status:`cleanup-pending`,reason:`transport-failed`,message:e.options.cleanupFailureMessage}):(e.setState(`ended`),{status:`completed`,result:{backend:e.options.backend,outputPath:e.options.outputPath,completedAt:e.options.host.clock.now()}})}async function j(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}function M(e,t,n){let r=e.artifacts.resolveSession(t);return n.outputPath===r.outputPath&&(n.pidPath===void 0||n.pidPath===r.pidPath)}function N(t,n){if(!M(t,n.sessionId,n))throw new e(`INVALID_ARGS`,`App-log paths do not match the owning session`)}const P=Object.freeze({available:!0});async function Te(e,t,n){let r=(await e.commands.run(t,n)).stdout.trim().split(/\s+/)[0]??``;return/^\d+$/.test(r)?r:``}function Ee(t,i){let a=n(i.family);return Object.freeze({owner:a,ownsDevice:e=>e.platform===i.family,inspectFacts:async e=>F(e,await t.processTransports.resolve(e),i),bind:async n=>{if(n.intent.kind===`exact-owner`&&!r(n.intent.owner,a))throw new e(`UNSUPPORTED_OPERATION`,`${i.label} app-log owner identity does not match`);if(n.device.platform!==i.family)throw new e(`UNSUPPORTED_PLATFORM`,`${i.label} app-log owner cannot bind ${n.device.platform}`);let o=await t.processTransports.resolve(n.device);return De(t,n.device,n.scope.signal,o,a,i)},shutdown:async()=>void 0})}function De(e,t,n,r,i,a){let o=m({codec:a.codec,reattach:async(t,n)=>M(e,n.sessionId,t)?await E(e,t.pidPath):{status:`unreattachable`,reason:`descriptor-invalid`,message:`${a.label} app-log descriptor paths do not match the owning session`},cleanup:async(t,n)=>M(e,n.sessionId,t)?await D(e,t.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`${a.label} app-log descriptor paths do not match the owning session`}}),s=Object.freeze({appLogInspect:async()=>({backend:a.backend}),appLogDoctor:async({appBundleId:r})=>await a.doctor({host:e,device:t,signal:n},r),...r.start?{appLogStart:async o=>await Oe(e,t,n,r,i,o,a)}:{},...o});return Object.freeze({device:t,owner:i,facts:F(t,r,a),operations:s,[Symbol.asyncDispose]:async()=>void 0})}function F(e,t,n){let r=t.start?P:{available:!1,reason:`owner-capability-missing`,hint:n.startUnavailableHint};return Object.freeze({device:{family:n.family,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:P,appLogDoctor:P,appLogStart:r,appLogReattach:P,appLogCleanup:P}})}async function Oe(t,n,r,i,a,o,s){if(!i.start)throw new e(`UNSUPPORTED_OPERATION`,s.startUnavailableHint);N(t,o);let c=t.artifacts.resolveSession(o.sessionId),l={host:t,device:n,signal:r,input:o,artifacts:c,transport:i};s.validateStart?.(l),r.throwIfAborted();let u=await s.process(l);r.throwIfAborted();let d=await Ce({host:t,backend:s.backend,outputPath:c.outputPath,pidPath:c.pidPath,processStart:i.start,setupSignal:r,resolvePid:u.resolvePid,command:u.command,cleanupFailureMessage:s.cleanupFailureMessage}),f=s.descriptor({artifacts:c,transport:i});return p(d,s.envelope({input:o,device:n,owner:a,descriptor:f}))}function I(e){for(let t of[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i]){let n=t.exec(e);if(!n)continue;let r=Number.parseInt(n[1]??``,10);if(Number.isInteger(r))return r}return null}function L(e){return/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e)?.[0]??/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e)?.[0]}function ke(e){let t=e.indexOf(`{`),n=e.lastIndexOf(`}`);if(t<0||n<=t)return null;try{let r=JSON.parse(e.slice(t,n+1));return r&&typeof r==`object`&&!Array.isArray(r)?r:null}catch{return null}}function R(e,t){for(let n of t){let t=e?.[n];if(typeof t==`string`&&t.trim())return t.trim()}}function Ae(e,t){for(let n of t){let t=e?.[n];if(typeof t==`number`&&Number.isInteger(t))return t;if(typeof t==`string`&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t,10)}return null}function je(e,t){let n=t?.headers??t?.requestHeaders??t?.responseHeaders;return n===void 0?/\bheaders?["'=: ]+(\{.*\})/i.exec(e)?.[1]?.trim():B(n)}function z(e,t,n){for(let r of n){if(t?.[r]!==void 0)return B(t[r]);let n=r.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),i=RegExp(`\\b${n}["'=: ]+(.+)$`,`i`).exec(e);if(i?.[1])return i[1].trim()}}function B(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function Me(e,t,n){let r=U(t,n,5),i=e.packetId??r.map(V).find(e=>typeof e==`string`&&e.length>0);i&&(e.packetId=i);let a=i?U(t,n,12).filter(e=>V(e)===i):r;e.timestamp??=a.map(L).find(e=>typeof e==`string`&&e.length>0),e.status??=a.map(I).find(e=>typeof e==`number`)??void 0,e.durationMs??=a.map(H).find(e=>typeof e==`number`)??void 0}function V(e){return/\bpacket id (\d+)\b/i.exec(e)?.[1]??null}function H(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);return t?Number.parseInt(t[1]??``,10):null}function U(e,t,n){return e.slice(Math.max(0,t-n),Math.min(e.length,t+n+1)).map(e=>e.trim()).filter(Boolean)}const Ne=RegExp(`\\b(${[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`].join(`|`)})\\b\\s+https?:\\/\\/`,`i`),Pe=/https?:\/\/[^\s"'<>\])]+/i,Fe=/\[C(\d+)\b[^\]]*?\burl:\s*([^\s,\]]+)/,W=/\bsummary for task (?:success|failure)\s*\{([^}]*)\}/,Ie=/\bTask\s+<([0-9A-Fa-f-]+)>\.<(\d+)>/,G=/(?:^|\s)(\S+)\[(\d+):[0-9a-f]+\]/,Le=/\burl:\s*(https?:\/\/[^\s,\]]+)/i;function Re(e,t,n=e.dump.limits.maxEntries){let r=[...e.dump.entries],i=new Set(r.map(K));for(let e of t.dump.entries){let t=K(e);if(!i.has(t)&&(i.add(t),r.push(e),r.length>=n))break}let a=new Set([...e.dump.entries,...t.dump.entries].map(e=>e.packetId).filter(e=>e!==void 0)),o=[...new Set([...e.unnamedRequestIds,...t.unnamedRequestIds])].filter(e=>!a.has(e));return Object.freeze({dump:Object.freeze({...e.dump,matchedLines:r.length,entries:Object.freeze(r),unnamedRequests:o.length}),unnamedRequestIds:Object.freeze(o)})}function ze(e,t){let n=J(t.maxEntries,25,1,200),r=t.include??`summary`,i=J(t.maxPayloadChars,2048,64,16384),a=J(t.maxScanLines,4e3,100,2e4),o=Ve(t.lineNumberOffset);if(!t.exists)return Object.freeze({dump:Object.freeze({path:t.path,exists:!1,scannedLines:0,matchedLines:0,entries:Object.freeze([]),unnamedRequests:0,include:r,limits:Object.freeze({maxEntries:n,maxPayloadChars:i,maxScanLines:a})}),unnamedRequestIds:Object.freeze([])});let s=e.split(`
1
+ import{O as e}from"./sdk-contracts.js";import{D as t}from"./sdk-device.js";import{Yt as n,en as r}from"./sdk-batch.js";import{t as i}from"./audio-probe-runtime.js";import{a,n as o,t as s}from"./durable-resource.js";import{n as c}from"./async-lifecycle.js";import{n as l,t as u}from"./audio-probe-result.js";import d from"node:fs/promises";function f(e,t){if(e.resourceKind!==t.resourceKind)return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Durable resource kind ${e.resourceKind} does not match ${t.resourceKind}`};if(e.descriptor.version!==t.version)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported ${t.resourceKind} descriptor version: ${e.descriptor.version}`,version:e.descriptor.version};try{let n=t.decode(e.descriptor.body);return n.status===`decoded`?n:{status:`unreattachable`,reason:`descriptor-invalid`,message:n.message}}catch(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e instanceof Error?e.message:`Descriptor codec rejected the body`}}}function p(e,t){return Object.freeze({pendingHandle:new c(e),envelope:t})}function m(e){return Object.freeze({appLogReattach:async({envelope:t})=>{let n=f(t,e.codec);return n.status===`unreattachable`?n:await e.reattach(n.descriptor,h(t))},appLogCleanup:async({envelope:t})=>{let n=f(t,e.codec);return n.status===`decoded`?await e.cleanup(n.descriptor,h(t)):{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message}}})}function h(e){return Object.freeze({sessionId:e.sessionId,fence:e.fence})}function g(e){if(typeof e!=`object`||!e||Array.isArray(e))return{status:`invalid`,message:`App-log process marker must be an object`};let t=e;return!Number.isInteger(t.pid)||Number(t.pid)<=0?{status:`invalid`,message:`App-log process marker pid must be a positive integer`}:typeof t.startTime!=`string`||t.startTime.trim().length===0?{status:`invalid`,message:`App-log process marker startTime must be a non-empty string`}:typeof t.command!=`string`||t.command.trim().length===0?{status:`invalid`,message:`App-log process marker command must be a non-empty string`}:{status:`decoded`,marker:Object.freeze({pid:Number(t.pid),startTime:t.startTime,command:t.command})}}function _(e){let t,n,r,i=()=>n??=e.forceCleanup();return Object.freeze({inspect:()=>e.inspect(),finish:()=>t??=e.finish(),forceCleanup:i,[Symbol.asyncDispose]:async()=>{r??=i().then(ee),await r}})}function v(e){return _({inspect:e.inspect,finish:e.finish,forceCleanup:async()=>{let t=await e.finish();return t.status===`completed`?{status:`cleaned`}:{status:`cleanup-pending`,reason:t.reason,message:t.message}}})}function ee(t){if(!s(t))throw new e(`COMMAND_FAILED`,t.message??`Durable resource cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:t.reason===`ownership-fence-lost`?`Use the current resource owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}const te=e=>b(e.backend)&&(e.source===`system-audio`||e.source===`media-elements`)&&x(e.sourceCount,0)&&re(e.notes)&&b(e.statusPath)&&x(e.startedAt,1)&&x(e.durationMs,1)&&x(e.bucketMs,1),y=Object.freeze({resourceKind:i,version:1,encode:e=>({...e,notes:[...e.notes],marker:{...e.marker}}),decode:e=>{let t=te(e)?ne(e.marker):`invalid`;if(t===`invalid`)return{status:`invalid`,message:`Audio probe descriptor body is invalid`};let n=e;return{status:`decoded`,descriptor:Object.freeze({backend:n.backend,source:n.source,sourceCount:n.sourceCount,notes:Object.freeze([...n.notes]),statusPath:n.statusPath,startedAt:n.startedAt,durationMs:n.durationMs,bucketMs:n.bucketMs,marker:t})}}});function ne(e){if(typeof e!=`object`||!e)return`invalid`;let t=e;return!x(t.pid,1)||!b(t.startTime)||!b(t.command)?`invalid`:Object.freeze({pid:t.pid,startTime:t.startTime,command:t.command})}function b(e){return typeof e==`string`&&e.length>0}function x(e,t){return typeof e==`number`&&Number.isInteger(e)&&e>=t}function re(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}async function S(e){try{let t=await d.readFile(e.statusPath,`utf8`);return l(JSON.parse(t),{source:e.source,backend:e.backend,durationMs:e.durationMs,elapsedMs:Date.now()-e.startedAt,bucketMs:e.bucketMs,activeFallback:!0,sourceCount:e.sourceCount,notes:[...e.notes]})}catch(e){if(e.code===`ENOENT`)return;throw e}}function C(e,t,n){let r=Math.min(e.durationMs,Math.max(0,Date.now()-e.startedAt));return{...t??u({source:e.source,backend:e.backend,durationMs:e.durationMs,bucketMs:e.bucketMs,sourceCount:e.sourceCount,notes:[...e.notes]}),state:`stopped`,active:!1,elapsedMs:r,stoppedAt:new Date().toISOString(),reason:n}}function ie(e){let{host:t}=e;return Object.freeze({audioProbeReattach:async e=>{let n=f(e.envelope,y);if(n.status!==`decoded`)return n;let r=n.descriptor,i=await t.inspectProcess(r.marker);if(i===`owned-alive`)return{status:`unreattachable`,reason:`transport-not-reattachable`};if(i===`ownership-lost`)return{status:`unreattachable`,reason:`ownership-fence-lost`};let a=await S(r);return a===void 0||a.state!==`stopped`?{status:`missing`}:{status:`completed`,result:C(r,a,`daemon-recovery`)}},audioProbeCleanup:async e=>{let n=f(e.envelope,y);if(n.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message};let r=n.descriptor,i=await t.inspectProcess(r.marker);if(i===`ownership-lost`)return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(i===`missing`)return{status:`already-missing`};let a=await t.terminateProcess(r.marker);return a===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:{status:a===`terminated`?`cleaned`:`already-missing`}}})}async function ae(n){let{host:r,device:s,owner:l,input:u}=n,f=Date.now(),p=r.info,m=Object.freeze([...p.notes(s)]),h=Object.freeze({source:p.source,backend:p.backend,sourceCount:p.sourceCount,notes:m,statusPath:u.statusPath,startedAt:f,durationMs:u.durationMs,bucketMs:u.bucketMs});await d.rm(u.statusPath,{force:!0});let g=await r.start({durationMs:u.durationMs,bucketMs:u.bucketMs,statusPath:u.statusPath});g.wait.catch(()=>{});let _=g.marker;try{if(_===void 0)throw new e(`COMMAND_FAILED`,`failed to start host audio probe: the helper process exposed no exact identity, so the capture could not be recovered after daemon loss and was terminated`);await ue(h,g)}catch(e){throw await g.terminate().catch(()=>{}),e}return Object.freeze({pendingHandle:new c(oe(h,g)),envelope:o({resourceKind:i,sessionId:u.sessionId,device:t(s),owner:l,fence:u.fence,lifecycle:`open`,descriptor:a(y,{backend:p.backend,source:p.source,sourceCount:p.sourceCount,notes:m,statusPath:u.statusPath,startedAt:f,durationMs:u.durationMs,bucketMs:u.bucketMs,marker:_})})})}function oe(e,t){let n,r,i,a;t.wait.then(e=>{a={message:se(e)}},e=>{a={message:e instanceof Error?e.message:`audio probe helper wait failed`}});let o=()=>n??=(async()=>{let n=await S(e);if(n?.state!==`stopped`&&a)throw w(a);return await t.terminate().catch(()=>{}),await t.wait.catch(()=>{}),{status:`completed`,result:C(e,n,`stopped`)}})(),s=()=>r??=n?n.then(async()=>({status:`cleaned`}),async()=>await T(t)):T(t);return Object.freeze({inspect:()=>e,status:async()=>{let t=await S(e);if(t?.state===`stopped`)return t;if(a)throw w(a);return t??C(e,void 0,`not-started`)},finish:o,forceCleanup:s,[Symbol.asyncDispose]:async()=>{i??=s().then(ce),await i}})}function se(e){return e.stderr?.trim()||e.stdout?.trim()||`audio probe helper exited with code ${e.exitCode??1}`}function w(t){return new e(`COMMAND_FAILED`,`host audio probe helper exited before completing the capture: ${t.message}`,{hint:`Keep audio-probe.resource.json; stop resolves the record through descriptor cleanup.`})}async function T(e){try{return await e.terminate(),await e.wait.catch(()=>{}),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:e instanceof Error?e.message:`Audio probe termination failed`}}}function ce(t){if(!s(t))throw new e(`COMMAND_FAILED`,t.message??`Audio probe cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`})}function le(e){let{host:t,device:n,owner:r}=e,i=ie({host:t});return Object.freeze({audioProbeStart:async e=>await ae({host:t,device:n,owner:r,input:e}),audioProbeReattach:i.audioProbeReattach,audioProbeCleanup:i.audioProbeCleanup})}async function ue(t,n){let r=Date.now()+5e3;for(;Date.now()<r;){if(await S(t))return;let r=await Promise.race([n.wait.then(e=>e,e=>e),de(100).then(()=>void 0)]);if(r instanceof Error)throw r;if(r){let t=r,n=t.stderr?.trim()||t.stdout?.trim()||`host audio probe helper exited with code ${t.exitCode??1}`;throw new e(`COMMAND_FAILED`,`failed to start host audio probe: ${n}`)}}throw new e(`COMMAND_FAILED`,`failed to start host audio probe`)}function de(e){return new Promise(t=>setTimeout(t,e))}async function E(e,t){let n=await O(e,t);if(n.status===`missing`)return{status:`missing`};if(n.status===`invalid`)return{status:`unreattachable`,reason:`ownership-fence-lost`,message:n.message};let r=await e.processes.inspect(n.marker);return r===`missing`?(t&&await e.processes.clearMarker(t),{status:`missing`}):r===`ownership-lost`?{status:`unreattachable`,reason:`ownership-fence-lost`}:{status:`unreattachable`,reason:`transport-not-reattachable`}}async function D(e,t){if(!t)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`App-log process marker path is missing`};let n=await O(e,t);if(n.status===`missing`)return{status:`already-missing`};if(n.status===`invalid`)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message};let r=await e.processes.inspect(n.marker);if(r===`ownership-lost`)return k();if(r===`missing`)return await e.processes.clearMarker(t),{status:`already-missing`};let i=await e.processes.terminate(n.marker);return i===`ownership-lost`?k():(await e.processes.clearMarker(t),{status:i===`terminated`?`cleaned`:`already-missing`})}async function O(e,t){return t?await e.processes.readMarker(t):{status:`invalid`,message:`App-log process marker path is missing`}}function k(){return{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function fe(e){let t=e.initialProcess;for(;!e.stopped();){if(t){await pe(e,t),t=void 0,await be(e);continue}let n=await xe(e);if(n.status===`stopped`)return;n.status!==`waiting`&&(t=n.process)}}async function pe(e,t){let{process:n}=t;e.setActive(n);try{e.setState(`active`),await me(e,t)}finally{await A(e,n)}}async function me(e,t){let n=he(t.process);try{await ge(e,t,n),await ve(e,t.process,n),await ye(n.outcome)}finally{n.controller.abort()}}function he(e){let t=new AbortController,n=!1,r=()=>{n=!0,t.abort()};return{controller:t,outcome:e.wait.then(()=>(r(),{status:`exited`}),e=>(r(),{status:`failed`,error:e})),settled:()=>n}}async function ge(e,t,n){for(;!e.stopped()&&!n.settled();){if(!await _e(e,n))return;let r=await e.resolvePid();if(e.stopped())return;if(r!==t.pid){await t.process.terminate();return}}}async function _e(e,t){try{await e.sleep(500,t.controller.signal)}catch(e){if(!t.settled())throw e}return!t.settled()}async function ve(e,t,n){e.stopped()&&!n.settled()&&await t.terminate()}async function ye(e){let t=await e;if(t.status===`failed`)throw t.error}async function be(e){e.stopped()||(e.setState(`recovering`),await e.sleep(500))}async function xe(e){let t=await e.resolvePid();if(e.stopped())return{status:`stopped`};if(!t)return e.setState(`recovering`),await e.sleep(1e3),{status:`waiting`};let n=await e.startProcess(t);return e.setActive(n),e.stopped()?(await Se(e,n),{status:`stopped`}):{status:`started`,process:{pid:t,process:n}}}async function Se(e,t){try{await t.terminate(),await t.wait}finally{await A(e,t)}}async function A(e,t){try{await t[Symbol.asyncDispose]()}finally{e.setActive(void 0)}}async function Ce(e){let t=await e.resolvePid(e.setupSignal);e.setupSignal.throwIfAborted();let n=await e.host.outputs.openAppend(e.outputPath),r=`recovering`,i=!1,a;try{if(e.setupSignal.throwIfAborted(),t){e.setupSignal.throwIfAborted();let i=new AbortController,o=()=>i.abort(e.setupSignal.reason);e.setupSignal.addEventListener(`abort`,o,{once:!0});try{a=await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath},i.signal)}finally{e.setupSignal.removeEventListener(`abort`,o)}e.setupSignal.throwIfAborted(),r=`active`}}catch(e){throw await j([async()=>await a?.terminate(),async()=>{await a?.wait},async()=>await a?.[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()]),e}let o=fe({initialProcess:a&&t?{pid:t,process:a}:void 0,stopped:()=>i,setActive:e=>{a=e},setState:e=>{r=e},resolvePid:async()=>await e.resolvePid(),startProcess:async t=>await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath}),sleep:async(t,n)=>await e.host.clock.sleep(t,n)}).catch(()=>{r=`failed`}),s,c=async()=>s??=we({options:e,monitor:o,active:()=>a,stop:()=>{i=!0},setState:e=>{r=e},output:n}),l=e.host.clock.now();return v({inspect:()=>({backend:e.backend,state:r,startedAt:l}),finish:c})}async function we(e){return e.stop(),(await j([async()=>await e.active()?.terminate(),async()=>await e.monitor,async()=>await e.output[Symbol.asyncDispose]()])).length>0?(e.setState(`failed`),{status:`cleanup-pending`,reason:`transport-failed`,message:e.options.cleanupFailureMessage}):(e.setState(`ended`),{status:`completed`,result:{backend:e.options.backend,outputPath:e.options.outputPath,completedAt:e.options.host.clock.now()}})}async function j(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}function M(e,t,n){let r=e.artifacts.resolveSession(t);return n.outputPath===r.outputPath&&(n.pidPath===void 0||n.pidPath===r.pidPath)}function N(t,n){if(!M(t,n.sessionId,n))throw new e(`INVALID_ARGS`,`App-log paths do not match the owning session`)}const P=Object.freeze({available:!0});async function Te(e,t,n){let r=(await e.commands.run(t,n)).stdout.trim().split(/\s+/)[0]??``;return/^\d+$/.test(r)?r:``}function Ee(t,i){let a=n(i.family);return Object.freeze({owner:a,ownsDevice:e=>e.platform===i.family,inspectFacts:async e=>F(e,await t.processTransports.resolve(e),i),bind:async n=>{if(n.intent.kind===`exact-owner`&&!r(n.intent.owner,a))throw new e(`UNSUPPORTED_OPERATION`,`${i.label} app-log owner identity does not match`);if(n.device.platform!==i.family)throw new e(`UNSUPPORTED_PLATFORM`,`${i.label} app-log owner cannot bind ${n.device.platform}`);let o=await t.processTransports.resolve(n.device);return De(t,n.device,n.scope.signal,o,a,i)},shutdown:async()=>void 0})}function De(e,t,n,r,i,a){let o=m({codec:a.codec,reattach:async(t,n)=>M(e,n.sessionId,t)?await E(e,t.pidPath):{status:`unreattachable`,reason:`descriptor-invalid`,message:`${a.label} app-log descriptor paths do not match the owning session`},cleanup:async(t,n)=>M(e,n.sessionId,t)?await D(e,t.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`${a.label} app-log descriptor paths do not match the owning session`}}),s=Object.freeze({appLogInspect:async()=>({backend:a.backend}),appLogDoctor:async({appBundleId:r})=>await a.doctor({host:e,device:t,signal:n},r),...r.start?{appLogStart:async o=>await Oe(e,t,n,r,i,o,a)}:{},...o});return Object.freeze({device:t,owner:i,facts:F(t,r,a),operations:s,[Symbol.asyncDispose]:async()=>void 0})}function F(e,t,n){let r=t.start?P:{available:!1,reason:`owner-capability-missing`,hint:n.startUnavailableHint};return Object.freeze({device:{family:n.family,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:P,appLogDoctor:P,appLogStart:r,appLogReattach:P,appLogCleanup:P}})}async function Oe(t,n,r,i,a,o,s){if(!i.start)throw new e(`UNSUPPORTED_OPERATION`,s.startUnavailableHint);N(t,o);let c=t.artifacts.resolveSession(o.sessionId),l={host:t,device:n,signal:r,input:o,artifacts:c,transport:i};s.validateStart?.(l),r.throwIfAborted();let u=await s.process(l);r.throwIfAborted();let d=await Ce({host:t,backend:s.backend,outputPath:c.outputPath,pidPath:c.pidPath,processStart:i.start,setupSignal:r,resolvePid:u.resolvePid,command:u.command,cleanupFailureMessage:s.cleanupFailureMessage}),f=s.descriptor({artifacts:c,transport:i});return p(d,s.envelope({input:o,device:n,owner:a,descriptor:f}))}function I(e){for(let t of[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i]){let n=t.exec(e);if(!n)continue;let r=Number.parseInt(n[1]??``,10);if(Number.isInteger(r))return r}return null}function L(e){return/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e)?.[0]??/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e)?.[0]}function ke(e){let t=e.indexOf(`{`),n=e.lastIndexOf(`}`);if(t<0||n<=t)return null;try{let r=JSON.parse(e.slice(t,n+1));return r&&typeof r==`object`&&!Array.isArray(r)?r:null}catch{return null}}function R(e,t){for(let n of t){let t=e?.[n];if(typeof t==`string`&&t.trim())return t.trim()}}function Ae(e,t){for(let n of t){let t=e?.[n];if(typeof t==`number`&&Number.isInteger(t))return t;if(typeof t==`string`&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t,10)}return null}function je(e,t){let n=t?.headers??t?.requestHeaders??t?.responseHeaders;return n===void 0?/\bheaders?["'=: ]+(\{.*\})/i.exec(e)?.[1]?.trim():B(n)}function z(e,t,n){for(let r of n){if(t?.[r]!==void 0)return B(t[r]);let n=r.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),i=RegExp(`\\b${n}["'=: ]+(.+)$`,`i`).exec(e);if(i?.[1])return i[1].trim()}}function B(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function Me(e,t,n){let r=U(t,n,5),i=e.packetId??r.map(V).find(e=>typeof e==`string`&&e.length>0);i&&(e.packetId=i);let a=i?U(t,n,12).filter(e=>V(e)===i):r;e.timestamp??=a.map(L).find(e=>typeof e==`string`&&e.length>0),e.status??=a.map(I).find(e=>typeof e==`number`)??void 0,e.durationMs??=a.map(H).find(e=>typeof e==`number`)??void 0}function V(e){return/\bpacket id (\d+)\b/i.exec(e)?.[1]??null}function H(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);return t?Number.parseInt(t[1]??``,10):null}function U(e,t,n){return e.slice(Math.max(0,t-n),Math.min(e.length,t+n+1)).map(e=>e.trim()).filter(Boolean)}const Ne=RegExp(`\\b(${[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`].join(`|`)})\\b\\s+https?:\\/\\/`,`i`),Pe=/https?:\/\/[^\s"'<>\])]+/i,Fe=/\[C(\d+)\b[^\]]*?\burl:\s*([^\s,\]]+)/,W=/\bsummary for task (?:success|failure)\s*\{([^}]*)\}/,Ie=/\bTask\s+<([0-9A-Fa-f-]+)>\.<(\d+)>/,G=/(?:^|\s)(\S+)\[(\d+):[0-9a-f]+\]/,Le=/\burl:\s*(https?:\/\/[^\s,\]]+)/i;function Re(e,t,n=e.dump.limits.maxEntries){let r=[...e.dump.entries],i=new Set(r.map(K));for(let e of t.dump.entries){let t=K(e);if(!i.has(t)&&(i.add(t),r.push(e),r.length>=n))break}let a=new Set([...e.dump.entries,...t.dump.entries].map(e=>e.packetId).filter(e=>e!==void 0)),o=[...new Set([...e.unnamedRequestIds,...t.unnamedRequestIds])].filter(e=>!a.has(e));return Object.freeze({dump:Object.freeze({...e.dump,matchedLines:r.length,entries:Object.freeze(r),unnamedRequests:o.length}),unnamedRequestIds:Object.freeze(o)})}function ze(e,t){let n=J(t.maxEntries,25,1,200),r=t.include??`summary`,i=J(t.maxPayloadChars,2048,64,16384),a=J(t.maxScanLines,4e3,100,2e4),o=Ve(t.lineNumberOffset);if(!t.exists)return Object.freeze({dump:Object.freeze({path:t.path,exists:!1,scannedLines:0,matchedLines:0,entries:Object.freeze([]),unnamedRequests:0,include:r,limits:Object.freeze({maxEntries:n,maxPayloadChars:i,maxScanLines:a})}),unnamedRequestIds:Object.freeze([])});let s=e.split(`
2
2
  `),c=Math.max(0,s.length-a),l=s.slice(c),u=[],d=Be(t.backend)?Qe(l):void 0,f=d?et(l,d):[];for(let e=l.length-1;e>=0&&u.length<n;--e){if(!l[e]?.trim())continue;let n=He(l,e,o+c+e+1,t.backend,r,i,d);n&&u.push(n)}return Object.freeze({dump:Object.freeze({path:t.path,exists:!0,scannedLines:l.length,matchedLines:u.length,entries:Object.freeze(u),unnamedRequests:f.length,include:r,limits:Object.freeze({maxEntries:n,maxPayloadChars:i,maxScanLines:a})}),unnamedRequestIds:Object.freeze(f)})}function Be(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Ve(e){if(e===void 0)return 0;if(!Number.isInteger(e)||e<0)throw TypeError(`Network line number offset must be a non-negative integer`);return e}function He(e,t,n,r,i,a,o){let s=e[t]?.trim();if(!s)return null;let c=ke(s),l=Ue(s,c)??(o?$e(s,o,t):null);if(!l)return null;let u=Je(s,n,l,a);return r===`android`&&Me(u,e,t),Ye(u,s,c,i,a),u}function Ue(e,t){let n=We(e,t),r=Ge(e,t);if(!r)return null;let i=Ke(e,t);return qe(e,n.explicit,i)?{method:n.value,url:r,status:i}:null}function We(e,t){let n=R(t,[`method`,`httpMethod`]),r=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(e)?.[1],i=Ne.exec(e)?.[1],a=n??r??i;return{value:a?.toUpperCase(),explicit:!!a}}function Ge(e,t){return R(t,[`url`,`requestUrl`])||(Le.exec(e)?.[1]??Pe.exec(e)?.[0])}function Ke(e,t){return Ae(t,[`status`,`statusCode`,`responseCode`])??I(e)??void 0}function qe(e,t,n){return t||n!==void 0||/\bURL["'=: ]+https?:\/\//i.test(e)||/\bheaders?["'=: ]+/i.test(e)||/\b(?:requestBody|responseBody|payload|request|response)["'=: ]+/i.test(e)}function Je(e,t,n,r){return{...n,timestamp:L(e),packetId:n.packetId??V(e)??void 0,durationMs:n.durationMs??H(e)??void 0,raw:q(e,r),line:t}}function Ye(e,t,n,r,i){if(Xe(r)){let r=je(t,n);r&&(e.headers=q(r,i))}if(Ze(r)){let r=z(t,n,[`requestBody`,`body`,`payload`,`request`]),a=z(t,n,[`responseBody`,`response`]);r&&(e.requestBody=q(r,i)),a&&(e.responseBody=q(a,i))}}function Xe(e){return e===`headers`||e===`all`}function Ze(e){return e===`body`||e===`all`}function K(e){return`${e.timestamp??``}|${e.method??``}|${e.url}|${e.status??``}|${e.raw}`}function q(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function J(e,t,n,r){return e===void 0||!Number.isInteger(e)?t:Math.max(n,Math.min(r,e))}function Qe(e){let t=new Map;for(let[n,r]of e.entries()){let e=Fe.exec(r);if(!e)continue;let i=Y(r,e[1]),a=i===void 0?void 0:nt(e[2]);if(!a||i===void 0)continue;let o=t.get(i);o?o.push({lineIndex:n,origin:a}):t.set(i,[{lineIndex:n,origin:a}])}return t}function Y(e,t){let n=G.exec(e);if(n)return`${n[1]}[${n[2]}]#${t}`}function $e(e,t,n){let r=W.exec(e);if(!r)return null;let i=Q(r[1]);if(i.get(`reused`)!==`1`)return null;let a=i.get(`connection`),o=a===void 0?void 0:Y(e,a),s=o===void 0?void 0:Z(t,o,n);return s?{url:s,status:rt(i.get(`response_status`)),durationMs:$(i.get(`transaction_duration_ms`)),pathUnavailable:!0,packetId:X(e)}:null}function et(e,t){let n=new Set;for(let[r,i]of e.entries()){let e=tt(i,t,r);e!==void 0&&n.add(e)}return[...n]}function tt(e,t,n){if(!e.includes(`summary for task`))return;let r=W.exec(e);if(!r)return;let i=Q(r[1]);if(i.get(`reused`)!==`1`)return;let a=i.get(`connection`),o=a===void 0?void 0:Y(e,a);if(!(o!==void 0&&Z(t,o,n)))return X(e)}function X(e){let t=Ie.exec(e);if(!t)return;let n=G.exec(e);return`${n?`${n[1]}[${n[2]}]`:``}#${t[1]}.${t[2]}`}function Z(e,t,n){let r=e.get(t);if(!r)return;let i;for(let e of r){if(e.lineIndex>n)break;i=e.origin}return i}function Q(e){let t=new Map;for(let n of e.split(`,`)){let e=n.indexOf(`=`);e!==-1&&t.set(n.slice(0,e).trim(),n.slice(e+1).trim())}return t}function nt(e){try{return new URL(e).origin}catch{return}}function rt(e){let t=$(e);return t!==void 0&&t>0?t:void 0}function $(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}export{M as a,E as c,m as d,p as f,Te as i,le as l,f as m,ze as n,N as o,g as p,Ee as r,D as s,Re as t,v as u};
package/dist/src/src8.js CHANGED
@@ -1,4 +1,4 @@
1
- import{i as e,r as t,t as n}from"./rolldown-runtime.js";import{D as r,k as i}from"./sdk-contracts.js";import a from"node:path";function o(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function s(e){return e.trim().toLowerCase().replaceAll(/\s+/g,` `)}function c(e){return[e.label,e.value,e.identifier].find(e=>typeof e==`string`&&e.length>0)?.trim()??``}function l(e={},t={}){let n={...t},i=u(e),a=[],o,s=0,c;return{get values(){return l()},get generation(){return s},get observation(){return c?.generation===s?c:void 0},enter(e={}){let t=f(e);return a.push(t),o=void 0,()=>{if(a.pop()!==t)throw new r(`COMMAND_FAILED`,`Maestro environment scopes were left out of order.`);o=void 0}},merge(e){i={...i,...e},o=void 0},replaceOutput(e){let t={};for(let[e,n]of Object.entries(i))e===`output`||e.startsWith(`output.`)||(t[e]=n);Object.assign(t,e),i=t,o=void 0},recordObservation(e){if(e.generation!==s)throw new r(`COMMAND_FAILED`,`Maestro observation generation ${e.generation} does not match ${s}.`);c=e},invalidateObservation(){s+=1,c=void 0},resolve(e){return d(e,l())},resolveDeferred(e){return d(e,l(),new Set,!1)}};function l(){return o||(o={...a.reduce((e,t)=>({...e,...t}),{...i}),...n},o)}function f(e){let t=u(e),r={};for(let[e,i]of Object.entries(t))r[e]=d(i,{...l(),...t,...r,...n},new Set,!1);return r}}function u(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function d(e,t,n=new Set,i=!0){let a=e.replaceAll(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,a)=>{if(!Object.hasOwn(t,a)){if(!i)return e;throw new r(`INVALID_ARGS`,`Maestro variable "${a}" is not defined.`)}if(n.has(a)){if(!i)return e;throw new r(`INVALID_ARGS`,`Maestro variable "${a}" has a cyclic reference.`)}return d(t[a],t,new Set([...n,a]),i)});return i&&f(a),a}function f(e){for(let t of e.matchAll(/\$\{[^{}]*\}/g))if(!p(t[0]))throw new r(`INVALID_ARGS`,`Maestro interpolation "${t[0]}" is unresolved or unsupported.`)}function p(e){return/^\$\{\s*maestro\.platform\s*(?:==|!=)\s*(['"]).*\1(?:\s*(?:&&|\|\|).*)?\s*\}$/.test(e)}var m=n((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),h=n((e=>{var t=m();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),g=n((e=>{var t=m(),n=h();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
1
+ import{i as e,r as t,t as n}from"./rolldown-runtime.js";import{A as r,O as i}from"./sdk-contracts.js";import a from"node:path";function o(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function s(e){return e.trim().toLowerCase().replaceAll(/\s+/g,` `)}function c(e){return[e.label,e.value,e.identifier].find(e=>typeof e==`string`&&e.length>0)?.trim()??``}function l(e={},t={}){let n={...t},r=u(e),a=[],o,s=0,c;return{get values(){return l()},get generation(){return s},get observation(){return c?.generation===s?c:void 0},enter(e={}){let t=f(e);return a.push(t),o=void 0,()=>{if(a.pop()!==t)throw new i(`COMMAND_FAILED`,`Maestro environment scopes were left out of order.`);o=void 0}},merge(e){r={...r,...e},o=void 0},replaceOutput(e){let t={};for(let[e,n]of Object.entries(r))e===`output`||e.startsWith(`output.`)||(t[e]=n);Object.assign(t,e),r=t,o=void 0},recordObservation(e){if(e.generation!==s)throw new i(`COMMAND_FAILED`,`Maestro observation generation ${e.generation} does not match ${s}.`);c=e},invalidateObservation(){s+=1,c=void 0},resolve(e){return d(e,l())},resolveDeferred(e){return d(e,l(),new Set,!1)}};function l(){return o||(o={...a.reduce((e,t)=>({...e,...t}),{...r}),...n},o)}function f(e){let t=u(e),r={};for(let[e,i]of Object.entries(t))r[e]=d(i,{...l(),...t,...r,...n},new Set,!1);return r}}function u(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function d(e,t,n=new Set,r=!0){let a=e.replaceAll(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,a)=>{if(!Object.hasOwn(t,a)){if(!r)return e;throw new i(`INVALID_ARGS`,`Maestro variable "${a}" is not defined.`)}if(n.has(a)){if(!r)return e;throw new i(`INVALID_ARGS`,`Maestro variable "${a}" has a cyclic reference.`)}return d(t[a],t,new Set([...n,a]),r)});return r&&f(a),a}function f(e){for(let t of e.matchAll(/\$\{[^{}]*\}/g))if(!p(t[0]))throw new i(`INVALID_ARGS`,`Maestro interpolation "${t[0]}" is unresolved or unsupported.`)}function p(e){return/^\$\{\s*maestro\.platform\s*(?:==|!=)\s*(['"]).*\1(?:\s*(?:&&|\|\|).*)?\s*\}$/.test(e)}var m=n((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),h=n((e=>{var t=m();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),g=n((e=>{var t=m(),n=h();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
2
2
  `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),_=n((e=>{var t=m(),n=h();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),v=n((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),y=n((e=>{var t=m();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),b=n((e=>{var t=v(),n=m(),r=y();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),x=n((e=>{var t=_(),n=h(),r=m(),i=b(),a=y(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),S=n((e=>{var t=m(),n=b(),r=y();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),C=n((e=>{var t=x(),n=m(),r=S();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??(f.anchor=c(e)),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),w=n((e=>{var t=C(),n=m(),r=b();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),T=n((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
3
3
  `)?n(r,t):r.includes(`
4
4
  `)?`
@@ -112,4 +112,4 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
112
112
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
113
113
  `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){u(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(a(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=l(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(a(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(s(t.key)&&!a(t.sep,`newline`)){let e=l(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):a(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!a(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){u(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||a(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=l(c(t));d(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
114
114
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
115
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=l(c(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=l(c(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Xe=n((e=>{var t=He(),n=Ee(),r=De(),i=re(),a=m(),o=Je(),s=Ye();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Ze=n((e=>{var t=He(),n=Ee(),r=we(),i=De(),a=x(),o=m(),s=D(),c=S(),l=O(),u=A();Ke();var d=qe(),f=Je(),p=Ye(),g=Xe(),_=h();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=g.parse,e.parseAllDocuments=g.parseAllDocuments,e.parseDocument=g.parseDocument,e.stringify=g.stringify,e.visit=_.visit,e.visitAsync=_.visitAsync})),P=Ze();function F(e,t){return Qe(e?.range?.[0],t)}function Qe(e,t){let n=t.lineCounter.linePos(e!==void 0&&e>=0?e:0).line;return t.sourcePath===void 0?{line:n}:{path:t.sourcePath,line:n}}function $e(e){return`${e.path===void 0?``:`${e.path}:`}line ${e.line}`}function I(e,t,n){throw new r(`INVALID_ARGS`,`${e} (${$e(F(t,n))})`)}function L(e,t,n){(0,P.isMap)(e)||I(`Maestro ${t} expects a map.`,e,n);let r=[];for(let i of e.items){let e=i.key;(0,P.isScalar)(e)||I(`Maestro ${t} map keys must be strings.`,void 0,n);let a=e.value;typeof a!=`string`&&typeof a!=`number`&&typeof a!=`boolean`&&I(`Maestro ${t} map keys must be strings.`,e,n),i.value!==null&&!(0,P.isNode)(i.value)&&I(`Maestro ${t} values must be YAML nodes.`,e,n),r.push({key:String(a),keyNode:e,value:i.value})}return r}function R(e,t,n){return(0,P.isSeq)(e)||I(`Maestro ${t} expects a list.`,e,n),e.items}function et(e,t,n){return R(e,t,n).map((e,r)=>K(e,`${t}[${r}]`,n))}function z(e,t,n,r){let i=new Set(n),a=new Set;for(let n of e)a.has(n.key)&&I(`Maestro ${t} contains duplicate field "${n.key}".`,n.keyNode,r),a.add(n.key),i.has(n.key)||I(`Maestro ${t} field "${n.key}" is not supported.`,n.keyNode,r)}function B(e,t){return e.some(e=>e.key===t)}function V(e,t){return e.find(e=>e.key===t)?.value}function H(e,t,n){return B(e,t)?n(V(e,t)):void 0}function U(e,t,n){return o({optional:H(e,`optional`,e=>J(e,`${t}.optional`,n))})}function W(e){return e===null||(0,P.isScalar)(e)&&e.value===null}function G(e,t,n){if(e==null)return null;(0,P.isScalar)(e)||I(`Maestro ${t} expects a scalar value.`,e,n);let r=e.value;if(r===null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return r;I(`Maestro ${t} contains an unsupported scalar value.`,e,n)}function K(e,t,n){let r=G(e,t,n);return typeof r!=`string`&&I(`Maestro ${t} expects a string.`,e,n),r}function q(e,t,n){let r=G(e,t,n);if(r!==null)return typeof r!=`string`&&I(`Maestro ${t} expects a string.`,e,n),r}function J(e,t,n){let r=G(e,t,n);if(r!==null)return typeof r!=`boolean`&&I(`Maestro ${t} expects a boolean.`,e,n),r}const tt=/^\$\{[A-Za-z_][A-Za-z0-9_.]*\}$/,nt=new Set([`allow`,`deny`,`unset`,`always`,`inuse`,`never`,`limited`]),rt=/^-?\d+(\.\d+)?$/,it=/^-?\d+$/,at={"tapOn.index":{integer:!0,nonNegative:!0},"tapOn.repeat":{integer:!0,positive:!0},"tapOn.delay":{integer:!0,nonNegative:!0},"doubleTapOn.delay":{integer:!0,nonNegative:!0},eraseText:{integer:!0,positive:!0},"eraseText.charactersToErase":{integer:!0,positive:!0},"extendedWaitUntil.timeout":{nonNegative:!0},"scrollUntilVisible.timeout":{nonNegative:!0},waitForAnimationToEnd:{nonNegative:!0},"waitForAnimationToEnd.timeout":{nonNegative:!0},"swipe.duration":{nonNegative:!0},"repeat.times":{integer:!0,nonNegative:!0},"retry.maxRetries":{integer:!0,nonNegative:!0}};function ot(e){return e.positive&&e.integer?`a positive integer`:e.positive?`a positive number`:e.nonNegative&&e.integer?`a non-negative integer`:e.nonNegative?`a non-negative finite number`:e.integer?`an integer`:`a finite number`}function st(e,t,n,r,i){let a=`Maestro ${t} expects ${ot(i)} or a variable expression.`;Number.isFinite(e)||I(a,n,r),Math.abs(e)>2**53-1&&I(a,n,r),i.integer&&!Number.isSafeInteger(e)&&I(a,n,r),i.nonNegative&&e<0&&I(a,n,r),i.positive&&e<=0&&I(a,n,r)}function ct(e,t,n,r,i){if(typeof e==`number`)return st(e,t,n,r,i),e;if(typeof e==`string`){if(tt.test(e))return e;if((i.integer?it:rt).test(e)){let a=Number(e);return st(a,t,n,r,i),a}}I(`Maestro ${t} expects ${ot(i)} or a variable expression.`,n,r)}function Y(e,t,n,r=at[t]??{}){let i=G(e,t,n);if(i!==null)return ct(i,t,e,n,r)}function lt(e,t,n){let r=at[t]??{},i=G(e,t,n);return i===null&&I(`Maestro ${t} expects ${ot(r)} or a variable expression.`,e,n),ct(i,t,e,n,r)}function ut(e,t,n){let r=G(e,t,n);return r===null&&I(`Maestro ${t} requires a condition.`,e,n),typeof r==`string`&&r.includes("${")&&!tt.test(r)&&I(`Maestro ${t} only supports a literal value or a bare \${VAR} lookup; JavaScript expressions are not supported — compute it in a runScript and reference \${output.x}.`,e,n),r}function dt(e,t,n){let r=L(e,t,n),i={};for(let e of r){let r=G(e.value,`${t}.${e.key}`,n);r===null&&I(`Maestro ${t}.${e.key} expects a string, number, or boolean.`,e.value,n),i[e.key]=r}return i}function X(e,t,n){return H(e,`label`,e=>q(e,`${t}.label`,n))}const Z=[`id`,`text`,`enabled`,`selected`,`index`,`childOf`,`below`,`above`,`leftOf`,`rightOf`,`containsChild`,`containsDescendants`],ft={textKeys:[`id`,`text`],booleanKeys:[`enabled`,`selected`],textAliases:{label:`text`}},pt={id:(e,t,n,r)=>vt(e,`id`,t,n,r),text:(e,t,n,r)=>vt(e,`text`,t,n,r),enabled:(e,t,n,r)=>yt(e,`enabled`,t,n,r),selected:(e,t,n,r)=>yt(e,`selected`,t,n,r),index:(e,t,n,r)=>{e.index=Y(t.value,`${n}.index`,r,{integer:!0,nonNegative:!0})},childOf:(e,t,n,r)=>{e.childOf=Q(t.value,`${n}.childOf`,r)},below:(e,t,n,r)=>{e.below=Q(t.value,`${n}.below`,r)},above:(e,t,n,r)=>{e.above=Q(t.value,`${n}.above`,r)},leftOf:(e,t,n,r)=>{e.leftOf=Q(t.value,`${n}.leftOf`,r)},rightOf:(e,t,n,r)=>{e.rightOf=Q(t.value,`${n}.rightOf`,r)},containsChild:(e,t,n,r)=>{e.containsChild=Q(t.value,`${n}.containsChild`,r)},containsDescendants:(e,t,n,r)=>{e.containsDescendants=R(t.value,`${n}.containsDescendants`,r).map(e=>Q(e,`${n}.containsDescendants`,r))},optional:(e,t,n,r)=>yt(e,`optional`,t,n,r)};function Q(e,t,n,r=Z){if((0,P.isScalar)(e))return{text:K(e,t,n)};let i=L(e,t,n);return z(i,t,r,n),mt(i,t,n)}function mt(e,t,n){e.length===0&&I(`Maestro ${t} selector is empty.`,void 0,n);let r={};for(let i of e){let e=pt[i.key];e||I(`Maestro ${t} selector field "${i.key}" is not supported.`,i.keyNode,n),e(r,i,t,n)}return Object.keys(r).filter(e=>e!==`optional`).length===0&&I(`Maestro ${t} selector must contain a selector value.`,e[0]?.keyNode,n),r}function ht(e,t,n,r){let i=F(t,n);if((0,P.isScalar)(e))return{source:i,entries:[],target:xt(Q(e,r.name,n,r.selectorKeys))};let a=L(e,r.name,n),o=B(a,`point`);if(z(a,r.name,o?r.pointAllowedKeys:r.selectorAllowedKeys,n),o){let e=r.pointConflictingSelectorKeys??r.selectorKeys;return a.some(t=>bt(t.key,e))&&I(`Maestro ${r.name}.point cannot be combined with a selector.`,t,n),{source:i,entries:a,target:r.parsePoint(V(a,`point`),`${r.name}.point`,n)}}return{source:i,entries:a,target:xt(mt(a.filter(e=>bt(e.key,r.selectorKeys)),r.name,n))}}function gt(e,t,n){let r=K(e,t,n),i=/^\s*(\d+)\s*,\s*(\d+)\s*$/.exec(r);if(i)return{space:`absolute`,x:Number(i[1]),y:Number(i[2])};let a=/^\s*(\d+)%\s*,\s*(\d+)%\s*$/.exec(r);if(a){let r=Number(a[1]),i=Number(a[2]);return(r>100||i>100)&&I(`Maestro ${t} percentage coordinates must be between 0% and 100%.`,e,n),{space:`percent`,x:r,y:i}}/^\s*\d+(?:\.\d+)?%\s*,\s*\d+(?:\.\d+)?%\s*$/.test(r)&&I(`Maestro ${t} percentage coordinates must be whole numbers.`,e,n),I(`Maestro ${t} expects absolute or percentage coordinates.`,e,n)}function _t(e,t,n){let r=gt(e,t,n);return r.space!==`absolute`&&I(`Maestro ${t} only supports absolute coordinates.`,e,n),r}function vt(e,t,n,r,i){let a=q(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function yt(e,t,n,r,i){let a=J(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function bt(e,t){return t.includes(e)}function xt(e){return{space:`target`,selector:e}}function St(e,t,n){let r=ht(e,t,n,{name:`tapOn`,selectorKeys:Z,pointConflictingSelectorKeys:Z,pointAllowedKeys:[`point`,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],selectorAllowedKeys:[...Z,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],parsePoint:gt});if(r.entries.length===0)return{kind:`tapOn`,source:r.source,target:r.target};if(r.target.space!==`target`)return{kind:`tapOn`,source:r.source,target:r.target,...kt(r.entries,n)};let i=kt(r.entries,n);return o({kind:`tapOn`,source:r.source,target:r.target,...i})}function Ct(e,t,n){let r=ht(e,t,n,{name:`doubleTapOn`,selectorKeys:Z,pointAllowedKeys:[`point`,`delay`,`optional`,`label`],selectorAllowedKeys:[...Z,`delay`,`optional`,`label`],parsePoint:_t}),i=U(r.entries,`doubleTapOn`,n),a=B(r.entries,`delay`)?Y(V(r.entries,`delay`),`doubleTapOn.delay`,n):void 0,s=X(r.entries,`doubleTapOn`,n);return o({kind:`doubleTapOn`,source:r.source,target:r.target,...i,delay:a,label:s})}function wt(e,t,n){let r=ht(e,t,n,{name:`longPressOn`,selectorKeys:Z,pointAllowedKeys:[`point`,`optional`,`label`],selectorAllowedKeys:[...Z,`optional`,`label`],parsePoint:_t});return o({kind:`longPressOn`,source:r.source,target:r.target,...U(r.entries,`longPressOn`,n),label:X(r.entries,`longPressOn`,n)})}function Tt(e,t,n){let r=F(t,n),i=L(e,`swipe`,n);z(i,`swipe`,[`start`,`end`,`direction`,`duration`,`from`,`label`,`optional`],n);let a=U(i,`swipe`,n),o=X(i,`swipe`,n),s=B(i,`duration`)?Y(V(i,`duration`),`swipe.duration`,n):void 0;if(B(i,`start`)||B(i,`end`))return{...Et(i,r,s,t,n),...a,label:o};let c=B(i,`direction`)?At(V(i,`direction`),`swipe.direction`,n):void 0;return B(i,`from`)?{...Dt(i,r,c,s,t,n),...a,label:o}:{...Ot(r,c,s,t,n),...a,label:o}}function Et(e,t,n,r,i){B(e,`direction`)&&I(`Maestro swipe cannot combine direction with start/end coordinates.`,r,i),(!B(e,`start`)||!B(e,`end`))&&I(`Maestro swipe requires both start and end coordinates.`,r,i);let a=gt(V(e,`start`),`swipe.start`,i),s=gt(V(e,`end`),`swipe.end`,i);return a.space!==s.space&&I(`Maestro swipe start/end must use the same coordinate space.`,r,i),{kind:`swipe`,source:t,gesture:o({kind:`coordinates`,start:a,end:s,duration:n})}}function Dt(e,t,n,r,i,a){return n===void 0&&I(`Maestro target swipe requires direction.`,i,a),{kind:`swipe`,source:t,gesture:o({kind:`target`,from:Q(V(e,`from`),`swipe.from`,a),direction:n,duration:r})}}function Ot(e,t,n,r,i){return t===void 0&&I(`Maestro swipe requires direction, target, or start/end coordinates.`,r,i),{kind:`swipe`,source:e,gesture:o({kind:`screen`,direction:t,duration:n})}}function kt(e,t){let n=H(e,`retryTapIfNoChange`,e=>J(e,`tapOn.retryTapIfNoChange`,t)),r=H(e,`repeat`,e=>lt(e,`tapOn.repeat`,t)),i=H(e,`delay`,e=>Y(e,`tapOn.delay`,t)),a=U(e,`tapOn`,t).optional;return o({retryTapIfNoChange:n,repeat:r,delay:i,optional:a,label:X(e,`tapOn`,t)})}function At(e,t,n){let r=K(e,t,n).toLowerCase();if(r===`up`||r===`down`||r===`left`||r===`right`)return r;I(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`,e,n)}function jt(e,t,n,r){let i=F(n,r);if((0,P.isScalar)(t))return{kind:e,source:i,target:Q(t,e,r)};let a=L(t,e,r);z(a,e,[...Z,`optional`,`label`],r);let s=U(a,e,r),c=X(a,e,r);return o({kind:e,source:i,target:mt(a.filter(e=>e.key!==`optional`&&e.key!==`label`),e,r),...s,label:c})}const Mt=[...Z,`optional`];function Nt(e,t,n,r){if(!B(e,t))return;let{optional:i,...a}=Q(V(e,t),n,r,Mt);return{selector:a,optional:i}}function Pt(e,t,n){let r=Nt(e,`visible`,`extendedWaitUntil.visible`,n),i=Nt(e,`notVisible`,`extendedWaitUntil.notVisible`,n);return r&&i&&I(`Maestro extendedWaitUntil cannot specify both visible and notVisible.`,t,n),!r&&!i&&I(`Maestro extendedWaitUntil requires visible or notVisible.`,t,n),r?{key:`visible`,selector:r.selector,optional:r.optional}:{key:`notVisible`,selector:i.selector,optional:i.optional}}function Ft(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`runScript`,source:r,file:K(e,`runScript`,n)};let i=L(e,`runScript`,n);return z(i,`runScript`,[`file`,`env`],n),B(i,`file`)||I(`Maestro runScript requires a file.`,t,n),o({kind:`runScript`,source:r,file:K(V(i,`file`),`runScript.file`,n),env:B(i,`env`)?dt(V(i,`env`),`runScript.env`,n):void 0})}function It(e,t,n,r){let i=F(t,n);if((0,P.isScalar)(e))return{kind:`runFlow`,source:i,include:{kind:`file`,path:K(e,`runFlow`,n)}};let a=L(e,`runFlow`,n);z(a,`runFlow`,[`file`,`commands`,`env`,`when`,`label`],n);let s=B(a,`file`);return s===B(a,`commands`)&&I(`Maestro runFlow requires exactly one of file or commands.`,t,n),o({kind:`runFlow`,source:i,include:s?{kind:`file`,path:K(V(a,`file`),`runFlow.file`,n)}:{kind:`commands`,commands:r(V(a,`commands`),`runFlow.commands`,n)},env:B(a,`env`)?dt(V(a,`env`),`runFlow.env`,n):void 0,when:B(a,`when`)?zt(V(a,`when`),n):void 0,label:X(a,`runFlow`,n)})}function Lt(e,t,n,r){let i=F(t,n),a=L(e,`repeat`,n);return z(a,`repeat`,[`times`,`commands`,`while`],n),B(a,`while`)&&I(`Maestro repeat.while is not supported; use repeat.times.`,V(a,`while`),n),B(a,`times`)||I(`Maestro repeat requires times.`,t,n),B(a,`commands`)||I(`Maestro repeat requires commands.`,t,n),{kind:`repeat`,source:i,times:lt(V(a,`times`),`repeat.times`,n),commands:r(V(a,`commands`),`repeat.commands`,n)}}function Rt(e,t,n,r){let i=F(t,n),a=L(e,`retry`,n);z(a,`retry`,[`maxRetries`,`commands`],n),B(a,`commands`)||I(`Maestro retry requires commands.`,t,n);let s=B(a,`maxRetries`)?lt(V(a,`maxRetries`),`retry.maxRetries`,n):void 0;return o({kind:`retry`,source:i,commands:r(V(a,`commands`),`retry.commands`,n),maxRetries:s})}function zt(e,t){let n=L(e,`runFlow.when`,t);return z(n,`runFlow.when`,[`platform`,`visible`,`notVisible`,`true`],t),n.length===0&&I(`Maestro runFlow.when cannot be empty.`,e,t),o({platform:H(n,`platform`,e=>Vt(e,t)),visible:H(n,`visible`,e=>Q(e,`runFlow.when.visible`,t)),notVisible:H(n,`notVisible`,e=>Q(e,`runFlow.when.notVisible`,t)),true:H(n,`true`,e=>Bt(e,t))})}function Bt(e,t){let n=G(e,`runFlow.when.true`,t);if(typeof n==`boolean`||typeof n==`string`)return n;I(`Maestro runFlow.when.true expects a boolean or expression string.`,e,t)}function Vt(e,t){let n=K(e,`runFlow.when.platform`,t).toLowerCase();if(n===`android`||n===`ios`||n===`web`)return n;I(`Maestro runFlow.when.platform expects Android, iOS, or Web.`,e,t)}function $(e,t,n){return R(e,t,n).map(e=>Ht(e,n))}function Ht(e,t){if((0,P.isScalar)(e))return typeof e.value!=`string`&&I(`Maestro command names must be strings.`,e,t),Ut(e.value,e,t);(0,P.isMap)(e)||I(`Maestro commands must be a scalar or one-key map.`,e,t);let n=L(e,`command`,t);n.length!==1&&I(`Maestro command maps must contain exactly one command.`,e,t);let r=n[0];return Gt(r.key,r.value,e,t)}function Ut(e,t,n){return Gt(e,null,t,n)}const Wt={launchApp:Kt,tapOn:St,doubleTapOn:Ct,longPressOn:wt,inputText:qt,eraseText:Jt,openLink:Yt,assertVisible:(e,t,n)=>jt(`assertVisible`,e,t,n),assertNotVisible:(e,t,n)=>jt(`assertNotVisible`,e,t,n),assertTrue:Xt,extendedWaitUntil:Zt,takeScreenshot:Qt,scroll:$t,scrollUntilVisible:en,swipe:Tt,hideKeyboard:tn,pressKey:nn,back:rn,waitForAnimationToEnd:an,stopApp:on,setPermissions:sn,clearState:un,runScript:Ft,evalScript:dn,runFlow:(e,t,n)=>It(e,t,n,$),repeat:(e,t,n)=>Lt(e,t,n,$),retry:(e,t,n)=>Rt(e,t,n,$)};Object.keys(Wt);function Gt(e,t,n,r){let i=Wt[e];return i||I(`Maestro command "${e}" is not supported.`,n,r),i(t,n,r)}function Kt(e,t,n){let r=F(t,n);if(W(e))return{kind:`launchApp`,source:r};if((0,P.isScalar)(e))return{kind:`launchApp`,source:r,appId:K(e,`launchApp`,n)};let i=L(e,`launchApp`,n);return z(i,`launchApp`,[`appId`,`stopApp`,`clearState`,`permissions`,`arguments`,`launchArguments`],n),o({kind:`launchApp`,source:r,appId:H(i,`appId`,e=>q(e,`launchApp.appId`,n)),stopApp:H(i,`stopApp`,e=>J(e,`launchApp.stopApp`,n)),clearState:H(i,`clearState`,e=>J(e,`launchApp.clearState`,n)),permissions:H(i,`permissions`,e=>cn(e,n,`launchApp`)),arguments:H(i,`arguments`,e=>fn(e,`launchApp.arguments`,n)),launchArguments:H(i,`launchArguments`,e=>fn(e,`launchApp.launchArguments`,n))})}function qt(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`inputText`,source:r,text:K(e,`inputText`,n)};let i=L(e,`inputText`,n);return z(i,`inputText`,[`text`,`label`],n),B(i,`text`)||I(`Maestro inputText requires text.`,t,n),o({kind:`inputText`,source:r,text:K(V(i,`text`),`inputText.text`,n),label:X(i,`inputText`,n)})}function Jt(e,t,n){let r=F(t,n);if(W(e))return{kind:`eraseText`,source:r};if((0,P.isScalar)(e))return{kind:`eraseText`,source:r,charactersToErase:lt(e,`eraseText`,n)};let i=L(e,`eraseText`,n);return z(i,`eraseText`,[`charactersToErase`],n),o({kind:`eraseText`,source:r,charactersToErase:B(i,`charactersToErase`)?Y(V(i,`charactersToErase`),`eraseText.charactersToErase`,n):void 0})}function Yt(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`openLink`,source:r,link:K(e,`openLink`,n)};let i=L(e,`openLink`,n);return z(i,`openLink`,[`link`],n),{kind:`openLink`,source:r,link:K(V(i,`link`),`openLink.link`,n)}}function Xt(e,t,n){let r=F(t,n);if(W(e)&&I(`Maestro assertTrue requires condition.`,t,n),(0,P.isScalar)(e))return{kind:`assertTrue`,source:r,condition:ut(e,`assertTrue`,n)};let i=L(e,`assertTrue`,n);z(i,`assertTrue`,[`condition`,`optional`,`label`],n),B(i,`condition`)||I(`Maestro assertTrue requires condition.`,t,n);let a=ut(V(i,`condition`),`assertTrue.condition`,n),s=U(i,`assertTrue`,n),c=X(i,`assertTrue`,n);return o({kind:`assertTrue`,source:r,condition:a,...s,label:c})}function Zt(e,t,n){let r=L(e,`extendedWaitUntil`,n);z(r,`extendedWaitUntil`,[`visible`,`notVisible`,`timeout`,`optional`,`label`],n);let i=U(r,`extendedWaitUntil`,n),a=X(r,`extendedWaitUntil`,n),s=Pt(r,t,n),c=B(r,`timeout`)?Y(V(r,`timeout`),`extendedWaitUntil.timeout`,n):void 0,l=i.optional===!0||s.optional===!0||void 0,u={kind:`extendedWaitUntil`,source:F(t,n),timeout:c,optional:l,label:a};return u[s.key]=s.selector,o(u)}function Qt(e,t,n){return{kind:`takeScreenshot`,source:F(t,n),path:K(e,`takeScreenshot`,n)}}function $t(e,t,n){return W(e)||I(`Maestro scroll does not accept options yet.`,t,n),{kind:`scroll`,source:F(t,n)}}function en(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`scrollUntilVisible`,source:r,element:Q(e,`scrollUntilVisible.element`,n)};let i=L(e,`scrollUntilVisible`,n);z(i,`scrollUntilVisible`,[`element`,`direction`,`timeout`,`optional`,`label`],n);let a=U(i,`scrollUntilVisible`,n),s=X(i,`scrollUntilVisible`,n),c=Nt(i,`element`,`scrollUntilVisible.element`,n);c||I(`Maestro scrollUntilVisible requires element.`,t,n);let l=B(i,`direction`)?At(V(i,`direction`),`scrollUntilVisible.direction`,n):void 0,u=B(i,`timeout`)?Y(V(i,`timeout`),`scrollUntilVisible.timeout`,n):void 0,d=a.optional===!0||c.optional===!0||void 0;return o({kind:`scrollUntilVisible`,source:r,element:c.selector,direction:l,timeout:u,optional:d,label:s})}function tn(e,t,n){return W(e)||I(`Maestro hideKeyboard does not accept options.`,t,n),{kind:`hideKeyboard`,source:F(t,n)}}function nn(e,t,n){let r=K(e,`pressKey`,n).toLowerCase();return r!==`back`&&r!==`enter`&&r!==`return`&&r!==`home`&&I(`Maestro pressKey "${r}" is not supported.`,e,n),{kind:`pressKey`,source:F(t,n),key:r}}function rn(e,t,n){return W(e)||I(`Maestro back does not accept options.`,t,n),{kind:`back`,source:F(t,n)}}function an(e,t,n){let r=F(t,n);if(W(e))return{kind:`waitForAnimationToEnd`,source:r};if((0,P.isScalar)(e))return o({kind:`waitForAnimationToEnd`,source:r,timeout:Y(e,`waitForAnimationToEnd`,n)});let i=L(e,`waitForAnimationToEnd`,n);return z(i,`waitForAnimationToEnd`,[`timeout`],n),o({kind:`waitForAnimationToEnd`,source:r,timeout:B(i,`timeout`)?Y(V(i,`timeout`),`waitForAnimationToEnd.timeout`,n):void 0})}function on(e,t,n){let r=F(t,n);return W(e)?{kind:`stopApp`,source:r}:{kind:`stopApp`,source:r,appId:K(e,`stopApp`,n)}}function sn(e,t,n){let r=F(t,n),i=L(e,`setPermissions`,n);z(i,`setPermissions`,[`appId`,`permissions`,`optional`,`label`],n),B(i,`permissions`)||I(`Maestro setPermissions requires permissions.`,t,n);let a=H(i,`appId`,e=>q(e,`setPermissions.appId`,n)),s=cn(V(i,`permissions`),n),c=U(i,`setPermissions`,n),l=X(i,`setPermissions`,n);return o({kind:`setPermissions`,source:r,appId:a,permissions:s,...c,label:l})}function cn(e,t,n=`setPermissions`){let r=L(e,`${n}.permissions`,t);r.length===0&&I(`Maestro ${n}.permissions requires at least one permission.`,e,t);let i={};for(let e of r)i[e.key]=ln(e,t,n);return i}function ln(e,t,n=`setPermissions`){let r=`${n}.permissions.${e.key}`,i=G(e.value,r,t);typeof i!=`string`&&I(`Maestro ${r} expects a string.`,e.value,t);let a=i.toLowerCase();if(nt.has(a))return a;if(tt.test(i))return i;i.includes("${")&&I(`Maestro ${r} only supports allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup; JavaScript expressions are not supported.`,e.value,t),I(`Maestro ${r} expects allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup.`,e.value,t)}function un(e,t,n){let r=F(t,n);return W(e)?{kind:`clearState`,source:r}:{kind:`clearState`,source:r,appId:K(e,`clearState`,n)}}function dn(e,t,n){return{kind:`evalScript`,source:F(t,n),script:K(e,`evalScript`,n)}}function fn(e,t,n){if((0,P.isSeq)(e))return{kind:`list`,values:R(e,t,n).map((e,r)=>{let i=G(e,`${t}[${r}]`,n);return i===null&&I(`${t}[${r}] expects a scalar value.`,e,n),i})};if((0,P.isMap)(e))return{kind:`map`,values:dt(e,t,n)};let r=G(e,t,n);return r===null&&I(`${t} expects a scalar, list, or map.`,e,n),{kind:`scalar`,value:r}}function pn(e,t={}){let n=new P.LineCounter,i=o({lineCounter:n,sourcePath:t.sourcePath}),a=(0,P.parseAllDocuments)(e,{lineCounter:n});for(let e of a)if(e.errors.length>0){let t=e.errors[0],n=t?.message??`Invalid Maestro YAML flow.`,a=Qe(t?.pos[0],i);throw new r(`INVALID_ARGS`,`Invalid Maestro YAML flow: ${n} (${$e(a)})`)}let s=a.map(e=>e.contents).filter(e=>e!==null);s.length===0&&I(`Maestro flow is empty.`,void 0,i);let c,l;s.length===1&&(0,P.isSeq)(s[0])?l=s[0]:s.length===2&&(0,P.isMap)(s[0])&&(0,P.isSeq)(s[1])?(c=s[0],l=s[1]):I(`Maestro flow must contain a command list, optionally preceded by one config document.`,s[0],i);let u=c?mn(c,i):{};return{kind:`program`,source:F(c??l,i),config:u,commands:$(l,`commands`,i)}}function mn(e,t){let n=L(e,`flow config`,t);return z(n,`flow config`,[`name`,`appId`,`tags`,`env`,`onFlowStart`,`onFlowComplete`],t),o({name:H(n,`name`,e=>q(e,`name`,t)),appId:H(n,`appId`,e=>q(e,`appId`,t)),tags:H(n,`tags`,e=>et(e,`tags`,t)),env:H(n,`env`,e=>dt(e,`env`,t)),onFlowStart:H(n,`onFlowStart`,e=>$(e,`onFlowStart`,t)),onFlowComplete:H(n,`onFlowComplete`,e=>$(e,`onFlowComplete`,t))})}function hn(e,t){let n=new Map;return async(r,a,o)=>{if(o?.aborted)throw i();let s=gn(r,a,e),c=n.get(s);if(c)return c;let l=pn(t(s),{sourcePath:s});return n.set(s,l),l}}function gn(e,t,n){let r=t?a.dirname(t):n;return a.resolve(r,e)}function _n(e){let t={[e.entryPath]:e.entrySource},n=vn(e.entrySource,e.entryPath);return n&&yn({program:n,sourcePath:e.entryPath,context:l({},{...e.env}),files:t,readSource:e.readSource}),t}function vn(e,t){try{return pn(e,{sourcePath:t})}catch{return}}function yn(e){let t=e.context.enter(e.program.config.env??{});try{bn([...e.program.config.onFlowStart??[],...e.program.commands,...e.program.config.onFlowComplete??[]],e)}finally{t()}}function bn(e,t){for(let n of e){if(n.kind===`repeat`||n.kind===`retry`){bn(n.commands,t);continue}if(n.kind!==`runFlow`)continue;let e=t.context.enter(n.env??{});try{if(n.include.kind===`commands`){bn(n.include.commands,t);continue}xn(n.include.path,t)}finally{e()}}}function xn(e,t){let n=t.context.resolveDeferred(e);if(n.includes("${"))return;let r=gn(n,t.sourcePath,t.sourcePath);if(t.files[r]!==void 0)return;let i=t.readSource(r);if(i===void 0)return;t.files[r]=i;let a=vn(i,r);a&&yn({...t,program:a,sourcePath:r})}var Sn=t({MAESTRO_COMPATIBILITY_ADR_URL:()=>MAESTRO_COMPATIBILITY_ADR_URL,MAESTRO_COMPATIBILITY_ISSUE_URL:()=>MAESTRO_COMPATIBILITY_ISSUE_URL,collectMaestroFlowSources:()=>_n});export{at as a,l as c,o as d,ft as i,c as l,hn as n,ot as o,pn as r,Ze as s,Sn as t,s as u};
115
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=l(c(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=l(c(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Xe=n((e=>{var t=He(),n=Ee(),r=De(),i=re(),a=m(),o=Je(),s=Ye();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Ze=n((e=>{var t=He(),n=Ee(),r=we(),i=De(),a=x(),o=m(),s=D(),c=S(),l=O(),u=A();Ke();var d=qe(),f=Je(),p=Ye(),g=Xe(),_=h();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=g.parse,e.parseAllDocuments=g.parseAllDocuments,e.parseDocument=g.parseDocument,e.stringify=g.stringify,e.visit=_.visit,e.visitAsync=_.visitAsync})),P=Ze();function F(e,t){return Qe(e?.range?.[0],t)}function Qe(e,t){let n=t.lineCounter.linePos(e!==void 0&&e>=0?e:0).line;return t.sourcePath===void 0?{line:n}:{path:t.sourcePath,line:n}}function $e(e){return`${e.path===void 0?``:`${e.path}:`}line ${e.line}`}function I(e,t,n){throw new i(`INVALID_ARGS`,`${e} (${$e(F(t,n))})`)}function L(e,t,n){(0,P.isMap)(e)||I(`Maestro ${t} expects a map.`,e,n);let r=[];for(let i of e.items){let e=i.key;(0,P.isScalar)(e)||I(`Maestro ${t} map keys must be strings.`,void 0,n);let a=e.value;typeof a!=`string`&&typeof a!=`number`&&typeof a!=`boolean`&&I(`Maestro ${t} map keys must be strings.`,e,n),i.value!==null&&!(0,P.isNode)(i.value)&&I(`Maestro ${t} values must be YAML nodes.`,e,n),r.push({key:String(a),keyNode:e,value:i.value})}return r}function R(e,t,n){return(0,P.isSeq)(e)||I(`Maestro ${t} expects a list.`,e,n),e.items}function et(e,t,n){return R(e,t,n).map((e,r)=>K(e,`${t}[${r}]`,n))}function z(e,t,n,r){let i=new Set(n),a=new Set;for(let n of e)a.has(n.key)&&I(`Maestro ${t} contains duplicate field "${n.key}".`,n.keyNode,r),a.add(n.key),i.has(n.key)||I(`Maestro ${t} field "${n.key}" is not supported.`,n.keyNode,r)}function B(e,t){return e.some(e=>e.key===t)}function V(e,t){return e.find(e=>e.key===t)?.value}function H(e,t,n){return B(e,t)?n(V(e,t)):void 0}function U(e,t,n){return o({optional:H(e,`optional`,e=>J(e,`${t}.optional`,n))})}function W(e){return e===null||(0,P.isScalar)(e)&&e.value===null}function G(e,t,n){if(e==null)return null;(0,P.isScalar)(e)||I(`Maestro ${t} expects a scalar value.`,e,n);let r=e.value;if(r===null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return r;I(`Maestro ${t} contains an unsupported scalar value.`,e,n)}function K(e,t,n){let r=G(e,t,n);return typeof r!=`string`&&I(`Maestro ${t} expects a string.`,e,n),r}function q(e,t,n){let r=G(e,t,n);if(r!==null)return typeof r!=`string`&&I(`Maestro ${t} expects a string.`,e,n),r}function J(e,t,n){let r=G(e,t,n);if(r!==null)return typeof r!=`boolean`&&I(`Maestro ${t} expects a boolean.`,e,n),r}const tt=/^\$\{[A-Za-z_][A-Za-z0-9_.]*\}$/,nt=new Set([`allow`,`deny`,`unset`,`always`,`inuse`,`never`,`limited`]),rt=/^-?\d+(\.\d+)?$/,it=/^-?\d+$/,at={"tapOn.index":{integer:!0,nonNegative:!0},"tapOn.repeat":{integer:!0,positive:!0},"tapOn.delay":{integer:!0,nonNegative:!0},"doubleTapOn.delay":{integer:!0,nonNegative:!0},eraseText:{integer:!0,positive:!0},"eraseText.charactersToErase":{integer:!0,positive:!0},"extendedWaitUntil.timeout":{nonNegative:!0},"scrollUntilVisible.timeout":{nonNegative:!0},waitForAnimationToEnd:{nonNegative:!0},"waitForAnimationToEnd.timeout":{nonNegative:!0},"swipe.duration":{nonNegative:!0},"repeat.times":{integer:!0,nonNegative:!0},"retry.maxRetries":{integer:!0,nonNegative:!0}};function ot(e){return e.positive&&e.integer?`a positive integer`:e.positive?`a positive number`:e.nonNegative&&e.integer?`a non-negative integer`:e.nonNegative?`a non-negative finite number`:e.integer?`an integer`:`a finite number`}function st(e,t,n,r,i){let a=`Maestro ${t} expects ${ot(i)} or a variable expression.`;Number.isFinite(e)||I(a,n,r),Math.abs(e)>2**53-1&&I(a,n,r),i.integer&&!Number.isSafeInteger(e)&&I(a,n,r),i.nonNegative&&e<0&&I(a,n,r),i.positive&&e<=0&&I(a,n,r)}function ct(e,t,n,r,i){if(typeof e==`number`)return st(e,t,n,r,i),e;if(typeof e==`string`){if(tt.test(e))return e;if((i.integer?it:rt).test(e)){let a=Number(e);return st(a,t,n,r,i),a}}I(`Maestro ${t} expects ${ot(i)} or a variable expression.`,n,r)}function Y(e,t,n,r=at[t]??{}){let i=G(e,t,n);if(i!==null)return ct(i,t,e,n,r)}function lt(e,t,n){let r=at[t]??{},i=G(e,t,n);return i===null&&I(`Maestro ${t} expects ${ot(r)} or a variable expression.`,e,n),ct(i,t,e,n,r)}function ut(e,t,n){let r=G(e,t,n);return r===null&&I(`Maestro ${t} requires a condition.`,e,n),typeof r==`string`&&r.includes("${")&&!tt.test(r)&&I(`Maestro ${t} only supports a literal value or a bare \${VAR} lookup; JavaScript expressions are not supported — compute it in a runScript and reference \${output.x}.`,e,n),r}function dt(e,t,n){let r=L(e,t,n),i={};for(let e of r){let r=G(e.value,`${t}.${e.key}`,n);r===null&&I(`Maestro ${t}.${e.key} expects a string, number, or boolean.`,e.value,n),i[e.key]=r}return i}function X(e,t,n){return H(e,`label`,e=>q(e,`${t}.label`,n))}const Z=[`id`,`text`,`enabled`,`selected`,`index`,`childOf`,`below`,`above`,`leftOf`,`rightOf`,`containsChild`,`containsDescendants`],ft={textKeys:[`id`,`text`],booleanKeys:[`enabled`,`selected`],textAliases:{label:`text`}},pt={id:(e,t,n,r)=>vt(e,`id`,t,n,r),text:(e,t,n,r)=>vt(e,`text`,t,n,r),enabled:(e,t,n,r)=>yt(e,`enabled`,t,n,r),selected:(e,t,n,r)=>yt(e,`selected`,t,n,r),index:(e,t,n,r)=>{e.index=Y(t.value,`${n}.index`,r,{integer:!0,nonNegative:!0})},childOf:(e,t,n,r)=>{e.childOf=Q(t.value,`${n}.childOf`,r)},below:(e,t,n,r)=>{e.below=Q(t.value,`${n}.below`,r)},above:(e,t,n,r)=>{e.above=Q(t.value,`${n}.above`,r)},leftOf:(e,t,n,r)=>{e.leftOf=Q(t.value,`${n}.leftOf`,r)},rightOf:(e,t,n,r)=>{e.rightOf=Q(t.value,`${n}.rightOf`,r)},containsChild:(e,t,n,r)=>{e.containsChild=Q(t.value,`${n}.containsChild`,r)},containsDescendants:(e,t,n,r)=>{e.containsDescendants=R(t.value,`${n}.containsDescendants`,r).map(e=>Q(e,`${n}.containsDescendants`,r))},optional:(e,t,n,r)=>yt(e,`optional`,t,n,r)};function Q(e,t,n,r=Z){if((0,P.isScalar)(e))return{text:K(e,t,n)};let i=L(e,t,n);return z(i,t,r,n),mt(i,t,n)}function mt(e,t,n){e.length===0&&I(`Maestro ${t} selector is empty.`,void 0,n);let r={};for(let i of e){let e=pt[i.key];e||I(`Maestro ${t} selector field "${i.key}" is not supported.`,i.keyNode,n),e(r,i,t,n)}return Object.keys(r).filter(e=>e!==`optional`).length===0&&I(`Maestro ${t} selector must contain a selector value.`,e[0]?.keyNode,n),r}function ht(e,t,n,r){let i=F(t,n);if((0,P.isScalar)(e))return{source:i,entries:[],target:xt(Q(e,r.name,n,r.selectorKeys))};let a=L(e,r.name,n),o=B(a,`point`);if(z(a,r.name,o?r.pointAllowedKeys:r.selectorAllowedKeys,n),o){let e=r.pointConflictingSelectorKeys??r.selectorKeys;return a.some(t=>bt(t.key,e))&&I(`Maestro ${r.name}.point cannot be combined with a selector.`,t,n),{source:i,entries:a,target:r.parsePoint(V(a,`point`),`${r.name}.point`,n)}}return{source:i,entries:a,target:xt(mt(a.filter(e=>bt(e.key,r.selectorKeys)),r.name,n))}}function gt(e,t,n){let r=K(e,t,n),i=/^\s*(\d+)\s*,\s*(\d+)\s*$/.exec(r);if(i)return{space:`absolute`,x:Number(i[1]),y:Number(i[2])};let a=/^\s*(\d+)%\s*,\s*(\d+)%\s*$/.exec(r);if(a){let r=Number(a[1]),i=Number(a[2]);return(r>100||i>100)&&I(`Maestro ${t} percentage coordinates must be between 0% and 100%.`,e,n),{space:`percent`,x:r,y:i}}/^\s*\d+(?:\.\d+)?%\s*,\s*\d+(?:\.\d+)?%\s*$/.test(r)&&I(`Maestro ${t} percentage coordinates must be whole numbers.`,e,n),I(`Maestro ${t} expects absolute or percentage coordinates.`,e,n)}function _t(e,t,n){let r=gt(e,t,n);return r.space!==`absolute`&&I(`Maestro ${t} only supports absolute coordinates.`,e,n),r}function vt(e,t,n,r,i){let a=q(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function yt(e,t,n,r,i){let a=J(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function bt(e,t){return t.includes(e)}function xt(e){return{space:`target`,selector:e}}function St(e,t,n){let r=ht(e,t,n,{name:`tapOn`,selectorKeys:Z,pointConflictingSelectorKeys:Z,pointAllowedKeys:[`point`,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],selectorAllowedKeys:[...Z,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],parsePoint:gt});if(r.entries.length===0)return{kind:`tapOn`,source:r.source,target:r.target};if(r.target.space!==`target`)return{kind:`tapOn`,source:r.source,target:r.target,...kt(r.entries,n)};let i=kt(r.entries,n);return o({kind:`tapOn`,source:r.source,target:r.target,...i})}function Ct(e,t,n){let r=ht(e,t,n,{name:`doubleTapOn`,selectorKeys:Z,pointAllowedKeys:[`point`,`delay`,`optional`,`label`],selectorAllowedKeys:[...Z,`delay`,`optional`,`label`],parsePoint:_t}),i=U(r.entries,`doubleTapOn`,n),a=B(r.entries,`delay`)?Y(V(r.entries,`delay`),`doubleTapOn.delay`,n):void 0,s=X(r.entries,`doubleTapOn`,n);return o({kind:`doubleTapOn`,source:r.source,target:r.target,...i,delay:a,label:s})}function wt(e,t,n){let r=ht(e,t,n,{name:`longPressOn`,selectorKeys:Z,pointAllowedKeys:[`point`,`optional`,`label`],selectorAllowedKeys:[...Z,`optional`,`label`],parsePoint:_t});return o({kind:`longPressOn`,source:r.source,target:r.target,...U(r.entries,`longPressOn`,n),label:X(r.entries,`longPressOn`,n)})}function Tt(e,t,n){let r=F(t,n),i=L(e,`swipe`,n);z(i,`swipe`,[`start`,`end`,`direction`,`duration`,`from`,`label`,`optional`],n);let a=U(i,`swipe`,n),o=X(i,`swipe`,n),s=B(i,`duration`)?Y(V(i,`duration`),`swipe.duration`,n):void 0;if(B(i,`start`)||B(i,`end`))return{...Et(i,r,s,t,n),...a,label:o};let c=B(i,`direction`)?At(V(i,`direction`),`swipe.direction`,n):void 0;return B(i,`from`)?{...Dt(i,r,c,s,t,n),...a,label:o}:{...Ot(r,c,s,t,n),...a,label:o}}function Et(e,t,n,r,i){B(e,`direction`)&&I(`Maestro swipe cannot combine direction with start/end coordinates.`,r,i),(!B(e,`start`)||!B(e,`end`))&&I(`Maestro swipe requires both start and end coordinates.`,r,i);let a=gt(V(e,`start`),`swipe.start`,i),s=gt(V(e,`end`),`swipe.end`,i);return a.space!==s.space&&I(`Maestro swipe start/end must use the same coordinate space.`,r,i),{kind:`swipe`,source:t,gesture:o({kind:`coordinates`,start:a,end:s,duration:n})}}function Dt(e,t,n,r,i,a){return n===void 0&&I(`Maestro target swipe requires direction.`,i,a),{kind:`swipe`,source:t,gesture:o({kind:`target`,from:Q(V(e,`from`),`swipe.from`,a),direction:n,duration:r})}}function Ot(e,t,n,r,i){return t===void 0&&I(`Maestro swipe requires direction, target, or start/end coordinates.`,r,i),{kind:`swipe`,source:e,gesture:o({kind:`screen`,direction:t,duration:n})}}function kt(e,t){let n=H(e,`retryTapIfNoChange`,e=>J(e,`tapOn.retryTapIfNoChange`,t)),r=H(e,`repeat`,e=>lt(e,`tapOn.repeat`,t)),i=H(e,`delay`,e=>Y(e,`tapOn.delay`,t)),a=U(e,`tapOn`,t).optional;return o({retryTapIfNoChange:n,repeat:r,delay:i,optional:a,label:X(e,`tapOn`,t)})}function At(e,t,n){let r=K(e,t,n).toLowerCase();if(r===`up`||r===`down`||r===`left`||r===`right`)return r;I(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`,e,n)}function jt(e,t,n,r){let i=F(n,r);if((0,P.isScalar)(t))return{kind:e,source:i,target:Q(t,e,r)};let a=L(t,e,r);z(a,e,[...Z,`optional`,`label`],r);let s=U(a,e,r),c=X(a,e,r);return o({kind:e,source:i,target:mt(a.filter(e=>e.key!==`optional`&&e.key!==`label`),e,r),...s,label:c})}const Mt=[...Z,`optional`];function Nt(e,t,n,r){if(!B(e,t))return;let{optional:i,...a}=Q(V(e,t),n,r,Mt);return{selector:a,optional:i}}function Pt(e,t,n){let r=Nt(e,`visible`,`extendedWaitUntil.visible`,n),i=Nt(e,`notVisible`,`extendedWaitUntil.notVisible`,n);return r&&i&&I(`Maestro extendedWaitUntil cannot specify both visible and notVisible.`,t,n),!r&&!i&&I(`Maestro extendedWaitUntil requires visible or notVisible.`,t,n),r?{key:`visible`,selector:r.selector,optional:r.optional}:{key:`notVisible`,selector:i.selector,optional:i.optional}}function Ft(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`runScript`,source:r,file:K(e,`runScript`,n)};let i=L(e,`runScript`,n);return z(i,`runScript`,[`file`,`env`],n),B(i,`file`)||I(`Maestro runScript requires a file.`,t,n),o({kind:`runScript`,source:r,file:K(V(i,`file`),`runScript.file`,n),env:B(i,`env`)?dt(V(i,`env`),`runScript.env`,n):void 0})}function It(e,t,n,r){let i=F(t,n);if((0,P.isScalar)(e))return{kind:`runFlow`,source:i,include:{kind:`file`,path:K(e,`runFlow`,n)}};let a=L(e,`runFlow`,n);z(a,`runFlow`,[`file`,`commands`,`env`,`when`,`label`],n);let s=B(a,`file`);return s===B(a,`commands`)&&I(`Maestro runFlow requires exactly one of file or commands.`,t,n),o({kind:`runFlow`,source:i,include:s?{kind:`file`,path:K(V(a,`file`),`runFlow.file`,n)}:{kind:`commands`,commands:r(V(a,`commands`),`runFlow.commands`,n)},env:B(a,`env`)?dt(V(a,`env`),`runFlow.env`,n):void 0,when:B(a,`when`)?zt(V(a,`when`),n):void 0,label:X(a,`runFlow`,n)})}function Lt(e,t,n,r){let i=F(t,n),a=L(e,`repeat`,n);return z(a,`repeat`,[`times`,`commands`,`while`],n),B(a,`while`)&&I(`Maestro repeat.while is not supported; use repeat.times.`,V(a,`while`),n),B(a,`times`)||I(`Maestro repeat requires times.`,t,n),B(a,`commands`)||I(`Maestro repeat requires commands.`,t,n),{kind:`repeat`,source:i,times:lt(V(a,`times`),`repeat.times`,n),commands:r(V(a,`commands`),`repeat.commands`,n)}}function Rt(e,t,n,r){let i=F(t,n),a=L(e,`retry`,n);z(a,`retry`,[`maxRetries`,`commands`],n),B(a,`commands`)||I(`Maestro retry requires commands.`,t,n);let s=B(a,`maxRetries`)?lt(V(a,`maxRetries`),`retry.maxRetries`,n):void 0;return o({kind:`retry`,source:i,commands:r(V(a,`commands`),`retry.commands`,n),maxRetries:s})}function zt(e,t){let n=L(e,`runFlow.when`,t);return z(n,`runFlow.when`,[`platform`,`visible`,`notVisible`,`true`],t),n.length===0&&I(`Maestro runFlow.when cannot be empty.`,e,t),o({platform:H(n,`platform`,e=>Vt(e,t)),visible:H(n,`visible`,e=>Q(e,`runFlow.when.visible`,t)),notVisible:H(n,`notVisible`,e=>Q(e,`runFlow.when.notVisible`,t)),true:H(n,`true`,e=>Bt(e,t))})}function Bt(e,t){let n=G(e,`runFlow.when.true`,t);if(typeof n==`boolean`||typeof n==`string`)return n;I(`Maestro runFlow.when.true expects a boolean or expression string.`,e,t)}function Vt(e,t){let n=K(e,`runFlow.when.platform`,t).toLowerCase();if(n===`android`||n===`ios`||n===`web`)return n;I(`Maestro runFlow.when.platform expects Android, iOS, or Web.`,e,t)}function $(e,t,n){return R(e,t,n).map(e=>Ht(e,n))}function Ht(e,t){if((0,P.isScalar)(e))return typeof e.value!=`string`&&I(`Maestro command names must be strings.`,e,t),Ut(e.value,e,t);(0,P.isMap)(e)||I(`Maestro commands must be a scalar or one-key map.`,e,t);let n=L(e,`command`,t);n.length!==1&&I(`Maestro command maps must contain exactly one command.`,e,t);let r=n[0];return Gt(r.key,r.value,e,t)}function Ut(e,t,n){return Gt(e,null,t,n)}const Wt={launchApp:Kt,tapOn:St,doubleTapOn:Ct,longPressOn:wt,inputText:qt,eraseText:Jt,openLink:Yt,assertVisible:(e,t,n)=>jt(`assertVisible`,e,t,n),assertNotVisible:(e,t,n)=>jt(`assertNotVisible`,e,t,n),assertTrue:Xt,extendedWaitUntil:Zt,takeScreenshot:Qt,scroll:$t,scrollUntilVisible:en,swipe:Tt,hideKeyboard:tn,pressKey:nn,back:rn,waitForAnimationToEnd:an,stopApp:on,setPermissions:sn,clearState:un,runScript:Ft,evalScript:dn,runFlow:(e,t,n)=>It(e,t,n,$),repeat:(e,t,n)=>Lt(e,t,n,$),retry:(e,t,n)=>Rt(e,t,n,$)};Object.keys(Wt);function Gt(e,t,n,r){let i=Wt[e];return i||I(`Maestro command "${e}" is not supported.`,n,r),i(t,n,r)}function Kt(e,t,n){let r=F(t,n);if(W(e))return{kind:`launchApp`,source:r};if((0,P.isScalar)(e))return{kind:`launchApp`,source:r,appId:K(e,`launchApp`,n)};let i=L(e,`launchApp`,n);return z(i,`launchApp`,[`appId`,`stopApp`,`clearState`,`permissions`,`arguments`,`launchArguments`],n),o({kind:`launchApp`,source:r,appId:H(i,`appId`,e=>q(e,`launchApp.appId`,n)),stopApp:H(i,`stopApp`,e=>J(e,`launchApp.stopApp`,n)),clearState:H(i,`clearState`,e=>J(e,`launchApp.clearState`,n)),permissions:H(i,`permissions`,e=>cn(e,n,`launchApp`)),arguments:H(i,`arguments`,e=>fn(e,`launchApp.arguments`,n)),launchArguments:H(i,`launchArguments`,e=>fn(e,`launchApp.launchArguments`,n))})}function qt(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`inputText`,source:r,text:K(e,`inputText`,n)};let i=L(e,`inputText`,n);return z(i,`inputText`,[`text`,`label`],n),B(i,`text`)||I(`Maestro inputText requires text.`,t,n),o({kind:`inputText`,source:r,text:K(V(i,`text`),`inputText.text`,n),label:X(i,`inputText`,n)})}function Jt(e,t,n){let r=F(t,n);if(W(e))return{kind:`eraseText`,source:r};if((0,P.isScalar)(e))return{kind:`eraseText`,source:r,charactersToErase:lt(e,`eraseText`,n)};let i=L(e,`eraseText`,n);return z(i,`eraseText`,[`charactersToErase`],n),o({kind:`eraseText`,source:r,charactersToErase:B(i,`charactersToErase`)?Y(V(i,`charactersToErase`),`eraseText.charactersToErase`,n):void 0})}function Yt(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`openLink`,source:r,link:K(e,`openLink`,n)};let i=L(e,`openLink`,n);return z(i,`openLink`,[`link`],n),{kind:`openLink`,source:r,link:K(V(i,`link`),`openLink.link`,n)}}function Xt(e,t,n){let r=F(t,n);if(W(e)&&I(`Maestro assertTrue requires condition.`,t,n),(0,P.isScalar)(e))return{kind:`assertTrue`,source:r,condition:ut(e,`assertTrue`,n)};let i=L(e,`assertTrue`,n);z(i,`assertTrue`,[`condition`,`optional`,`label`],n),B(i,`condition`)||I(`Maestro assertTrue requires condition.`,t,n);let a=ut(V(i,`condition`),`assertTrue.condition`,n),s=U(i,`assertTrue`,n),c=X(i,`assertTrue`,n);return o({kind:`assertTrue`,source:r,condition:a,...s,label:c})}function Zt(e,t,n){let r=L(e,`extendedWaitUntil`,n);z(r,`extendedWaitUntil`,[`visible`,`notVisible`,`timeout`,`optional`,`label`],n);let i=U(r,`extendedWaitUntil`,n),a=X(r,`extendedWaitUntil`,n),s=Pt(r,t,n),c=B(r,`timeout`)?Y(V(r,`timeout`),`extendedWaitUntil.timeout`,n):void 0,l=i.optional===!0||s.optional===!0||void 0,u={kind:`extendedWaitUntil`,source:F(t,n),timeout:c,optional:l,label:a};return u[s.key]=s.selector,o(u)}function Qt(e,t,n){return{kind:`takeScreenshot`,source:F(t,n),path:K(e,`takeScreenshot`,n)}}function $t(e,t,n){return W(e)||I(`Maestro scroll does not accept options yet.`,t,n),{kind:`scroll`,source:F(t,n)}}function en(e,t,n){let r=F(t,n);if((0,P.isScalar)(e))return{kind:`scrollUntilVisible`,source:r,element:Q(e,`scrollUntilVisible.element`,n)};let i=L(e,`scrollUntilVisible`,n);z(i,`scrollUntilVisible`,[`element`,`direction`,`timeout`,`optional`,`label`],n);let a=U(i,`scrollUntilVisible`,n),s=X(i,`scrollUntilVisible`,n),c=Nt(i,`element`,`scrollUntilVisible.element`,n);c||I(`Maestro scrollUntilVisible requires element.`,t,n);let l=B(i,`direction`)?At(V(i,`direction`),`scrollUntilVisible.direction`,n):void 0,u=B(i,`timeout`)?Y(V(i,`timeout`),`scrollUntilVisible.timeout`,n):void 0,d=a.optional===!0||c.optional===!0||void 0;return o({kind:`scrollUntilVisible`,source:r,element:c.selector,direction:l,timeout:u,optional:d,label:s})}function tn(e,t,n){return W(e)||I(`Maestro hideKeyboard does not accept options.`,t,n),{kind:`hideKeyboard`,source:F(t,n)}}function nn(e,t,n){let r=K(e,`pressKey`,n).toLowerCase();return r!==`back`&&r!==`enter`&&r!==`return`&&r!==`home`&&I(`Maestro pressKey "${r}" is not supported.`,e,n),{kind:`pressKey`,source:F(t,n),key:r}}function rn(e,t,n){return W(e)||I(`Maestro back does not accept options.`,t,n),{kind:`back`,source:F(t,n)}}function an(e,t,n){let r=F(t,n);if(W(e))return{kind:`waitForAnimationToEnd`,source:r};if((0,P.isScalar)(e))return o({kind:`waitForAnimationToEnd`,source:r,timeout:Y(e,`waitForAnimationToEnd`,n)});let i=L(e,`waitForAnimationToEnd`,n);return z(i,`waitForAnimationToEnd`,[`timeout`],n),o({kind:`waitForAnimationToEnd`,source:r,timeout:B(i,`timeout`)?Y(V(i,`timeout`),`waitForAnimationToEnd.timeout`,n):void 0})}function on(e,t,n){let r=F(t,n);return W(e)?{kind:`stopApp`,source:r}:{kind:`stopApp`,source:r,appId:K(e,`stopApp`,n)}}function sn(e,t,n){let r=F(t,n),i=L(e,`setPermissions`,n);z(i,`setPermissions`,[`appId`,`permissions`,`optional`,`label`],n),B(i,`permissions`)||I(`Maestro setPermissions requires permissions.`,t,n);let a=H(i,`appId`,e=>q(e,`setPermissions.appId`,n)),s=cn(V(i,`permissions`),n),c=U(i,`setPermissions`,n),l=X(i,`setPermissions`,n);return o({kind:`setPermissions`,source:r,appId:a,permissions:s,...c,label:l})}function cn(e,t,n=`setPermissions`){let r=L(e,`${n}.permissions`,t);r.length===0&&I(`Maestro ${n}.permissions requires at least one permission.`,e,t);let i={};for(let e of r)i[e.key]=ln(e,t,n);return i}function ln(e,t,n=`setPermissions`){let r=`${n}.permissions.${e.key}`,i=G(e.value,r,t);typeof i!=`string`&&I(`Maestro ${r} expects a string.`,e.value,t);let a=i.toLowerCase();if(nt.has(a))return a;if(tt.test(i))return i;i.includes("${")&&I(`Maestro ${r} only supports allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup; JavaScript expressions are not supported.`,e.value,t),I(`Maestro ${r} expects allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup.`,e.value,t)}function un(e,t,n){let r=F(t,n);return W(e)?{kind:`clearState`,source:r}:{kind:`clearState`,source:r,appId:K(e,`clearState`,n)}}function dn(e,t,n){return{kind:`evalScript`,source:F(t,n),script:K(e,`evalScript`,n)}}function fn(e,t,n){if((0,P.isSeq)(e))return{kind:`list`,values:R(e,t,n).map((e,r)=>{let i=G(e,`${t}[${r}]`,n);return i===null&&I(`${t}[${r}] expects a scalar value.`,e,n),i})};if((0,P.isMap)(e))return{kind:`map`,values:dt(e,t,n)};let r=G(e,t,n);return r===null&&I(`${t} expects a scalar, list, or map.`,e,n),{kind:`scalar`,value:r}}function pn(e,t={}){let n=new P.LineCounter,r=o({lineCounter:n,sourcePath:t.sourcePath}),a=(0,P.parseAllDocuments)(e,{lineCounter:n});for(let e of a)if(e.errors.length>0){let t=e.errors[0],n=t?.message??`Invalid Maestro YAML flow.`,a=Qe(t?.pos[0],r);throw new i(`INVALID_ARGS`,`Invalid Maestro YAML flow: ${n} (${$e(a)})`)}let s=a.map(e=>e.contents).filter(e=>e!==null);s.length===0&&I(`Maestro flow is empty.`,void 0,r);let c,l;s.length===1&&(0,P.isSeq)(s[0])?l=s[0]:s.length===2&&(0,P.isMap)(s[0])&&(0,P.isSeq)(s[1])?(c=s[0],l=s[1]):I(`Maestro flow must contain a command list, optionally preceded by one config document.`,s[0],r);let u=c?mn(c,r):{};return{kind:`program`,source:F(c??l,r),config:u,commands:$(l,`commands`,r)}}function mn(e,t){let n=L(e,`flow config`,t);return z(n,`flow config`,[`name`,`appId`,`tags`,`env`,`onFlowStart`,`onFlowComplete`],t),o({name:H(n,`name`,e=>q(e,`name`,t)),appId:H(n,`appId`,e=>q(e,`appId`,t)),tags:H(n,`tags`,e=>et(e,`tags`,t)),env:H(n,`env`,e=>dt(e,`env`,t)),onFlowStart:H(n,`onFlowStart`,e=>$(e,`onFlowStart`,t)),onFlowComplete:H(n,`onFlowComplete`,e=>$(e,`onFlowComplete`,t))})}function hn(e,t){let n=new Map;return async(i,a,o)=>{if(o?.aborted)throw r();let s=gn(i,a,e),c=n.get(s);if(c)return c;let l=pn(t(s),{sourcePath:s});return n.set(s,l),l}}function gn(e,t,n){let r=t?a.dirname(t):n;return a.resolve(r,e)}function _n(e){let t={[e.entryPath]:e.entrySource},n=vn(e.entrySource,e.entryPath);return n&&yn({program:n,sourcePath:e.entryPath,context:l({},{...e.env}),files:t,readSource:e.readSource}),t}function vn(e,t){try{return pn(e,{sourcePath:t})}catch{return}}function yn(e){let t=e.context.enter(e.program.config.env??{});try{bn([...e.program.config.onFlowStart??[],...e.program.commands,...e.program.config.onFlowComplete??[]],e)}finally{t()}}function bn(e,t){for(let n of e){if(n.kind===`repeat`||n.kind===`retry`){bn(n.commands,t);continue}if(n.kind!==`runFlow`)continue;let e=t.context.enter(n.env??{});try{if(n.include.kind===`commands`){bn(n.include.commands,t);continue}xn(n.include.path,t)}finally{e()}}}function xn(e,t){let n=t.context.resolveDeferred(e);if(n.includes("${"))return;let r=gn(n,t.sourcePath,t.sourcePath);if(t.files[r]!==void 0)return;let i=t.readSource(r);if(i===void 0)return;t.files[r]=i;let a=vn(i,r);a&&yn({...t,program:a,sourcePath:r})}var Sn=t({MAESTRO_COMPATIBILITY_ADR_URL:()=>MAESTRO_COMPATIBILITY_ADR_URL,MAESTRO_COMPATIBILITY_ISSUE_URL:()=>MAESTRO_COMPATIBILITY_ISSUE_URL,collectMaestroFlowSources:()=>_n});export{at as a,l as c,o as d,ft as i,c as l,hn as n,ot as o,pn as r,Ze as s,Sn as t,s as u};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";function t(t,n={message:e=>`Invalid value: ${e}`}){let r=new Set(t),i=n.normalize??(e=>e);return{is:e=>typeof e==`string`&&r.has(e),parse:t=>{let a=i(t??``);if(r.has(a))return a;throw new e(`INVALID_ARGS`,n.message(t??``))}}}export{t};
1
+ import{O as e}from"./sdk-contracts.js";function t(t,n={message:e=>`Invalid value: ${e}`}){let r=new Set(t),i=n.normalize??(e=>e);return{is:e=>typeof e==`string`&&r.has(e),parse:t=>{let a=i(t??``);if(r.has(a))return a;throw new e(`INVALID_ARGS`,n.message(t??``))}}}export{t};
@@ -1,4 +1,4 @@
1
- import{D as e}from"./sdk-contracts.js";import{t}from"./shared.js";import{randomUUID as n}from"node:crypto";const r=async({positionals:t,flags:n,client:r})=>{let s=t[0]?.toLowerCase();if(s===`status`){if(t.length!==1)throw new e(`INVALID_ARGS`,`takeover status does not accept additional arguments.`);return await a(n,r),!0}if(s===`release`){if(t.length!==2||!t[1])throw new e(`INVALID_ARGS`,`takeover release requires a hold id.`);return await o(n,r,t[1]),!0}if(t.length>0)throw new e(`INVALID_ARGS`,`takeover accepts only: status or release <hold-id>.`);return await i(n,r),!0};async function i(e,r){let i=`takeover-${n()}`,a={reason:`Human is interacting with the simulator or device.`,ttlMs:15e3},o=r.leases.humanControl,c=await o.put(i,a);await t(e,{hold:c,state:`active`},()=>s(c));let l,u,d=!1,f,p=new Promise(e=>{f=e}),m=()=>f?.();process.once(`SIGINT`,m),process.once(`SIGTERM`,m);let h=setInterval(()=>{u||=o.put(i,a).then(()=>void 0).catch(e=>{l=e,f?.()}).finally(()=>{u=void 0})},5e3);try{await p}finally{clearInterval(h),process.off(`SIGINT`,m),process.off(`SIGTERM`,m),await u,d=await o.remove(i).catch(()=>!1)}if(l)throw l;e.json||process.stdout.write(d?`Human control released. Agent interactions are enabled.
1
+ import{O as e}from"./sdk-contracts.js";import{t}from"./shared.js";import{randomUUID as n}from"node:crypto";const r=async({positionals:t,flags:n,client:r})=>{let s=t[0]?.toLowerCase();if(s===`status`){if(t.length!==1)throw new e(`INVALID_ARGS`,`takeover status does not accept additional arguments.`);return await a(n,r),!0}if(s===`release`){if(t.length!==2||!t[1])throw new e(`INVALID_ARGS`,`takeover release requires a hold id.`);return await o(n,r,t[1]),!0}if(t.length>0)throw new e(`INVALID_ARGS`,`takeover accepts only: status or release <hold-id>.`);return await i(n,r),!0};async function i(e,r){let i=`takeover-${n()}`,a={reason:`Human is interacting with the simulator or device.`,ttlMs:15e3},o=r.leases.humanControl,c=await o.put(i,a);await t(e,{hold:c,state:`active`},()=>s(c));let l,u,d=!1,f,p=new Promise(e=>{f=e}),m=()=>f?.();process.once(`SIGINT`,m),process.once(`SIGTERM`,m);let h=setInterval(()=>{u||=o.put(i,a).then(()=>void 0).catch(e=>{l=e,f?.()}).finally(()=>{u=void 0})},5e3);try{await p}finally{clearInterval(h),process.off(`SIGINT`,m),process.off(`SIGTERM`,m),await u,d=await o.remove(i).catch(()=>!1)}if(l)throw l;e.json||process.stdout.write(d?`Human control released. Agent interactions are enabled.
2
2
  `:`Release could not be confirmed. The safety TTL will re-enable agent interactions automatically.
3
3
  `)}async function a(e,n){let r=await n.leases.humanControl.list();await t(e,{holds:r},()=>c(r))}async function o(e,n,r){let i=await n.leases.humanControl.remove(r);await t(e,{holdId:r,released:i},()=>i?`Released human-control hold ${r}.`:`No active hold found for ${r}.`)}function s(e){return[`Human control active for ${e.scope.deviceKey}.`,`Agent interactions are paused. Press Ctrl+C to return control.`,`Hold: ${e.id}`].join(`
4
4
  `)}function c(e){return e.length===0?`No active human-control holds.`:[`Active human-control holds:`,...e.map(e=>{let t=e.scope.deviceKey;return` ${e.id}: ${t}`})].join(`
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{Hr as t,Kr as n,Ur as r}from"./sdk-batch.js";import{n as i,r as a}from"./snapshot.js";function o(t,n,r,i){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,y:n,...i,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function s(e){let t=[];for(let n of p(e)){let e=a(n);r(e)&&t.push({node:n,identity:m(n),rect:e})}return t}function c(e){let t=new Map;for(let n of e)t.set(n.identity,(t.get(n.identity)??0)+1);return t}function l(e){let t=s(e),r=c(t),i=null,a=1/0;for(let e of t){if(!e.node.traits?.includes(`IsEditing`))continue;let t=n(e.rect);t>=a||(i=r.get(e.identity)===1?{identity:e.identity,rect:e.rect}:{rect:e.rect},a=t)}return i}function u(e,n,r){let i=s(e),a=c(i),o=new Set;for(let e of i)a.get(e.identity)===1&&t(e.rect,n,r)&&o.add(e.identity);return o}async function d(e){let t=Date.now()+(e.timeoutMs??3e3),n=0,r=!1;for(;;){let i=await e.readFocus();if(n+=1,i&&(r=!0,f(i,e.targetsAtPoint,e.x,e.y)))return`focused-element`;if(Date.now()>=t)break;await e.sleep(150)}throw o(e.x,e.y,`nothing there took text-entry focus, so the text was not sent`,{samples:n,editingElementObserved:r})}function f(e,n,r,i){return t(e.rect,r,i)?!0:e.identity!==void 0&&n.has(e.identity)}function p(e){let t=[],n=e=>{t.push(e);for(let t of i(e))n(t)};for(let t of Array.isArray(e)?e:[e])n(t);return t}function m(e){return[e.pid??``,e.type??e.elementType??``,e.AXUniqueId??e.identifier??``,e.AXLabel??e.label??``].join(`\0`)}export{d as awaitLimrunTextEntryFocus,l as readLimrunTextEntryFocus,u as readLimrunUnambiguousTapTargets};
1
+ import{O as e}from"./sdk-contracts.js";import{Hr as t,Wr as n,qr as r}from"./sdk-batch.js";import{n as i,r as a}from"./snapshot.js";function o(t,n,r,i){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,y:n,...i,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function s(e){let t=[];for(let r of p(e)){let e=a(r);n(e)&&t.push({node:r,identity:m(r),rect:e})}return t}function c(e){let t=new Map;for(let n of e)t.set(n.identity,(t.get(n.identity)??0)+1);return t}function l(e){let t=s(e),n=c(t),i=null,a=1/0;for(let e of t){if(!e.node.traits?.includes(`IsEditing`))continue;let t=r(e.rect);t>=a||(i=n.get(e.identity)===1?{identity:e.identity,rect:e.rect}:{rect:e.rect},a=t)}return i}function u(e,n,r){let i=s(e),a=c(i),o=new Set;for(let e of i)a.get(e.identity)===1&&t(e.rect,n,r)&&o.add(e.identity);return o}async function d(e){let t=Date.now()+(e.timeoutMs??3e3),n=0,r=!1;for(;;){let i=await e.readFocus();if(n+=1,i&&(r=!0,f(i,e.targetsAtPoint,e.x,e.y)))return`focused-element`;if(Date.now()>=t)break;await e.sleep(150)}throw o(e.x,e.y,`nothing there took text-entry focus, so the text was not sent`,{samples:n,editingElementObserved:r})}function f(e,n,r,i){return t(e.rect,r,i)?!0:e.identity!==void 0&&n.has(e.identity)}function p(e){let t=[],n=e=>{t.push(e);for(let t of i(e))n(t)};for(let t of Array.isArray(e)?e:[e])n(t);return t}function m(e){return[e.pid??``,e.type??e.elementType??``,e.AXUniqueId??e.identifier??``,e.AXLabel??e.label??``].join(`\0`)}export{d as awaitLimrunTextEntryFocus,l as readLimrunTextEntryFocus,u as readLimrunUnambiguousTapTargets};
@@ -1 +1 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./tool-provider.js";export{o as createLocalAppleToolProvider,n as hasScopedAppleToolProvider,i as readApplePlistJson,t as resolveAppleToolProvider,e as runAppleToolCommand,r as runXcrun,a as withAppleToolProvider};
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,t as o}from"./tool-provider.js";export{o as createLocalAppleToolProvider,r as hasScopedAppleToolProvider,a as readApplePlistJson,n as resolveAppleToolProvider,e as runAppleToolCommand,i as runXcrun,t as withAppleToolProvider};