agent-device 0.21.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.apk → agent-device-android-ime-helper-0.21.1.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.1.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.manifest.json → agent-device-android-ime-helper-0.21.1.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.apk → agent-device-android-snapshot-helper-0.21.1.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.1.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.manifest.json → agent-device-android-snapshot-helper-0.21.1.manifest.json} +6 -6
  7. package/apple/snapshot-bridge/README.md +58 -1
  8. package/apple/snapshot-bridge/SnapshotBridge.m +6 -0
  9. package/apple/snapshot-bridge/SnapshotBridgeCapture.h +25 -0
  10. package/apple/snapshot-bridge/SnapshotBridgeCapture.m +138 -0
  11. package/apple/snapshot-bridge/SnapshotBridgeRuntime.h +1 -0
  12. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +32 -3
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +12 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +15 -15
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +72 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +63 -14
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +668 -82
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +14 -4
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +39 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1065 -223
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +290 -0
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +1 -1
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +10 -10
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +249 -61
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +101 -42
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +13 -13
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +51 -43
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +71 -4
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +144 -7
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +13 -1
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +216 -17
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +206 -22
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +289 -42
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +92 -22
  36. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +617 -122
  37. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +79 -4
  38. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +71 -71
  39. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +83 -5
  40. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +67 -67
  41. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +4 -4
  42. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +17 -17
  43. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +30 -30
  44. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +31 -31
  45. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +28 -0
  46. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +101 -0
  47. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +19 -19
  48. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +55 -17
  49. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +26 -5
  50. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +125 -75
  51. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +9 -9
  52. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +9 -9
  53. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +4 -4
  54. package/dist/src/adapter.js +1 -1
  55. package/dist/src/adb-executor.js +1 -1
  56. package/dist/src/adb-failure.js +1 -1
  57. package/dist/src/agent-browser-process-record.js +1 -1
  58. package/dist/src/agent-browser-provider.js +1 -1
  59. package/dist/src/agent-browser-tool.js +1 -1
  60. package/dist/src/agent-device-client.js +2 -2
  61. package/dist/src/ai-sdk.d.ts +1 -1
  62. package/dist/src/ai-sdk.js +1 -1
  63. package/dist/src/alert-runtime.js +1 -1
  64. package/dist/src/android-input-ownership.js +1 -1
  65. package/dist/src/app-catalog.js +1 -1
  66. package/dist/src/app-deployment-resolution.js +1 -1
  67. package/dist/src/app-inventory-contract.js +1 -1
  68. package/dist/src/app-inventory.js +1 -1
  69. package/dist/src/app-launch.js +2 -2
  70. package/dist/src/app-lifecycle.js +3 -3
  71. package/dist/src/app-lifecycle2.js +1 -1
  72. package/dist/src/app-log-files.js +1 -1
  73. package/dist/src/app-log-runtime2.js +3 -3
  74. package/dist/src/app-resolution.js +1 -1
  75. package/dist/src/apple-runner-platform.js +1 -0
  76. package/dist/src/application-lifecycle-interaction.js +1 -1
  77. package/dist/src/archive.js +1 -1
  78. package/dist/src/artifact-download.js +1 -1
  79. package/dist/src/auth-session.js +1 -1
  80. package/dist/src/auth.js +1 -1
  81. package/dist/src/backend-snapshot-options.js +1 -1
  82. package/dist/src/boot-diagnostics.js +1 -1
  83. package/dist/src/capture.js +1 -1
  84. package/dist/src/cli-config.js +1 -1
  85. package/dist/src/cli-help.js +25 -21
  86. package/dist/src/cli-runner.js +1 -1
  87. package/dist/src/cli.js +4 -4
  88. package/dist/src/click-button.js +1 -1
  89. package/dist/src/client-metro-companion.js +1 -1
  90. package/dist/src/client-metro.js +1 -1
  91. package/dist/src/client-types.d.ts +27 -13
  92. package/dist/src/code-signature-cache.js +1 -1
  93. package/dist/src/code-signature.js +1 -1
  94. package/dist/src/command-schema.js +3 -3
  95. package/dist/src/command-tools.js +2 -2
  96. package/dist/src/command.js +1 -1
  97. package/dist/src/connection-runtime.js +1 -1
  98. package/dist/src/connection.js +3 -3
  99. package/dist/src/contracts.d.ts +1 -1
  100. package/dist/src/contracts.js +1 -1
  101. package/dist/src/daemon-client-lifecycle.js +1 -1
  102. package/dist/src/daemon.js +1 -1
  103. package/dist/src/debug-symbols-facade.js +1 -1
  104. package/dist/src/device-claim-rule.js +1 -1
  105. package/dist/src/device-inventory-context.js +1 -1
  106. package/dist/src/device-rotation.js +1 -1
  107. package/dist/src/device-selection-resolver.js +1 -1
  108. package/dist/src/device-session.js +1 -1
  109. package/dist/src/device2.js +1 -1
  110. package/dist/src/diagnostics.js +1 -1
  111. package/dist/src/dispatch-resolve.js +1 -1
  112. package/dist/src/doctor2.js +1 -1
  113. package/dist/src/error.js +1 -1
  114. package/dist/src/exec.js +1 -1
  115. package/dist/src/file.js +1 -1
  116. package/dist/src/find.js +1 -1
  117. package/dist/src/generic-settle.js +1 -1
  118. package/dist/src/gesture-plan.js +1 -1
  119. package/dist/src/gesture-runtime.js +1 -1
  120. package/dist/src/harmonyos.js +1 -1
  121. package/dist/src/hdc.js +1 -1
  122. package/dist/src/helper.js +2 -2
  123. package/dist/src/human-control-contract.js +1 -1
  124. package/dist/src/human-control.js +1 -1
  125. package/dist/src/index.d.ts +1 -1
  126. package/dist/src/index.js +1 -1
  127. package/dist/src/input-actions.js +1 -1
  128. package/dist/src/input-actions2.js +2 -2
  129. package/dist/src/install-artifact-facade.js +1 -1
  130. package/dist/src/install-source-network-transport.js +1 -1
  131. package/dist/src/install-source2.js +1 -1
  132. package/dist/src/interaction-positionals.js +1 -1
  133. package/dist/src/interaction-ref-policy.js +1 -1
  134. package/dist/src/interaction2.js +1 -1
  135. package/dist/src/interactor.js +5 -5
  136. package/dist/src/interactor2.js +1 -1
  137. package/dist/src/interactors.js +1 -1
  138. package/dist/src/internal/bin.js +1 -1
  139. package/dist/src/internal/daemon.js +2 -2
  140. package/dist/src/internal/png-worker.js +1 -1
  141. package/dist/src/internal/run-script-http-child.js +1 -1
  142. package/dist/src/inventory.js +2 -2
  143. package/dist/src/inventory2.js +1 -1
  144. package/dist/src/inventory3.js +1 -1
  145. package/dist/src/inventory5.js +1 -1
  146. package/dist/src/ios-snapshot-runtime.js +1 -1
  147. package/dist/src/ios-system-surface.js +1 -0
  148. package/dist/src/lease-scope.js +1 -1
  149. package/dist/src/lease.js +1 -1
  150. package/dist/src/limrun-runtime-dependencies.js +1 -1
  151. package/dist/src/limrun.d.ts +1 -1
  152. package/dist/src/linux.js +1 -1
  153. package/dist/src/location-coordinates.js +1 -1
  154. package/dist/src/managed-device-scope.js +1 -1
  155. package/dist/src/mechanics.js +16 -16
  156. package/dist/src/multitouch-support.js +1 -1
  157. package/dist/src/observation.js +1 -1
  158. package/dist/src/open-target-resolution.js +1 -0
  159. package/dist/src/owner-identity.js +3 -3
  160. package/dist/src/parameterized-recorded-fill.js +1 -1
  161. package/dist/src/perf-facade.js +2 -2
  162. package/dist/src/perf-process-identity.js +1 -0
  163. package/dist/src/perf-runtime-operation-builder.js +1 -1
  164. package/dist/src/perf-runtime-plan.js +1 -1
  165. package/dist/src/perf.js +1 -1
  166. package/dist/src/physical-device-control.js +1 -1
  167. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  168. package/dist/src/platform-runtime-app-log-process.js +1 -1
  169. package/dist/src/platform-runtime-host.js +1 -1
  170. package/dist/src/platform-runtime-managed-owner.js +1 -1
  171. package/dist/src/platform-runtime-open-target.js +1 -1
  172. package/dist/src/platform-runtime-operation-host.js +2 -2
  173. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  174. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  175. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  176. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  177. package/dist/src/platform-runtime-unavailable.js +1 -1
  178. package/dist/src/platform-runtime.js +1 -1
  179. package/dist/src/platform-runtime2.js +1 -1
  180. package/dist/src/png-worker-contract.js +1 -1
  181. package/dist/src/prepare-kind.js +1 -1
  182. package/dist/src/provider-device-runtime.js +1 -1
  183. package/dist/src/provider-session-ownership.js +1 -1
  184. package/dist/src/provider-webdriver.js +1 -1
  185. package/dist/src/proxy.js +1 -1
  186. package/dist/src/react-native.js +1 -1
  187. package/dist/src/record-runtime.js +1 -1
  188. package/dist/src/rect-center.js +1 -1
  189. package/dist/src/register-builtins.js +1 -1
  190. package/dist/src/registry.js +37 -36
  191. package/dist/src/remote-config2.js +1 -1
  192. package/dist/src/replay-divergence.js +1 -1
  193. package/dist/src/replay.js +2 -2
  194. package/dist/src/reporting.js +9 -8
  195. package/dist/src/request-admission.js +1 -1
  196. package/dist/src/request-cancel.js +1 -1
  197. package/dist/src/request-runtime-binding.js +1 -1
  198. package/dist/src/retry.js +1 -1
  199. package/dist/src/runner-cache-metadata.js +2 -2
  200. package/dist/src/runner-client.js +1 -1
  201. package/dist/src/runner-disposal.js +1 -1
  202. package/dist/src/runner-operations-facade.js +1 -1
  203. package/dist/src/runner.js +1 -1
  204. package/dist/src/runtime-transport-hints.js +1 -1
  205. package/dist/src/runtime.js +3 -3
  206. package/dist/src/runtime2.js +4 -4
  207. package/dist/src/runtime3.js +1 -1
  208. package/dist/src/runtime4.js +5 -4
  209. package/dist/src/runtime5.js +1 -1
  210. package/dist/src/runtime6.js +1 -1
  211. package/dist/src/runtime7.js +1 -1
  212. package/dist/src/runtime8.js +1 -1
  213. package/dist/src/runtime9.js +1 -1
  214. package/dist/src/screen-recording-live-handle.js +1 -1
  215. package/dist/src/screen-recording-options.js +1 -1
  216. package/dist/src/screen-recording-resource-recovery.js +1 -1
  217. package/dist/src/screenshot-density.js +1 -1
  218. package/dist/src/screenshot-runtime.js +1 -1
  219. package/dist/src/screenshot.js +1 -1
  220. package/dist/src/screenshot3.js +3 -3
  221. package/dist/src/script.js +1 -1
  222. package/dist/src/scroll-command.js +1 -1
  223. package/dist/src/scroll-gesture.js +1 -1
  224. package/dist/src/sdk-batch-runner.js +2 -2
  225. package/dist/src/sdk-batch.js +2 -2
  226. package/dist/src/sdk-contracts.d.ts +44 -1
  227. package/dist/src/sdk-contracts.js +2 -2
  228. package/dist/src/sdk-device.js +1 -1
  229. package/dist/src/sdk-finders.d.ts +1 -1
  230. package/dist/src/sdk-io.js +1 -1
  231. package/dist/src/sdk-remote-config.d.ts +1 -1
  232. package/dist/src/sdk-remote-config.js +1 -1
  233. package/dist/src/sdk-selectors.d.ts +69 -13
  234. package/dist/src/selector-runtime.js +1 -1
  235. package/dist/src/server.js +3 -3
  236. package/dist/src/session-allocation.js +1 -1
  237. package/dist/src/session-observation.js +1 -0
  238. package/dist/src/session-routing.js +1 -1
  239. package/dist/src/session-runtime-admission.js +1 -1
  240. package/dist/src/session-snapshot.js +1 -1
  241. package/dist/src/session-store.js +3 -3
  242. package/dist/src/session-target-evidence.js +1 -1
  243. package/dist/src/session2.js +5 -5
  244. package/dist/src/settings.js +1 -1
  245. package/dist/src/simulator.js +1 -1
  246. package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
  247. package/dist/src/snapshot-quality-verdict.js +1 -1
  248. package/dist/src/snapshot-runtime-binding.js +1 -1
  249. package/dist/src/snapshot-runtime.js +1 -1
  250. package/dist/src/snapshot-state.js +1 -1
  251. package/dist/src/snapshot2.js +1 -1
  252. package/dist/src/snapshot3.js +1 -1
  253. package/dist/src/snapshot4.js +1 -1
  254. package/dist/src/src.js +1 -1
  255. package/dist/src/src7.js +2 -2
  256. package/dist/src/src8.js +2 -2
  257. package/dist/src/string-enum.js +1 -1
  258. package/dist/src/takeover.js +1 -1
  259. package/dist/src/tool-provider.js +2 -2
  260. package/dist/src/tool-provider2.js +1 -1
  261. package/dist/src/tool-provider3.js +1 -1
  262. package/dist/src/toolchain-probe.js +1 -1
  263. package/dist/src/touch-reference-frame.js +1 -0
  264. package/dist/src/touch-runtime.js +1 -1
  265. package/dist/src/transport.js +1 -1
  266. package/dist/src/tv-remote.js +1 -1
  267. package/dist/src/type-text-runtime.js +1 -1
  268. package/dist/src/update-check.js +1 -1
  269. package/dist/src/verified-file.js +1 -1
  270. package/dist/src/video.js +1 -1
  271. package/dist/src/web.js +1 -1
  272. package/dist/src/web2.js +1 -1
  273. package/dist/src/webdriver-source.js +1 -1
  274. package/dist/src/window-state.js +1 -0
  275. package/package.json +3 -2
  276. package/server.json +2 -2
  277. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.0.apk.sha256 +0 -1
  278. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk.sha256 +0 -1
  279. package/dist/src/back-mode.js +0 -1
  280. package/dist/src/format.js +0 -2
  281. package/dist/src/platform-runtime-apple-resources.js +0 -1
  282. package/dist/src/runner-selector-query.js +0 -1
@@ -1,4 +1,4 @@
1
- import{y as e}from"./sdk-contracts.js";import{g as t}from"./sdk-batch-runner.js";import{s as n}from"./owner-identity.js";import{i as r,s as i}from"./exec.js";import"./command.js";import"./process.js";import{D as a,g as o,o as s,u as c,y as l}from"./host-file.js";import u from"node:path";const d=/^[0-9a-fA-F-]{32,36}$/;function f(e){if(!(!e||!d.test(e)))return e.replaceAll(`-`,``).toUpperCase()}function p(e,t){return`${e.uuid}:${m(t)}`}function m(e){return`0x${e.toString(16)}`}function h(e){return typeof e==`string`&&e.length>0?e:void 0}function g(...e){for(let t of e){let e=h(t);if(e)return e}}function _(e){let t=e.filter(e=>!!e);return t.length>0?t.join(` `):void 0}function v(e){try{let n=JSON.parse(e);return t(n)?n:null}catch{return null}}function y(e){if(typeof e==`number`&&Number.isSafeInteger(e))return e;if(typeof e==`string`){let t=e.startsWith(`0x`)?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function b(e,t,n){if(!Object.hasOwn(e,t))return;let r=y(e[t]);if(r!==void 0)return r;S(n,t)}function x(e,t,n){if(!Object.hasOwn(e,t))return;let r=ee(e[t]);if(r!==void 0)return r;S(n,t)}function ee(e){if(typeof e==`bigint`)return e;if(typeof e==`number`&&Number.isSafeInteger(e)||typeof e==`string`&&/^(?:0x[0-9a-fA-F]+|\d+)$/.test(e))return BigInt(e)}function S(t,n){throw new e(`INVALID_ARGS`,`Invalid ${t} numeric field: ${n}`,{hint:`Crash artifact numeric fields must be integer numbers or integer numeric strings.`})}function C(e){return e.length===1?e[0]:void 0}function w(e){return[...new Set(e)]}function te(e){let t=e.match(/^(.*) \+ (\d+)$/);return t?{symbol:t[1],location:Number(t[2])}:{symbol:e}}const ne=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;function re(e){return ie(e)??O(e)}function ie(e){let t=ae(e);if(!t)return null;let n=(Array.isArray(t.payload.usedImages)?t.payload.usedImages:[]).flatMap((e,t)=>D(e,t));if(n.length===0)return null;let r=oe(Array.isArray(t.payload.threads)?t.payload.threads:[],n);return{format:`ips`,images:n,addresses:r.map(({frame:e,...t})=>t),document:t,frameMatches:r,write:e=>T(t,r,e)}}function ae(e){let t=v(e);if(t)return{payload:t};let n=e.indexOf(`
1
+ import{C as e}from"./sdk-contracts.js";import{g as t}from"./sdk-batch-runner.js";import{s as n}from"./owner-identity.js";import{a as r,c as i}from"./exec.js";import"./command.js";import"./process.js";import{D as a,g as o,o as s,u as c,y as l}from"./host-file.js";import u from"node:path";const d=/^[0-9a-fA-F-]{32,36}$/;function f(e){if(!(!e||!d.test(e)))return e.replaceAll(`-`,``).toUpperCase()}function p(e,t){return`${e.uuid}:${m(t)}`}function m(e){return`0x${e.toString(16)}`}function h(e){return typeof e==`string`&&e.length>0?e:void 0}function g(...e){for(let t of e){let e=h(t);if(e)return e}}function _(e){let t=e.filter(e=>!!e);return t.length>0?t.join(` `):void 0}function v(e){try{let n=JSON.parse(e);return t(n)?n:null}catch{return null}}function y(e){if(typeof e==`number`&&Number.isSafeInteger(e))return e;if(typeof e==`string`){let t=e.startsWith(`0x`)?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function b(e,t,n){if(!Object.hasOwn(e,t))return;let r=y(e[t]);if(r!==void 0)return r;S(n,t)}function x(e,t,n){if(!Object.hasOwn(e,t))return;let r=ee(e[t]);if(r!==void 0)return r;S(n,t)}function ee(e){if(typeof e==`bigint`)return e;if(typeof e==`number`&&Number.isSafeInteger(e)||typeof e==`string`&&/^(?:0x[0-9a-fA-F]+|\d+)$/.test(e))return BigInt(e)}function S(t,n){throw new e(`INVALID_ARGS`,`Invalid ${t} numeric field: ${n}`,{hint:`Crash artifact numeric fields must be integer numbers or integer numeric strings.`})}function C(e){return e.length===1?e[0]:void 0}function w(e){return[...new Set(e)]}function te(e){let t=e.match(/^(.*) \+ (\d+)$/);return t?{symbol:t[1],location:Number(t[2])}:{symbol:e}}const ne=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;function re(e){return ie(e)??O(e)}function ie(e){let t=ae(e);if(!t)return null;let n=(Array.isArray(t.payload.usedImages)?t.payload.usedImages:[]).flatMap((e,t)=>D(e,t));if(n.length===0)return null;let r=oe(Array.isArray(t.payload.threads)?t.payload.threads:[],n);return{format:`ips`,images:n,addresses:r.map(({frame:e,...t})=>t),document:t,frameMatches:r,write:e=>T(t,r,e)}}function ae(e){let t=v(e);if(t)return{payload:t};let n=e.indexOf(`
2
2
  `);if(n===-1)return null;let r=e.slice(0,n),i=v(e.slice(n+1));return i?{header:r,payload:i}:null}function oe(e,t){let n=new Map(t.map(e=>[e.index,e]));return e.flatMap((e,t)=>se(e).flatMap((e,r)=>ce(e,n,t,r)))}function se(e){return!t(e)||!Array.isArray(e.frames)?[]:e.frames.filter(t)}function ce(e,t,n,r){let i=b(e,`imageIndex`,`IPS frame`),a=x(e,`imageOffset`,`IPS frame`);if(i===void 0||a===void 0)return[];let o=t.get(i);return o?[{frame:e,frameIndex:r,threadIndex:n,image:o,address:o.base+a}]:[]}function T(e,t,n){for(let e of t){let t=n.get(p(e.image,e.address))?.text;t&&E(e.frame,t)}e.payload.agentDeviceSymbolication={tool:`agent-device debug symbols`,symbolicatedFrames:[...n.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}\n`;return e.header?`${e.header}\n${r}`:r}function E(e,t){let n=te(t);e.symbol=n.symbol,n.location!==void 0&&(e.symbolLocation=n.location)}function D(e,n){if(!t(e))return[];let r=f(h(e.uuid)),i=x(e,`base`,`IPS usedImages`);if(!r||i===void 0)return[];let a=h(e.path);return[{index:n,name:h(e.name)??(a?u.basename(a):`image-${n}`),uuid:r,arch:h(e.arch),base:i,path:a}]}function O(e){let t=e.split(`
3
3
  `),n=k(t);if(n.length===0)return null;let r=M(t,n);return{format:`text`,images:n,addresses:r,lines:t,frameMatches:r,write(e){let n=new Map(r.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let i=n.get(r);if(!i)return t;let a=e.get(p(i.image,i.address))?.text;return!a||t.includes(a)?t:`${t} // ${a}`}).join(`
4
4
  `)}}}function k(e){let t=[],n=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(n===-1)return t;for(let r of e.slice(n+1)){let e=A(r);e&&t.push(e)}return t}function A(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let n=f(t[4]);if(!n)return null;let r=j(t[3].trim(),t[5].trim());return{name:r.name,arch:r.arch,uuid:n,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}function j(e,t){let n=e.split(/\s+/),r=n.at(-1);if(r&&ne.test(r))return{name:n.slice(0,-1).join(` `).trim(),arch:r};let i=u.basename(t);return{name:e.startsWith(i)?i:e}}function M(e,t){let n=[],r;for(let[i,a]of e.entries()){let e=a.match(/^Thread\s+(\d+)\s+Crashed:/);e?r=Number(e[1]):(a.trim().length===0||/^Thread\s+\d+/.test(a))&&(r=void 0);let o=N(a,t),s=a.match(/^\s*(\d+)/);o&&s&&n.push({...o,frameIndex:Number(s[1]),lineIndex:i,threadIndex:r})}return n}function N(e,t){let n=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!n)return null;let r=n[1].trim(),i=BigInt(n[2]),a=P(t,r,i);return a?{image:a,address:i}:null}function P(e,t,n){let r=e.filter(e=>e.name===t);return r.find(e=>F(e,n))??C(r)}function F(e,t){return e.end!==void 0&&e.base<=t&&t<=e.end}const I=1e4;async function L(e){return e.dsym&&e.searchPath?[K(e.cwd,e.dsym),...await R(K(e.cwd,e.searchPath))]:e.dsym?[K(e.cwd,e.dsym)]:e.searchPath?await R(K(e.cwd,e.searchPath)):[]}async function R(t){let n=[],r=0;async function i(a){if(n.length>=200)return;if(r+=1,r>I)throw new e(`COMMAND_FAILED`,`debug symbols search-path scan exceeded bounds.`,{searchPath:t,maxEntries:I,hint:`Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory.`});if(!(await z(a,t)).isDirectory()){a===t&&B(t);return}if(a.endsWith(`.dSYM`)){n.push(a);return}let s=await o(a,{withFileTypes:!0});for(let e of s)e.isDirectory()&&await i(u.join(a,e.name))}return await i(t),n}async function z(t,n){try{return await c(t)}catch{throw new e(`INVALID_ARGS`,`debug symbols search path does not exist: ${n}`,{hint:`Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly.`})}}function B(t){throw new e(`INVALID_ARGS`,`debug symbols search path is not a directory: ${t}`,{hint:`Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly.`})}async function V(t,n){let r=(await Promise.all(w(t).map(e=>H(e,n)))).flat();if(r.length===0)throw new e(`COMMAND_FAILED`,`No UUIDs found in dSYM bundle.`,{hint:`Verify the path points to a built .dSYM bundle with DWARF contents.`});return r}async function H(e,t){return await U(e),W(e,r(await i(t,[`--uuid`,e],{timeoutMs:15e3,allowFailure:!0}),`Failed to inspect dSYM UUIDs: ${e}`,{hint:`Verify the dSYM bundle is valid and readable.`}).stdout)}async function U(t){if(!((await c(t).catch(()=>null))?.isDirectory()&&t.endsWith(`.dSYM`)))throw new e(`INVALID_ARGS`,`Not a .dSYM bundle: ${t}`,{hint:`Pass the .dSYM bundle path, not the DWARF executable inside it.`})}function W(e,t){return t.split(`
@@ -1 +1 @@
1
- import{b as e,o as t,x as n,y as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./sdk-batch-runner.js";import{p as a}from"./android-input-ownership.js";import{_ as o,c as s,l as c,m as l,o as u,v as d}from"./sdk-device.js";import{d as f,l as p,n as m,r as h}from"./lease-scope.js";import{Jt as g,Rr as _,Ut as ee,Yt as te,er as ne,jr as re,wr as ie,xr as ae}from"./sdk-batch.js";import{a as oe,n as se,r as ce}from"./script.js";import"./session-store.js";import{r as le}from"./format.js";import{r as v}from"./diagnostics.js";import"./diagnostics2.js";import{r as y}from"./command.js";import{a as ue,t as de}from"./config.js";import{n as b}from"./runtime-transport-hints.js";import{n as fe,t as pe,u as me}from"./provider-session-ownership.js";import{a as he,c as ge,d as x,f as S,g as _e,h as ve,i as ye,l as be,m as xe,n as C,o as Se,p as Ce,r as we,s as w,u as Te}from"./human-control-contract.js";import{r as Ee}from"./application-lifecycle-runtime.js";import{a as De,c as Oe,n as ke,o as Ae,r as je,s as T,t as Me}from"./device-claim-inspection.js";import{b as Ne,c as Pe,g as Fe,i as Ie,p as Le,x as E}from"./perf-runtime-plan.js";import{n as Re,r as ze,t as Be}from"./lease-context.js";import{h as Ve,l as He,u as Ue}from"./screenshot-runtime.js";import{t as We}from"./device-isolation.js";import{i as D}from"./request-runtime-binding.js";import{a as Ge,c as Ke,d as O,l as qe,n as Je,o as Ye,r as Xe,u as k}from"./src8.js";import{n as Ze,t as Qe}from"./compatibility-policy.js";import{a as $e}from"./screen-recording-resource-recovery.js";import A from"node:path";import"node:fs";import et,{createHash as tt}from"node:crypto";import nt from"node:os";import j from"node:fs/promises";function rt(e,t){if(t?.replayBackend&&t.replayBackend!==`maestro`)throw new r(`INVALID_ARGS`,`Unsupported replay backend "${t.replayBackend}".`);return{...se(e),metadata:ce(e)}}function it(e,t){return M(e,t)?t:`${e}:${t}`}function M(e,t){return t.startsWith(`${e}:`)}function at(e,t){return!e.partitioned||M(e.tenant,t)}var ot=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},st=class{holdsByDevice=new Map;mutations=new ot;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=be(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new pe({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=Ce(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=ge(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=S(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw Te(i);return w(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=_e(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);Se(n,e),w(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),{released:!0,lease:t}):{released:!1}}getLease(e){let t=_e(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return Se(n,e),w(n,e),{...n}}assertLeaseAdmission(e){let t=xe(e);this.cleanupExpiredLeases(),w(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?x(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>C(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(e,t,n,i){i?.throwIfAborted();let a=ye(t),o=he(n);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(e,o),c=x(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(e,l),x(l.hold.scope)!==c))throw new r(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...e.kind===`lease`?{ownerLeaseId:e.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(e,t,n,i){let a=this.holdsByDevice.get(e),{id:o}=t.hold;try{if(await this.mutations.wait(e,i),i?.throwIfAborted(),a.get(o)!==t)throw new r(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return t.hold={...t.hold,state:`active`,updatedAt:s,...n===void 0?{}:{expiresAt:s+n}},this.refreshHeldLease(e,s),C(t.hold)}catch(n){throw a.get(o)===t&&this.deleteHumanControlHold(e,o),n}}removeHumanControlHold(e,t){let n=ye(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=x(r.hold.scope);return this.deleteHumanControlHold(i,n),C(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=x(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw we(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=x(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(e){let t=this.getActiveLease(e);if(!t.deviceKey)throw new r(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...t,deviceKey:t.deviceKey}}resolveHumanControlScope(e,t){if(e.kind===`host`){if(!t.scope)throw new r(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return t.scope}if(t.scope)throw new r(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let n=this.requireHumanControlLease(e.leaseId);return{backend:n.backend,leaseProvider:n.leaseProvider,deviceKey:n.deviceKey}}assertHoldAuthority(e,t){if(e.kind===`host`)return;let n=this.requireHumanControlLease(e.leaseId);if(t.ownerLeaseId!==n.leaseId||x(n)!==x(t.hold.scope))throw new r(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=x(e);return t!==void 0&&this.holdsByDevice.has(t)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){let n=this.deviceBindings.get(e),r=n?this.leases.get(n):void 0;r&&this.refreshLease(r,r.expiresAt-r.heartbeatAt,Math.max(t,r.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(n.expiresAt>e||this.hasHumanControl(n))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=ve(e);if(!t)return;let n=this.leases.get(t);if(!n||n.expiresAt>this.now()||this.hasHumanControl(n))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(e){if(e!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let t=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(t<this.maxActiveSimulatorLeases))throw new r(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:t,maxActiveLeases:this.maxActiveSimulatorLeases,backend:e,hint:`Retry after releasing another simulator lease.`})}getActiveLease(e){let t=this.leases.get(e);if(t)return t;throw new r(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(S(e),e.leaseId);let t=x(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(S(e));let n=x(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=x({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw Te(r)}};function ct(e){let t=ue(e.meta?.sessionIsolation??e.flags?.sessionIsolation),n=e.meta?.tenantId??e.flags?.tenant,i=de(n);if(n&&!i)throw new r(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(t!==`tenant`)return e;if(!i)throw new r(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=e.session||`default`;return M(i,a)?{...e,meta:{...e.meta,tenantId:i,sessionIsolation:t}}:{...e,session:it(i,a),meta:{...e.meta,tenantId:i,sessionIsolation:t}}}function lt(e,t,n,i={}){if(Ue(e.command))return;let a=Re(e);ft(e,a);let o=n?.lease;if(n===void 0&&!a.leaseId&&ut(e,i.providerAppCatalog))return;if(e.command===`human_control`&&!o&&!a.leaseId)throw new r(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(e.command!==`human_control`&&!o&&e.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;pt(a,o);let s=ze(e,n),c={...s,leaseTtlMs:s.leaseTtlMs??(h(s)?3e5:void 0)};t.assertLeaseAdmission(p(s));let l=t.heartbeatLease(p(c));return He(e)&&t.assertHumanControlAdmission(l),l}function ut(e,t){let n=Ve(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function dt(e){Ue(e.command)||ft(e,Re(e))}function ft(e,t){if(e.command!==`open`)return;let n=m(t);if(n.length!==0)throw new r(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:n})}function pt(e,t){t&&(N(`leaseId`,e.leaseId,t.leaseId),N(`tenantId`,e.tenantId,t.tenantId),N(`runId`,e.runId,t.runId),N(`leaseProvider`,e.leaseProvider,t.leaseProvider),N(`clientId`,e.clientId,t.clientId),N(`deviceKey`,e.deviceKey,t.deviceKey))}function N(e,t,n){if(!(!t||!n||t===n))throw new r(`UNAUTHORIZED`,`Lease does not match session owner (${e})`,{reason:`LEASE_SESSION_MISMATCH`,field:e})}async function mt(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),v({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return v({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function ht(e){dt(e)}async function gt(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(v({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{v({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await Ne(t.deviceClaim).catch(e=>{v({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function _t(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=lt(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function vt(e){return Be(e.req,e.req.internal?.admittedLease)??e.existingLease}async function yt(e){let t=e.session.lease;if(!t)return;let n=f({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=fe(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return v({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const bt=[`platform`,`target`],xt=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function St(e){return u({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function Ct(e){return St(e)||Et(e,bt)}function wt(e){return Ct(e)||Et(e,xt)}function Tt(e){return typeof e==`string`&&e.trim().length>0}function Et(e,t){return e?t.some(t=>Tt(e[t])):!1}function Dt(e){return{appleSimulatorAppTarget:Ot(e)}}function Ot(e){return e&&!i(e)?e:void 0}function kt(e){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function P(e,t){return e.session.screenRecording?jt(e.address,t):Mt(e.address,t)}function At(e,t){return D(`DEVICE_IN_USE`,`Device is already in use by session "${e.address}".`,{session:e.address,deviceId:t.id,deviceName:t.name,hint:P(e,`device-in-use`)})}function jt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return`Recording session "${e}" owns this device. Run ${`agent-device record stop --session ${n}`}; if the session still appears in agent-device session list, run ${r}. ${t===`selector-conflict`?`To keep using this device, rerun the command with --session ${n} and remove conflicting device selectors.`:`To keep using this device, reuse --session ${n} for commands that should attach to the recording session.`} Run agent-device session list to inspect active sessions.`}function Mt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return t===`selector-conflict`?`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n} and remove conflicting device selectors. To switch devices, first run ${r}, then open the desired device with a different --session name.`:`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n}. To open a new session on this device, first run ${r}.`}function Nt(e,t){let{address:n,session:i}=e,a=Pt(i,t);if(a.length!==0)throw new r(`INVALID_ARGS`,`Session "${n}" is already bound to ${kt(i)}, but this request selected ${a.map(Ft).join(`, `)}.`,{session:n,conflicts:a.map(Ft),hint:P(e,`selector-conflict`)})}function Pt(e,t){if(!t)return[];let n=[],r=e.device,i=t.platform;if(i&&!o(r,i)&&n.push({key:`platform`,value:t.platform}),t.target&&t.target!==(r.target??`mobile`)&&n.push({key:`target`,value:t.target}),t.udid&&(!c(r)||t.udid!==r.id)&&n.push({key:`udid`,value:t.udid}),t.serial&&(!l(r.platform)||t.serial!==r.id)&&n.push({key:`serial`,value:t.serial}),t.device&&t.device.trim().toLowerCase()!==r.name.trim().toLowerCase()&&n.push({key:`device`,value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=r.simulatorSetPath?.trim();(!c(r)||r.kind!==`simulator`||e!==i)&&n.push({key:`iosSimulatorDeviceSet`,value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=We(t.androidDeviceAllowlist);(r.platform!==`android`||!e.has(r.id))&&n.push({key:`androidDeviceAllowlist`,value:t.androidDeviceAllowlist})}return n}function Ft(e){return`${It(e.key)}=${e.value}`}function It(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}function Lt(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return tt(`sha256`).update(ne(t),`utf8`).digest(`hex`)}function Rt(e,t,n){return new qt(Bt(zt(t.resolve(e))),n).parse()}function zt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Bt(e){let t=[],n=0;for(;n<e.length;){let i=e.slice(n),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){n+=a;continue}let o=Vt(i);if(!o)throw new r(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);t.push(o.value),n+=o.length}return t}function Vt(e){return Ht(e)??Ut(e)??Wt(e)??Gt(e)??Kt(e)}function Ht(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Ut(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Wt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Gt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Kt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var qt=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new r(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new r(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new r(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new r(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let e=this.peek();if(e?.type!==`operator`||e.value!==`==`&&e.value!==`!=`)throw new r(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new r(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,e.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Jt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Yt(e,t){return{...I(e,t),source:e.source}}function Xt(e,t,n){if(e===void 0)return;let i=n??Ge[t]??{},a=Ye(i),o;if(typeof e==`number`)o=e;else{let n=e.trim();if(n===``)throw new r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(n)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function Zt(e,t,n,r){return Xt(e===void 0?t:n.resolve(String(e)),r)}function F(e){if(e?.aborted)throw n()}async function Qt(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new r(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return F(t.signal),t.signal?await t.loadProgram(e.include.path,e.source.path,t.signal):await t.loadProgram(e.include.path,e.source.path)}function $t(e,t){if(e.include.kind===`file`)return A.resolve(t?A.dirname(t):process.cwd(),e.include.path)}function en(e){return e===void 0?void 0:A.resolve(e)}function tn(e,t){let n=$t(e,e.source.path);if(n&&t.has(n))throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${n}.`);return n}function nn(e,t,n,i){let a=e.include.kind===`file`?en(t.source.path):void 0,o=new Set([n,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function rn(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:Rt(e.true,t,n.platform)}function an(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function I(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>I(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I(n,t)])):e}async function on(e,t){F(t.signal);let n=en(e.source.path),r={options:t,context:Ke(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await sn(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function sn(e,t,n,r,i){F(i.options.signal);let a=_n(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await ln(s,a,o,e.source.path??r,i));return n}finally{s()}}async function cn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await ln(o,t,n,r,i));return a}async function ln(e,t,n,r,i){F(i.options.signal);let a=vn(e,r);switch(a.kind){case`runFlow`:{let e=dn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await un(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[L(a,t,n,o)]}case`repeat`:return[L(a,t,n,await cn(a.commands,t,n,r,i))];case`retry`:return[L(a,t,n,await cn(a.commands,t,n,r,i))];default:return[hn(a,t,n)]}}async function un(e,t,n,r,i){let a=pn(e,i.context),o=tn(a,i.activeIncludePaths),s=await Qt(a,i.options);F(i.options.signal);let c=nn(a,s,o,i.activeIncludePaths),l=_n(t,e.env),u=i.context.enter(e.env);try{return await sn(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function dn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:fn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function fn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return mn(t.context.resolveDeferred(e))?`opaque`:Rt(e,t.context,t.options.platform)?void 0:`omit`}function pn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function mn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function hn(e,t,n){return O({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function L(e,t,n,r){return O({kind:`opaque`,command:gn(e),source:e.source,scopes:t,body:r,appId:n})}function gn(e){switch(e.kind){case`runFlow`:return O({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return O({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function _n(e,t){return t===void 0?e:[...e,t]}function vn(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function yn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await on(e,t),a=bn(t.runtimeHints),o=O({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=Lt(o);return xn({...o,digest:s})}function bn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function xn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))xn(t);return Object.freeze(e)}function Sn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`)return{allowed:!1,reason:`step ${t+1} (runScript) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function Cn(e,t={}){let n=Sn(e,t);if(!n.allowed)throw new r(`INVALID_ARGS`,n.reason);return n.startIndex}function wn(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new r(`INVALID_ARGS`,`Maestro replay startIndex ${t} is out of range for a ${e.total}-step plan.`);return t}const Tn=`maestro-test-failure`;function R(e,t={}){return new r(`COMMAND_FAILED`,e,{...t,reason:Tn})}function En(e){return e instanceof r&&e.code===`COMMAND_FAILED`&&e.details?.reason===Tn}const Dn=new Set([``,`false`,`0`,`null`,`undefined`]);function On(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!Dn.has(e)}async function kn(e,t){F(t.options.signal);try{return await Vn(e,t.context,async()=>await An(e,t))}catch(t){throw V(t,e)}}async function An(e,t){if(e.kind===`command`)return await jn(e.command,e.appId,t);await In(e,t)}async function jn(e,t,n){let r=Yt(e,n.context);try{return await Pn(r,t,n)}catch(e){if(F(n.options.signal),Nn(r)&&En(e)){n.warnings.push(Mn(r,e)),n.skipped+=1;return}throw Hn(e,r)}}function Mn(e,t){let n=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,i=t instanceof r?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${n}: ${i}`}function Nn(e){return`optional`in e&&e.optional===!0}async function Pn(e,t,n){switch(e.kind){case`assertVisible`:await B({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await B({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!On(e.condition))throw R(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await B(Bn(e),Xt(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await Fn(e,t,n)}}async function Fn(e,t,n){let r=O({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return F(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function In(e,t){let n=Yt(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await Rn(n.when,t)){t.skipped+=1;return}t.executed+=1,await z(e.body,t);return;case`repeat`:{let r=Zt(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)F(t.options.signal),await z(e.body,t);return}case`retry`:{let r=Math.min(Zt(n.maxRetries,1,t.context,`retry.maxRetries`),Ze.control.retryMaxRetries);t.executed+=1,await Ln(e.body,r,t);return}}}async function z(e,t){for(let n of e)await kn(n,t)}async function Ln(e,t,n){let i;for(let r=0;r<=t;r+=1){F(n.options.signal);try{await z(e,n);return}catch(t){if(F(n.options.signal),!En(Wn(t)))throw t;i=V(t,e[0])}}throw i||new r(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function Rn(e,t){if(!rn(e,t.context,t.options))return!1;for(let n of an(e))if(F(t.options.signal),!(await zn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function B(e,t,n){if(!(await zn(e,t,n)).matched)throw R(`Maestro ${e.kind} condition did not match.`)}async function zn(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return F(n.options.signal),n.context.recordObservation(i),i}function Bn(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new r(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Vn(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function V(e,t){if(Un(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Gn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Hn(e,t){return{kind:`maestroPlanStepFailure`,error:Gn(e,t),source:t.source,command:t}}function Un(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Wn(e){return Un(e)?e.error:e}function Gn(e,t){if(!(e instanceof r)||!t||/\bline \d+\b/.test(e.message))return e;let n=t.source.path?`${t.source.path}:`:``;return new r(e.code,`${e.message} (${n}line ${t.source.line})`,e.details)}async function Kn(e,t,n={}){F(n.signal);let i=n.startIndex??0;if(!Number.isInteger(i)||i<0||i>e.total)throw new r(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:n,context:Ke(n.defaults,n.env?{...n.env}:{}),timing:Qe,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=i;t<e.steps.length;t+=1)try{await qn(e.steps[t],t,a)}catch(e){throw Wn(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function qn(e,t,n){F(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};H(()=>n.options.observer?.commandStarted?.(s));try{let t=await kn(e,n);F(n.options.signal),H(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Jn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=V(t,e);throw H(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Jn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts]})),o}}function Jn(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function H(e){try{e?.()}catch{}}async function Yn(e,t,n={}){let r=Xn(e,n);return await Kn(e,t,{...n,startIndex:r})}function Xn(e,t){return t.from!==void 0||t.planDigest!==void 0?Cn(e,{from:t.from,planDigest:t.planDigest}):wn(e,t.startIndex??0)}function Zn(e){return Jt(e)?{command:e.kind,...e.kind===`runFlow`?W(e.label??e.includePath):{}}:{command:e.kind,...Qn(e)}}function Qn(e){return`label`in e&&e.label?W(e.label):$n(e)?W(or(e.target)):er(e)?tr(e):e.kind===`inputText`?W(`<text>`):nr(e)}function $n(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function er(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function tr(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return W(U(e.target));case`extendedWaitUntil`:return W(U(e.visible??e.notVisible));case`scrollUntilVisible`:return W(U(e.element))}}function nr(e){return rr(e)?ir(e):e.kind===`swipe`?ar(e):e.kind===`runFlow`?W(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?W(String(e.condition)):{}}function rr(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function ir(e){switch(e.kind){case`openLink`:return W(e.link);case`takeScreenshot`:return W(e.path);case`runScript`:return W(e.file);case`pressKey`:return W(e.key)}}function ar(e){return W(e.gesture.kind===`coordinates`?`${sr(e.gesture.start)} to ${sr(e.gesture.end)}`:e.gesture.direction)}function or(e){return e.space===`target`?U(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function U(e){return e?.id??e?.text}function sr(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function W(e){return e?{value:e}:{}}const cr=new Set(String.raw`^$\.*+?()[]{}|`);function lr(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function ur(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(cr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!cr.has(i))return;t+=i,n+=1}return t}function dr(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(_(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>ie(e,n)?e:null);return r?_(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function fr(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function pr(e,t){let n=[t.id===void 0?void 0:hr(e.identifier,t.id),t.text===void 0?void 0:gr(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function mr(e){return e.matches.filter(t=>dr(t,e.visibility,e.platform))}function hr(e,t){let n=e??``;return k(n)===k(t)||lr(n,t)}function gr(e,t){return[e.label,qe(e),e.identifier].filter(e=>!!e).some(e=>hr(e,t))}function _r(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function vr(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function yr(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=xr(a.rect,e.rect);n===void 0||!br(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function br(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function xr(e,t){if(!(!Sr(e)||!Sr(t)))return Math.fround(Math.hypot(G(e.x,e.width)-G(t.x,t.width),G(e.y,e.height)-G(t.y,t.height)))}function Sr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function G(e,t){return e+Math.trunc(t/2)}function Cr(e,t={},n={}){let i=ae(e.nodes,t);t.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=t=>t.parentIndex===void 0?void 0:i.nodeByIndex.get(t.parentIndex)??e.nodes[t.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(n,r)=>{let i=c.get(n);i||(i=new WeakMap,c.set(n,i));let a=i.get(r);if(a)return a;t.onPositionComputed?.(n,r);let o=yr(e.nodes,n,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new r(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),t.onSelectorComputed?.(i);try{let t=wr(e,i,l,u,m,p),r={matches:t,indexed:Or(t,i.index,n.orderUnindexed)};return a.set(i,r),r}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function wr(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=vr(m)?e.nodes.filter(e=>pr(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>Er(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>Tr(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of Dr(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function Tr(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function Er(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Dr(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function Or(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Ar(e)[jr(t)];return r?[r]:[]}function kr(e,t){return t===void 0?e[0]:Ar(e)[jr(t)]}function Ar(e){return[...e].sort((e,t)=>{let n=K(e.rect?.y),r=K(t.rect?.y);return n===r?K(e.rect?.x)-K(t.rect?.x):n-r})}function K(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function jr(e){let t=typeof e==`number`?e:Number(e.trim());if(!Number.isSafeInteger(t)||t<0)throw new r(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return t}const Mr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Nr(e,t){let n=Mr[t];if(n.kind===`divergence`)return n;let r=a(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function q(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Pr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Pr(e){return e===!0?2:+(e===!1)}function Fr(e,t,n,r={}){let i=Nr(e,n),a=Lr(e,i,r),o=Ir(t,a),s=mr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:Rr(s,t,n,a.visibility,i)}}function Ir(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Lr(e,t,n={}){return Cr(e,n,t?{orderUnindexed:e=>q(e,t)}:{})}function Rr(e,t,n,r,i){let a=n!==`ios`||!Hr(t)?e:e.filter(n=>{if(Gr(n))return!0;let i=e.filter(e=>e!==n&&Ur(n,e,t));return!i.some(e=>Gr(e)&&fr(n,e,r))&&!i.some(e=>fr(e,n,r))});return t.index===void 0&&i?q(a,i):a}function zr(e,t){let n=t===void 0?e.find(J):Br(e,t);return!n||!J(n)?null:{node:n,rect:n.rect}}function Br(e,t){return kr(e,t)}function Vr(e){return J(e)?e.rect:void 0}function J(e){return _(e.rect)}function Hr(e){return e.id!==void 0||e.text!==void 0}function Ur(e,t,n){if(n.id!==void 0&&Y(e.identifier)!==Y(t.identifier))return!1;if(n.text!==void 0){let n=Wr(e),r=new Set(Wr(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Wr(e){return[e.label,e.value,e.identifier].map(Y).filter(e=>e!==void 0)}function Y(e){if(e)return k(e)||void 0}function Gr(e){let t=re(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Kr=Symbol(`maestroFlowProgram`),qr=Symbol(`maestroFailureCommand`),Jr=Symbol(`maestroFailurePlan`);function Yr(e,t){let n=Xe(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:$r(n),[Kr]:n}}async function Xr(e,t,n){let r;try{let i=Je(A.dirname(e.sourcePath),n.readSource),a=await yn(e[Kr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=Cn(a,{from:n.from,planDigest:n.planDigest}),s=await Yn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,observer:Qr(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Zr(e,t){let n=ti(e[qr]),r=e[Jr].platform;return!n||r!==`android`&&r!==`ios`?[]:Fr(t,n.selector,r).ranked.map(e=>({node:e,basis:ni(n.selector,e)}))}function Qr(e,t,n){return{commandStarted:e=>t?.actionStarted?.(X(e)),commandCompleted:e=>t?.actionCompleted?.({...X(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=Sn(e,{from:r.stepIndex,planDigest:e.digest}),a={...X(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,isControl:Jt(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[qr]:r.command,[Jr]:e};n(a),t?.actionFailed?.(a)}}}function X(e){let t=Zn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function $r(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(ei)}function ei(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function ti(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function ni(e,t){return e.id!==void 0||e.text!==void 0&&pr({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const ri=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function ii(e,t){let n=e.files[t];if(n===void 0)throw new r(`INVALID_ARGS`,`replay script source is missing ${t}; it was not part of the script sources sent with this request.`,{path:t,entry:e.entry});return n}function ai(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=ii(t,n);if(le(n,e.flags?.replayBackend)===`maestro`){let t=Yr(r,n);return{flags:e.flags??{},options:oi(t.appTarget,e.flags?.platform)}}let i=rt(r,e.flags),a=si(i.actions);if(!a.appTarget)return;let o=ci(e.flags,i.actions),s=o.platform??i.metadata.platform;return{flags:s&&o.platform===void 0?{...o,platform:s}:o,options:s===`ios`?ui(a.appTarget):void 0}}catch{return}}function oi(e,t){return t===`ios`?ui(e)??{}:{}}function si(e){let t=oe(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return li(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function ci(e,t){let n=si(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function li(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function ui(e){let t=Ot(e);return t?{appleSimulatorAppTarget:t}:void 0}const di={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},Z=new Map;async function fi(e){let t=await j.mkdtemp(A.join(nt.tmpdir(),`agent-device-materialized-`));try{let n=await gi(e.installablePath,A.join(t,`installable`)),r=e.archivePath?await gi(e.archivePath,A.join(t,`archive`)):void 0,i=et.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{hi(i)},a);return Z.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await j.rm(t,{recursive:!0,force:!0}),e}}async function pi(e,t){await Q(e,me(Z,e,t,di))}async function mi(e){let t=Array.from(Z.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await Q(e,t)}))}async function hi(e){let t=Z.get(e);if(t)try{await Q(e,t)}catch{}}async function Q(e,t){clearTimeout(t.timer),Z.delete(e),await j.rm(t.rootPath,{recursive:!0,force:!0})}async function gi(e,t){let n=await j.stat(e);await j.mkdir(t,{recursive:!0});let r=A.join(t,A.basename(e));return n.isDirectory()?(await j.cp(e,r,{recursive:!0}),r):(await j.copyFile(e,r),r)}function _i(e){return e.device.platform===`web`}function vi(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function yi(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await Le({session:t,sessionName:n,sessionStore:r,resourcePath:Fe.resolvePath(r.resolveSessionDir(n))})}async function bi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Ie({...e,session:t})}async function xi(e,t){await t.stopSnapshotHelper(e.device)}async function Si(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>vi(r)})}async function Ci(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function wi(e){if(e.failures.length===0)return;let t=e.failures.map(({step:e})=>e),n=e.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return v({level:`error`,phase:e.phase,data:{session:e.sessionName,failedSteps:t,errors:n}}),new r(`COMMAND_FAILED`,`Session cleanup left ${e.failures.length} resource(s) unreleased: ${n.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:e.sessionName,failedSteps:t,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function Ti(e){let{session:t,sessionName:n,sessionStore:i}=e;if(!e.platformCleanup)throw new r(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=e.platformCleanup,o=[{step:`recording`,run:()=>Ei({session:t,sessionName:n,sessionStore:i})},...e.appLog===`run`?[{step:`app_log`,run:()=>yi({session:t,sessionName:n,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Di({session:t,sessionName:n,sessionStore:i})},{step:`perf_capture`,run:()=>bi({session:t,sessionName:n,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>xi(t,a)},{step:`web_browser`,run:()=>Si({session:t,sessionName:n,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>mi(n)});let s=wi({sessionName:n,phase:`session_teardown_cleanup_failed`,failures:await Ci(o)});if(s)throw s}async function Ei(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await $e({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Di(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Pe({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function Oi(e){return c(e)&&e.kind===`simulator`}function ki(e){return e.platform===`android`&&e.kind===`emulator`}const Ai=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function ji(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function $(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Mi(e){return Ee($(e))}function Ni(e,t){if(e!==void 0){if(typeof e!=`string`)throw new r(`INVALID_ARGS`,`Invalid open runtime ${t}: expected string.`);return b(e)}}function Pi(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new r(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function Fi(e){if(e!==void 0){if(typeof e!=`number`)throw new r(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Pi(e)}}function Ii(e,n,i){if(e===void 0)return i;if(!t(e))throw new r(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios", "android", or "harmonyos".`);if(i&&e!==i)throw new r(`INVALID_ARGS`,`open runtime targets ${e}, but session "${n}" is bound to ${i}.`);return e}function Li(e){if(t(e))return e}function Ri(e,t){return{platform:t,metroHost:b(e?.metroHost),metroPort:Pi(e?.metroPort),bundleUrl:b(e?.bundleUrl),launchUrl:b(e?.launchUrl)}}function zi(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Bi(e){if(ki(e))return`10.0.2.2`;if(Oi(e))return`127.0.0.1`}function Vi(e,t){if(!e||b(e.metroHost)||b(e.bundleUrl)||e.metroPort===void 0)return e;let n=Bi(t);return n?{...e,metroHost:n}:e}function Hi(e){let{runtime:t,sessionName:n,platform:i}=e;if(t===void 0)return;if(!t||typeof t!=`object`||Array.isArray(t))throw new r(`INVALID_ARGS`,`open runtime must be an object.`);let a=t,o=Object.keys(a).find(e=>!Ai.includes(e));if(o)throw new r(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ai.join(`, `)}.`);return{platform:Ii(a.platform,n,i),metroHost:Ni(a.metroHost,`metroHost`),metroPort:Fi(a.metroPort),bundleUrl:Ni(a.bundleUrl,`bundleUrl`),launchUrl:Ni(a.launchUrl,`launchUrl`)}}function Ui(e,t,n){if(n){if(ji(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Wi(e,t,n,i){let a=e.getRuntimeHints(t);if(!a)return;let o=n?d(n):void 0,s=Li(o)??i;if(a.platform&&n&&!s)throw new r(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${t}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new r(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Gi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Li(d(i)):e.platform,o=n.getRuntimeHints(r),s=Hi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Wi(n,r,i,a);return{runtime:i?Vi(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&ji(s)>0?s:void 0;return{runtime:i?Vi(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ki(e){return Gi(e).runtime}function qi(t){try{return{ok:!0,data:Gi(t)}}catch(t){let n=e(t);return D(n.code,n.message,n.details)}}async function Ji(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!Yi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:$(t)})}function Yi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Mi(e.previousRuntime)&&!Mi(e.runtime)}function Xi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&te(i.owner,n)?ee(i.fence):null;if(!a)return{status:`binding-invalid`};let o=T(E(t)),s=je(Oe(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!Qi(c.stateDir,r)||!te(Ae(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function Zi(e){let t=T(E(e));return De(Oe(t))}function Qi(e,t){return A.resolve(e)===A.resolve(t)}const $i=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function ea(e){return $i.has(e)}function ta(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=d(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=s(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${y(i)}`,`${a} ${y(e.id)}`,...n===`release`||ke(t.classification)?[`--stale`]:[]].join(` `)}function na(e,t){if(t.classification===`allocator-held`)return ia(e,t);let n=t.claim,i=ta(e,t,Me(t.classification)?`release`:`status`),a=d(n?{platform:n.device.family,appleOs:n.device.appleOs}:e);return new r(`DEVICE_IN_USE`,n?`${a} device ${e.id} is owned by session "${n.session}" in workspace "${n.workspace}".`:`${e.name} has an ownership claim that could not be verified.`,{reason:da(t.classification),classification:t.classification,deviceKey:t.deviceKey,...n?{owner:{session:n.session,workspace:n.workspace,stateDir:n.stateDir}}:{},recovery:{command:i},hint:Me(t.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function ra(e,t){return ua(na(e,t))}function ia(e,t){let n=t.allocatorClaim,i=d({platform:n.device.family,appleOs:n.device.appleOs}),a=ta(e,t);return new r(`DEVICE_IN_USE`,`${i} device ${e.id} is held by managed-device allocator "${n.allocator.instanceId}" for installation "${n.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:t.classification,deviceKey:t.deviceKey,owner:{kind:`allocator`,stateDir:n.stateDir,allocator:n.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function aa(e,t){return new r(`COMMAND_FAILED`,`${d(e)} device ${e.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:g(t),deviceKey:T(E(e)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function oa(e,t,n){return new r(`COMMAND_FAILED`,`${d(e)} device ${e.id} is held for identity incarnation "${n}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:g(t),deviceKey:T(E(e)),heldIncarnationId:n,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function sa(e,t){return new r(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:g(t),deviceKey:T(E(e)),retriable:!1})}function ca(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:sa(e,t)};case`missing`:return{admitted:!1,error:aa(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:oa(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:na(e,n.conflict)}}}function la(e,t,n){let r=ca(e,t,n);return r.admitted?void 0:ua(r.error)}function ua(e){let{hint:t,retriable:n,...r}=e.details??{};return D(e.code,e.message,r,{hint:t,retriable:n})}function da(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function fa(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{ur as $,mi as A,Lr as B,yi as C,_i as D,Ti as E,ri as F,Br as G,Fr as H,ii as I,Nr as J,Vr as K,Zr as L,oi as M,ci as N,vi as O,ai as P,dr as Q,Xr as R,wi as S,xi as T,Rr as U,Ir as V,zr as W,_r as X,Cr as Y,mr as Z,Yi as _,yt as _t,na as a,At as at,Di as b,st as bt,Xi as c,Dt as ct,Mi as d,wt as dt,R as et,Ji as f,Tt as ft,Ui as g,mt as gt,$ as h,gt as ht,ca as i,Pt as it,fi as j,pi as k,Ri as l,Ct as lt,Ki as m,ht as mt,la as n,Nt as nt,ea as o,P as ot,zi as p,_t as pt,q,ra as r,Ft as rt,Zi as s,kt as st,fa as t,Xt as tt,ji as u,St as ut,Li as v,vt,bi as w,Ei as x,at as xt,qi as y,ct as yt,Yr as z};
1
+ import{C as e,T as t,o as n,w as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./sdk-batch-runner.js";import{p as a}from"./android-input-ownership.js";import{N as o}from"./registry.js";import{_ as s,c,l,m as u,o as d,v as f}from"./sdk-device.js";import{d as p,l as m,n as h,r as ee}from"./lease-scope.js";import{Jt as g,Rr as _,Ut as te,Yt as ne,er as re,jr as ie,wr as ae,xr as oe}from"./sdk-batch.js";import{a as se,n as ce,r as le}from"./script.js";import"./session-store.js";import{r as v}from"./diagnostics.js";import"./diagnostics2.js";import{r as y}from"./command.js";import{a as ue,t as de}from"./config.js";import{n as b}from"./runtime-transport-hints.js";import{n as fe,t as pe,u as me}from"./provider-session-ownership.js";import{a as he,c as ge,d as x,f as _e,g as ve,h as ye,i as be,l as xe,m as Se,n as S,o as Ce,p as we,r as Te,s as C,u as Ee}from"./human-control-contract.js";import{r as De}from"./application-lifecycle-runtime.js";import{a as Oe,c as ke,n as Ae,o as je,r as Me,s as w,t as Ne}from"./device-claim-inspection.js";import{b as Pe,c as Fe,g as Ie,i as Le,p as Re,x as T}from"./perf-runtime-plan.js";import{n as ze,r as Be,t as Ve}from"./lease-context.js";import{h as He,l as Ue,u as We}from"./screenshot-runtime.js";import{t as Ge}from"./device-isolation.js";import{i as E}from"./request-runtime-binding.js";import{a as Ke,c as qe,d as D,l as Je,n as Ye,o as Xe,r as Ze,u as O}from"./src8.js";import{n as Qe,t as $e}from"./compatibility-policy.js";import{a as et}from"./screen-recording-resource-recovery.js";import k from"node:path";import"node:fs";import tt,{createHash as nt}from"node:crypto";import rt from"node:os";import A from"node:fs/promises";function it(t,n){if(n?.replayBackend&&n.replayBackend!==`maestro`)throw new e(`INVALID_ARGS`,`Unsupported replay backend "${n.replayBackend}".`);return{...ce(t),metadata:le(t)}}function at(e,t){return j(e,t)?t:`${e}:${t}`}function j(e,t){return t.startsWith(`${e}:`)}function ot(e,t){return!e.partitioned||j(e.tenant,t)}var st=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},ct=class{holdsByDevice=new Map;mutations=new st;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=xe(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new pe({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=we(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=ge(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=_e(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw Ee(i);return C(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=ve(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);Ce(n,e),C(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),{released:!0,lease:t}):{released:!1}}getLease(e){let t=ve(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return Ce(n,e),C(n,e),{...n}}assertLeaseAdmission(e){let t=Se(e);this.cleanupExpiredLeases(),C(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?x(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>S(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=be(n),o=he(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=x(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),x(l.hold.scope)!==c))throw new e(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...t.kind===`lease`?{ownerLeaseId:t.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(t,n,r,i){let a=this.holdsByDevice.get(t),{id:o}=n.hold;try{if(await this.mutations.wait(t,i),i?.throwIfAborted(),a.get(o)!==n)throw new e(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return n.hold={...n.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(t,s),S(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=be(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=x(r.hold.scope);return this.deleteHumanControlHold(i,n),S(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=x(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw Te(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=x(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(t){let n=this.getActiveLease(t);if(!n.deviceKey)throw new e(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...n,deviceKey:n.deviceKey}}resolveHumanControlScope(t,n){if(t.kind===`host`){if(!n.scope)throw new e(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return n.scope}if(n.scope)throw new e(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(t.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(t,n){if(t.kind===`host`)return;let r=this.requireHumanControlLease(t.leaseId);if(n.ownerLeaseId!==r.leaseId||x(r)!==x(n.hold.scope))throw new e(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=x(e);return t!==void 0&&this.holdsByDevice.has(t)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){let n=this.deviceBindings.get(e),r=n?this.leases.get(n):void 0;r&&this.refreshLease(r,r.expiresAt-r.heartbeatAt,Math.max(t,r.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(n.expiresAt>e||this.hasHumanControl(n))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=ye(e);if(!t)return;let n=this.leases.get(t);if(!n||n.expiresAt>this.now()||this.hasHumanControl(n))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(t){if(t!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let n=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(n<this.maxActiveSimulatorLeases))throw new e(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:n,maxActiveLeases:this.maxActiveSimulatorLeases,backend:t,hint:`Retry after releasing another simulator lease.`})}getActiveLease(t){let n=this.leases.get(t);if(n)return n;throw new e(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(_e(e),e.leaseId);let t=x(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(_e(e));let n=x(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=x({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw Ee(r)}};function lt(t){let n=ue(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=de(r);if(r&&!i)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n!==`tenant`)return t;if(!i)throw new e(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=t.session||`default`;return j(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:at(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function ut(t,n,r,i={}){if(We(t.command))return;let a=ze(t);pt(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&dt(t,i.providerAppCatalog))return;if(t.command===`human_control`&&!o&&!a.leaseId)throw new e(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(t.command!==`human_control`&&!o&&t.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;mt(a,o);let s=Be(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(ee(s)?3e5:void 0)};n.assertLeaseAdmission(m(s));let l=n.heartbeatLease(m(c));return Ue(t)&&n.assertHumanControlAdmission(l),l}function dt(e,t){let n=He(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function ft(e){We(e.command)||pt(e,ze(e))}function pt(t,n){if(t.command!==`open`)return;let r=h(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function mt(e,t){t&&(M(`leaseId`,e.leaseId,t.leaseId),M(`tenantId`,e.tenantId,t.tenantId),M(`runId`,e.runId,t.runId),M(`leaseProvider`,e.leaseProvider,t.leaseProvider),M(`clientId`,e.clientId,t.clientId),M(`deviceKey`,e.deviceKey,t.deviceKey))}function M(t,n,r){if(!(!n||!r||n===r))throw new e(`UNAUTHORIZED`,`Lease does not match session owner (${t})`,{reason:`LEASE_SESSION_MISMATCH`,field:t})}async function ht(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),v({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return v({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function gt(e){ft(e)}async function _t(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(v({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{v({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await Pe(t.deviceClaim).catch(e=>{v({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function vt(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=ut(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function yt(e){return Ve(e.req,e.req.internal?.admittedLease)??e.existingLease}async function bt(e){let t=e.session.lease;if(!t)return;let n=p({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=fe(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return v({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const xt=[`platform`,`target`],St=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function Ct(e){return d({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function wt(e){return Ct(e)||Dt(e,xt)}function Tt(e){return wt(e)||Dt(e,St)}function Et(e){return typeof e==`string`&&e.trim().length>0}function Dt(e,t){return e?t.some(t=>Et(e[t])):!1}function Ot(e){return{appleSimulatorAppTarget:kt(e)}}function kt(e){return e&&!i(e)?e:void 0}function At(e){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function N(e,t){return e.session.screenRecording?Mt(e.address,t):Nt(e.address,t)}function jt(e,t){return E(`DEVICE_IN_USE`,`Device is already in use by session "${e.address}".`,{session:e.address,deviceId:t.id,deviceName:t.name,hint:N(e,`device-in-use`)})}function Mt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return`Recording session "${e}" owns this device. Run ${`agent-device record stop --session ${n}`}; if the session still appears in agent-device session list, run ${r}. ${t===`selector-conflict`?`To keep using this device, rerun the command with --session ${n} and remove conflicting device selectors.`:`To keep using this device, reuse --session ${n} for commands that should attach to the recording session.`} Run agent-device session list to inspect active sessions.`}function Nt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return t===`selector-conflict`?`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n} and remove conflicting device selectors. To switch devices, first run ${r}, then open the desired device with a different --session name.`:`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n}. To open a new session on this device, first run ${r}.`}function Pt(t,n){let{address:r,session:i}=t,a=Ft(i,n);if(a.length!==0)throw new e(`INVALID_ARGS`,`Session "${r}" is already bound to ${At(i)}, but this request selected ${a.map(P).join(`, `)}.`,{session:r,conflicts:a.map(P),hint:N(t,`selector-conflict`)})}function Ft(e,t){if(!t)return[];let n=[],r=e.device,i=t.platform;if(i&&!s(r,i)&&n.push({key:`platform`,value:t.platform}),t.target&&t.target!==(r.target??`mobile`)&&n.push({key:`target`,value:t.target}),t.udid&&(!l(r)||t.udid!==r.id)&&n.push({key:`udid`,value:t.udid}),t.serial&&(!u(r.platform)||t.serial!==r.id)&&n.push({key:`serial`,value:t.serial}),t.device&&t.device.trim().toLowerCase()!==r.name.trim().toLowerCase()&&n.push({key:`device`,value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=r.simulatorSetPath?.trim();(!l(r)||r.kind!==`simulator`||e!==i)&&n.push({key:`iosSimulatorDeviceSet`,value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=Ge(t.androidDeviceAllowlist);(r.platform!==`android`||!e.has(r.id))&&n.push({key:`androidDeviceAllowlist`,value:t.androidDeviceAllowlist})}return n}function P(e){return`${It(e.key)}=${e.value}`}function It(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}function Lt(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return nt(`sha256`).update(re(t),`utf8`).digest(`hex`)}function Rt(e,t,n){return new qt(Bt(zt(t.resolve(e))),n).parse()}function zt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Bt(t){let n=[],r=0;for(;r<t.length;){let i=t.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Vt(i);if(!o)throw new e(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);n.push(o.value),r+=o.length}return n}function Vt(e){return Ht(e)??Ut(e)??Wt(e)??Gt(e)??Kt(e)}function Ht(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Ut(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Wt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Gt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Kt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var qt=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let t=this.parseOr();if(this.peek())throw new e(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return t}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let t=this.peek();if(!t)throw new e(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(t.type===`boolean`)return this.index+=1,t.value;if(t.type===`paren`&&t.value===`(`){this.index+=1;let t=this.parseOr();if(!this.consumeParen(`)`))throw new e(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return t}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new e(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let t=this.peek();if(t?.type!==`operator`||t.value!==`==`&&t.value!==`!=`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,t}consumeStringLiteral(){let t=this.peek();if(t?.type!==`string`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,t.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Jt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Yt(e,t){return{...L(e,t),source:e.source}}function F(t,n,r){if(t===void 0)return;let i=r??Ke[n]??{},a=Xe(i),o;if(typeof t==`number`)o=t;else{let r=t.trim();if(r===``)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);return o}function Xt(e,t,n,r){return F(e===void 0?t:n.resolve(String(e)),r)}function I(e){if(e?.aborted)throw t()}async function Zt(t,n){if(t.include.kind===`commands`)return{kind:`program`,source:t.source,config:{},commands:t.include.commands};if(!n.loadProgram)throw new e(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return I(n.signal),n.signal?await n.loadProgram(t.include.path,t.source.path,n.signal):await n.loadProgram(t.include.path,t.source.path)}function Qt(e,t){if(e.include.kind===`file`)return k.resolve(t?k.dirname(t):process.cwd(),e.include.path)}function $t(e){return e===void 0?void 0:k.resolve(e)}function en(t,n){let r=Qt(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function tn(t,n,r,i){let a=t.include.kind===`file`?$t(n.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function nn(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:Rt(e.true,t,n.platform)}function rn(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function L(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>L(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,L(n,t)])):e}async function an(e,t){I(t.signal);let n=$t(e.source.path),r={options:t,context:qe(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await on(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function on(e,t,n,r,i){I(i.options.signal);let a=gn(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await cn(s,a,o,e.source.path??r,i));return n}finally{s()}}async function sn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await cn(o,t,n,r,i));return a}async function cn(e,t,n,r,i){I(i.options.signal);let a=_n(e,r);switch(a.kind){case`runFlow`:{let e=un(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await ln(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[R(a,t,n,o)]}case`repeat`:return[R(a,t,n,await sn(a.commands,t,n,r,i))];case`retry`:return[R(a,t,n,await sn(a.commands,t,n,r,i))];default:return[mn(a,t,n)]}}async function ln(e,t,n,r,i){let a=fn(e,i.context),o=en(a,i.activeIncludePaths),s=await Zt(a,i.options);I(i.options.signal);let c=tn(a,s,o,i.activeIncludePaths),l=gn(t,e.env),u=i.context.enter(e.env);try{return await on(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function un(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:dn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function dn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return pn(t.context.resolveDeferred(e))?`opaque`:Rt(e,t.context,t.options.platform)?void 0:`omit`}function fn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function pn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function mn(e,t,n){return D({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function R(e,t,n,r){return D({kind:`opaque`,command:hn(e),source:e.source,scopes:t,body:r,appId:n})}function hn(e){switch(e.kind){case`runFlow`:return D({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return D({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function gn(e,t){return t===void 0?e:[...e,t]}function _n(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function vn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await an(e,t),a=yn(t.runtimeHints),o=D({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=Lt(o);return bn({...o,digest:s})}function yn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function bn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))bn(t);return Object.freeze(e)}function xn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`)return{allowed:!1,reason:`step ${t+1} (runScript) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function Sn(t,n={}){let r=xn(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function Cn(t,n){if(!Number.isInteger(n)||n<0||n>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${n} is out of range for a ${t.total}-step plan.`);return n}const wn=`maestro-test-failure`;function z(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:wn})}function Tn(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===wn}const En=new Set([``,`false`,`0`,`null`,`undefined`]);function Dn(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!En.has(e)}async function On(e,t){I(t.options.signal);try{return await Bn(e,t.context,async()=>await kn(e,t))}catch(t){throw H(t,e)}}async function kn(e,t){if(e.kind===`command`)return await An(e.command,e.appId,t);await Fn(e,t)}async function An(e,t,n){let r=Yt(e,n.context);try{return await Nn(r,t,n)}catch(e){if(I(n.options.signal),Mn(r)&&Tn(e)){n.warnings.push(jn(r,e)),n.skipped+=1;return}throw Vn(e,r)}}function jn(t,n){let r=`${t.source.path?`${t.source.path}:`:``}line ${t.source.line}`,i=n instanceof e?n.message:String(n);return`Optional Maestro ${t.kind} skipped at ${r}: ${i}`}function Mn(e){return`optional`in e&&e.optional===!0}async function Nn(e,t,n){switch(e.kind){case`assertVisible`:await V({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await V({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!Dn(e.condition))throw z(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await V(zn(e),F(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await Pn(e,t,n)}}async function Pn(e,t,n){let r=D({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return I(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function Fn(e,t){let n=Yt(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await Ln(n.when,t)){t.skipped+=1;return}t.executed+=1,await B(e.body,t);return;case`repeat`:{let r=Xt(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)I(t.options.signal),await B(e.body,t);return}case`retry`:{let r=Math.min(Xt(n.maxRetries,1,t.context,`retry.maxRetries`),Qe.control.retryMaxRetries);t.executed+=1,await In(e.body,r,t);return}}}async function B(e,t){for(let n of e)await On(n,t)}async function In(t,n,r){let i;for(let e=0;e<=n;e+=1){I(r.options.signal);try{await B(t,r);return}catch(e){if(I(r.options.signal),!Tn(Un(e)))throw e;i=H(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function Ln(e,t){if(!nn(e,t.context,t.options))return!1;for(let n of rn(e))if(I(t.options.signal),!(await Rn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function V(e,t,n){if(!(await Rn(e,t,n)).matched)throw z(`Maestro ${e.kind} condition did not match.`)}async function Rn(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return I(n.options.signal),n.context.recordObservation(i),i}function zn(t){if(t.visible)return{kind:`visible`,selector:t.visible};if(t.notVisible)return{kind:`notVisible`,selector:t.notVisible};throw new e(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Bn(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function H(e,t){if(Hn(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Wn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Vn(e,t){return{kind:`maestroPlanStepFailure`,error:Wn(e,t),source:t.source,command:t}}function Hn(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Un(e){return Hn(e)?e.error:e}function Wn(t,n){if(!(t instanceof e)||!n||/\bline \d+\b/.test(t.message))return t;let r=n.source.path?`${n.source.path}:`:``;return new e(t.code,`${t.message} (${r}line ${n.source.line})`,t.details)}async function Gn(t,n,r={}){I(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${t.total}-step plan.`);let a={plan:t,port:n,options:r,context:qe(r.defaults,r.env?{...r.env}:{}),timing:$e,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Kn(t.steps[e],e,a)}catch(e){throw Un(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Kn(e,t,n){I(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};U(()=>n.options.observer?.commandStarted?.(s));try{let t=await On(e,n);I(n.options.signal),U(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...qn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=H(t,e);throw U(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...qn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts]})),o}}function qn(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function U(e){try{e?.()}catch{}}async function Jn(e,t,n={}){let r=Yn(e,n);return await Gn(e,t,{...n,startIndex:r})}function Yn(e,t){return t.from!==void 0||t.planDigest!==void 0?Sn(e,{from:t.from,planDigest:t.planDigest}):Cn(e,t.startIndex??0)}function Xn(e){return Jt(e)?{command:e.kind,...e.kind===`runFlow`?G(e.label??e.includePath):{}}:{command:e.kind,...Zn(e)}}function Zn(e){return`label`in e&&e.label?G(e.label):Qn(e)?G(ar(e.target)):$n(e)?er(e):e.kind===`inputText`?G(`<text>`):tr(e)}function Qn(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function $n(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function er(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return G(W(e.target));case`extendedWaitUntil`:return G(W(e.visible??e.notVisible));case`scrollUntilVisible`:return G(W(e.element))}}function tr(e){return nr(e)?rr(e):e.kind===`swipe`?ir(e):e.kind===`runFlow`?G(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?G(String(e.condition)):{}}function nr(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function rr(e){switch(e.kind){case`openLink`:return G(e.link);case`takeScreenshot`:return G(e.path);case`runScript`:return G(e.file);case`pressKey`:return G(e.key)}}function ir(e){return G(e.gesture.kind===`coordinates`?`${or(e.gesture.start)} to ${or(e.gesture.end)}`:e.gesture.direction)}function ar(e){return e.space===`target`?W(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function W(e){return e?.id??e?.text}function or(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function G(e){return e?{value:e}:{}}const sr=new Set(String.raw`^$\.*+?()[]{}|`);function cr(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function lr(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(sr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!sr.has(i))return;t+=i,n+=1}return t}function ur(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(_(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>ae(e,n)?e:null);return r?_(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function dr(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function fr(e,t){let n=[t.id===void 0?void 0:mr(e.identifier,t.id),t.text===void 0?void 0:hr(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function pr(e){return e.matches.filter(t=>ur(t,e.visibility,e.platform))}function mr(e,t){let n=e??``;return O(n)===O(t)||cr(n,t)}function hr(e,t){return[e.label,Je(e),e.identifier].filter(e=>!!e).some(e=>mr(e,t))}function gr(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function _r(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function vr(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=br(a.rect,e.rect);n===void 0||!yr(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function yr(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function br(e,t){if(!(!xr(e)||!xr(t)))return Math.fround(Math.hypot(K(e.x,e.width)-K(t.x,t.width),K(e.y,e.height)-K(t.y,t.height)))}function xr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function K(e,t){return e+Math.trunc(t/2)}function Sr(t,n={},r={}){let i=oe(t.nodes,n);n.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=e=>e.parentIndex===void 0?void 0:i.nodeByIndex.get(e.parentIndex)??t.nodes[e.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(e,r)=>{let i=c.get(e);i||(i=new WeakMap,c.set(e,i));let a=i.get(r);if(a)return a;n.onPositionComputed?.(e,r);let o=vr(t.nodes,e,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new e(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),n.onSelectorComputed?.(i);try{let e=Cr(t,i,l,u,m,p),n={matches:e,indexed:Dr(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function Cr(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=_r(m)?e.nodes.filter(e=>fr(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>Tr(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>wr(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of Er(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function wr(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function Tr(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Er(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function Dr(e,t,n){if(t===void 0)return n?n(e):[...e];let r=kr(e)[Ar(t)];return r?[r]:[]}function Or(e,t){return t===void 0?e[0]:kr(e)[Ar(t)]}function kr(e){return[...e].sort((e,t)=>{let n=q(e.rect?.y),r=q(t.rect?.y);return n===r?q(e.rect?.x)-q(t.rect?.x):n-r})}function q(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function Ar(t){let n=typeof t==`number`?t:Number(t.trim());if(!Number.isSafeInteger(n)||n<0)throw new e(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return n}const jr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Mr(e,t){let n=jr[t];if(n.kind===`divergence`)return n;let r=a(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function J(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Nr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Nr(e){return e===!0?2:+(e===!1)}function Pr(e,t,n,r={}){let i=Mr(e,n),a=Ir(e,i,r),o=Fr(t,a),s=pr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:Lr(s,t,n,a.visibility,i)}}function Fr(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Ir(e,t,n={}){return Sr(e,n,t?{orderUnindexed:e=>J(e,t)}:{})}function Lr(e,t,n,r,i){let a=n!==`ios`||!Vr(t)?e:e.filter(n=>{if(Wr(n))return!0;let i=e.filter(e=>e!==n&&Hr(n,e,t));return!i.some(e=>Wr(e)&&dr(n,e,r))&&!i.some(e=>dr(e,n,r))});return t.index===void 0&&i?J(a,i):a}function Rr(e,t){let n=t===void 0?e.find(Y):zr(e,t);return!n||!Y(n)?null:{node:n,rect:n.rect}}function zr(e,t){return Or(e,t)}function Br(e){return Y(e)?e.rect:void 0}function Y(e){return _(e.rect)}function Vr(e){return e.id!==void 0||e.text!==void 0}function Hr(e,t,n){if(n.id!==void 0&&X(e.identifier)!==X(t.identifier))return!1;if(n.text!==void 0){let n=Ur(e),r=new Set(Ur(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Ur(e){return[e.label,e.value,e.identifier].map(X).filter(e=>e!==void 0)}function X(e){if(e)return O(e)||void 0}function Wr(e){let t=ie(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Gr=Symbol(`maestroFlowProgram`),Kr=Symbol(`maestroFailureCommand`),qr=Symbol(`maestroFailurePlan`);function Jr(e,t){let n=Ze(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Qr(n),[Gr]:n}}async function Yr(e,t,n){let r;try{let i=Ye(k.dirname(e.sourcePath),n.readSource),a=await vn(e[Gr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=Sn(a,{from:n.from,planDigest:n.planDigest}),s=await Jn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,observer:Zr(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Xr(e,t){let n=ei(e[Kr]),r=e[qr].platform;return!n||r!==`android`&&r!==`ios`?[]:Pr(t,n.selector,r).ranked.map(e=>({node:e,basis:ti(n.selector,e)}))}function Zr(e,t,n){return{commandStarted:e=>t?.actionStarted?.(Z(e)),commandCompleted:e=>t?.actionCompleted?.({...Z(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=xn(e,{from:r.stepIndex,planDigest:e.digest}),a={...Z(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,isControl:Jt(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Kr]:r.command,[qr]:e};n(a),t?.actionFailed?.(a)}}}function Z(e){let t=Xn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Qr(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find($r)}function $r(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function ei(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function ti(e,t){return e.id!==void 0||e.text!==void 0&&fr({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const ni=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function ri(t,n){let r=t.files[n];if(r===void 0)throw new e(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:t.entry});return r}function ii(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=ri(t,n);if(o(n,e.flags?.replayBackend)===`maestro`){let t=Jr(r,n);return{flags:e.flags??{},options:ai(t.appTarget,e.flags?.platform)}}let i=it(r,e.flags),a=oi(i.actions);if(!a.appTarget)return;let s=si(e.flags,i.actions),c=s.platform??i.metadata.platform;return{flags:c&&s.platform===void 0?{...s,platform:c}:s,options:c===`ios`?li(a.appTarget):void 0}}catch{return}}function ai(e,t){return t===`ios`?li(e)??{}:{}}function oi(e){let t=se(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ci(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function si(e,t){let n=oi(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ci(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function li(e){let t=kt(e);return t?{appleSimulatorAppTarget:t}:void 0}const ui={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},Q=new Map;async function di(e){let t=await A.mkdtemp(k.join(rt.tmpdir(),`agent-device-materialized-`));try{let n=await gi(e.installablePath,k.join(t,`installable`)),r=e.archivePath?await gi(e.archivePath,k.join(t,`archive`)):void 0,i=tt.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{mi(i)},a);return Q.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await A.rm(t,{recursive:!0,force:!0}),e}}async function fi(e,t){await hi(e,me(Q,e,t,ui))}async function pi(e){let t=Array.from(Q.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await hi(e,t)}))}async function mi(e){let t=Q.get(e);if(t)try{await hi(e,t)}catch{}}async function hi(e,t){clearTimeout(t.timer),Q.delete(e),await A.rm(t.rootPath,{recursive:!0,force:!0})}async function gi(e,t){let n=await A.stat(e);await A.mkdir(t,{recursive:!0});let r=k.join(t,k.basename(e));return n.isDirectory()?(await A.cp(e,r,{recursive:!0}),r):(await A.copyFile(e,r),r)}function _i(e){return e.device.platform===`web`}function vi(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function yi(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await Re({session:t,sessionName:n,sessionStore:r,resourcePath:Ie.resolvePath(r.resolveSessionDir(n))})}async function bi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Le({...e,session:t})}async function xi(e,t){await t.stopSnapshotHelper(e.device)}async function Si(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>vi(r)})}async function Ci(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function wi(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return v({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function Ti(t){let{session:n,sessionName:r,sessionStore:i}=t;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[{step:`recording`,run:()=>Ei({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>yi({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Di({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>bi({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>xi(n,a)},{step:`web_browser`,run:()=>Si({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>pi(r)});let s=wi({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await Ci(o)});if(s)throw s}async function Ei(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await et({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Di(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Fe({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function Oi(e){return l(e)&&e.kind===`simulator`}function ki(e){return e.platform===`android`&&e.kind===`emulator`}const Ai=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function $(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function ji(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Mi(e){return De(ji(e))}function Ni(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return b(t)}}function Pi(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function Fi(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Pi(t)}}function Ii(t,r,i){if(t===void 0)return i;if(!n(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(i&&t!==i)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${r}" is bound to ${i}.`);return t}function Li(e){if(n(e))return e}function Ri(e,t){return{platform:t,metroHost:b(e?.metroHost),metroPort:Pi(e?.metroPort),bundleUrl:b(e?.bundleUrl),launchUrl:b(e?.launchUrl)}}function zi(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Bi(e){if(ki(e))return`10.0.2.2`;if(Oi(e))return`127.0.0.1`}function Vi(e,t){if(!e||b(e.metroHost)||b(e.bundleUrl)||e.metroPort===void 0)return e;let n=Bi(t);return n?{...e,metroHost:n}:e}function Hi(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!Ai.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ai.join(`, `)}.`);return{platform:Ii(a.platform,r,i),metroHost:Ni(a.metroHost,`metroHost`),metroPort:Fi(a.metroPort),bundleUrl:Ni(a.bundleUrl,`bundleUrl`),launchUrl:Ni(a.launchUrl,`launchUrl`)}}function Ui(e,t,n){if(n){if($(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Wi(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?f(r):void 0,s=Li(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Gi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Li(f(i)):e.platform,o=n.getRuntimeHints(r),s=Hi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Wi(n,r,i,a);return{runtime:i?Vi(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&$(s)>0?s:void 0;return{runtime:i?Vi(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ki(e){return Gi(e).runtime}function qi(e){try{return{ok:!0,data:Gi(e)}}catch(e){let t=r(e);return E(t.code,t.message,t.details)}}async function Ji(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!Yi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:ji(t)})}function Yi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Mi(e.previousRuntime)&&!Mi(e.runtime)}function Xi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&ne(i.owner,n)?te(i.fence):null;if(!a)return{status:`binding-invalid`};let o=w(T(t)),s=Me(ke(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!Qi(c.stateDir,r)||!ne(je(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function Zi(e){let t=w(T(e));return Oe(ke(t))}function Qi(e,t){return k.resolve(e)===k.resolve(t)}const $i=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function ea(e){return $i.has(e)}function ta(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=f(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=c(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${y(i)}`,`${a} ${y(e.id)}`,...n===`release`||Ae(t.classification)?[`--stale`]:[]].join(` `)}function na(t,n){if(n.classification===`allocator-held`)return ia(t,n);let r=n.claim,i=ta(t,n,Ne(n.classification)?`release`:`status`),a=f(r?{platform:r.device.family,appleOs:r.device.appleOs}:t);return new e(`DEVICE_IN_USE`,r?`${a} device ${t.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${t.name} has an ownership claim that could not be verified.`,{reason:da(n.classification),classification:n.classification,deviceKey:n.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:Ne(n.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function ra(e,t){return ua(na(e,t))}function ia(t,n){let r=n.allocatorClaim,i=f({platform:r.device.family,appleOs:r.device.appleOs}),a=ta(t,n);return new e(`DEVICE_IN_USE`,`${i} device ${t.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:n.classification,deviceKey:n.deviceKey,owner:{kind:`allocator`,stateDir:r.stateDir,allocator:r.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function aa(t,n){return new e(`COMMAND_FAILED`,`${f(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:g(n),deviceKey:w(T(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function oa(t,n,r){return new e(`COMMAND_FAILED`,`${f(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:g(n),deviceKey:w(T(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function sa(t,n){return new e(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:g(n),deviceKey:w(T(t)),retriable:!1})}function ca(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:sa(e,t)};case`missing`:return{admitted:!1,error:aa(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:oa(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:na(e,n.conflict)}}}function la(e,t,n){let r=ca(e,t,n);return r.admitted?void 0:ua(r.error)}function ua(e){let{hint:t,retriable:n,...r}=e.details??{};return E(e.code,e.message,r,{hint:t,retriable:n})}function da(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function fa(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{lr as $,pi as A,Ir as B,yi as C,_i as D,Ti as E,ni as F,zr as G,Pr as H,ri as I,Mr as J,Br as K,Xr as L,ai as M,si as N,vi as O,ii as P,ur as Q,Yr as R,wi as S,xi as T,Lr as U,Fr as V,Rr as W,gr as X,Sr as Y,pr as Z,Yi as _,bt as _t,na as a,jt as at,Di as b,ct as bt,Xi as c,Ot as ct,Mi as d,Tt as dt,z as et,Ji as f,Et as ft,Ui as g,ht as gt,ji as h,_t as ht,ca as i,Ft as it,di as j,fi as k,Ri as l,wt as lt,Ki as m,gt as mt,la as n,Pt as nt,ea as o,N as ot,zi as p,vt as pt,J as q,ra as r,P as rt,Zi as s,At as st,fa as t,F as tt,$ as u,Ct as ut,Li as v,yt as vt,bi as w,Ei as x,ot as xt,qi as y,lt as yt,Jr as z};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{E as t,y as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";var i=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,readInstalledAppProbe:()=>c,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>s});const a=`device_inventory_context_unavailable`,o=new r;async function s(e,t){return await o.run(e,t)}function c(){return o.getStore()?.findInstalledApp}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=o.getStore();if(!e)throw new n(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return t(e)||e instanceof n&&e.code===`COMMAND_FAILED`&&e.details?.reason===a?!0:e instanceof Error&&e.name===`AbortError`}export{m as a,u as i,l as n,s as o,d as r,i as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{A as t,C as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";var i=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,readInstalledAppProbe:()=>c,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>s});const a=`device_inventory_context_unavailable`,o=new r;async function s(e,t){return await o.run(e,t)}function c(){return o.getStore()?.findInstalledApp}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=o.getStore();if(!e)throw new n(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return t(e)||e instanceof n&&e.code===`COMMAND_FAILED`&&e.details?.reason===a?!0:e instanceof Error&&e.name===`AbortError`}export{m as a,u as i,l as n,s as o,d as r,i as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";const t=[`portrait`,`portrait-upside-down`,`landscape-left`,`landscape-right`],n={portrait:0,"landscape-left":1,"portrait-upside-down":2,"landscape-right":3};function r(e){return n[e]*90}function i(e){return n[e]%2==0?`PORTRAIT`:`LANDSCAPE`}function a(t){if(t===void 0)throw new e(`INVALID_ARGS`,`orientation requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.`);switch(t?.trim().toLowerCase()){case`portrait`:return`portrait`;case`portrait-upside-down`:case`upside-down`:return`portrait-upside-down`;case`landscape-left`:case`left`:return`landscape-left`;case`landscape-right`:case`right`:return`landscape-right`;default:throw new e(`INVALID_ARGS`,`Invalid rotation: ${t}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}export{a,r as i,n,i as r,t};
1
+ import{C as e}from"./sdk-contracts.js";const t=[`portrait`,`portrait-upside-down`,`landscape-left`,`landscape-right`],n={portrait:0,"landscape-left":1,"portrait-upside-down":2,"landscape-right":3};function r(e){return n[e]*90}function i(e){return n[e]%2==0?`PORTRAIT`:`LANDSCAPE`}function a(t){if(t===void 0)throw new e(`INVALID_ARGS`,`orientation requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.`);switch(t?.trim().toLowerCase()){case`portrait`:return`portrait`;case`portrait-upside-down`:case`upside-down`:return`portrait-upside-down`;case`landscape-left`:case`left`:return`landscape-left`;case`landscape-right`:case`right`:return`landscape-right`;default:throw new e(`INVALID_ARGS`,`Invalid rotation: ${t}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}export{a,r as i,n,i as r,t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{y as t}from"./sdk-contracts.js";import{g as n,l as r,m as i,o as a,x as o}from"./sdk-device.js";var s=e({markSelectionBootOccurred:()=>u,resolveExistingSessionDeviceSelection:()=>l,resolveInventoryDeviceSelection:()=>c});async function c(e){let{devices:t,selector:r,source:i}=e,s=a(r);if(i===`provider`&&!s)return p(t,r);if(i===`local`&&!s){let n=await m(t,r,e.appleSimulatorAppTarget);if(n)return n}let c=t.filter(e=>n(e,r,{includeExplicitSelectors:s}));try{return d(await o([...t],r),c,{explicitSelector:s,source:i})}catch(e){throw h(e,c)}}function l(e){return{device:e,reason:`existing-session`,source:`session`,candidateCount:1,bootOccurred:!1}}function u(e){if(!e||e.source!==`local`)return e;let{device:t}=e;return t.booted!==!0&&(t.kind===`simulator`||t.kind===`emulator`)?{...e,bootOccurred:!0}:e}function d(e,t,n){return{device:e,reason:n.explicitSelector?`explicit-selector`:n.source===`provider`?`single-provider-device`:f(e,t),source:n.source,candidateCount:t.length,bootOccurred:!1}}function f(e,t){return e.booted===!0&&t.filter(e=>e.booted===!0).length===1?`single-booted-local`:!e.booted&&t.length===1?`single-bootable-local`:`preferred-local`}async function p(e,r){let i=e.filter(e=>n(e,r)),a=i[0];if(a!==void 0&&i.length===1)return d(a,i,{explicitSelector:!1,source:`provider`});try{await o([...e],r)}catch(e){throw h(e,i)}throw new t(`AMBIGUOUS_MATCH`,`Multiple provider devices match this request.`,{...g(i),matches:i.length,hint:`Select the leased provider device explicitly with --device, --udid, or --serial.`,retrySelectors:_(i)})}async function m(e,i,a){let o=a?.trim();if(!o)return;let{readInstalledAppProbe:s}=await import(`./device-inventory-context.js`).then(e=>e.t),c=s();if(!c)return;let l=e.filter(e=>n(e,i)&&r(e)&&e.kind===`simulator`&&e.booted===!0);if(l.length<2)return;let u=(await Promise.all(l.map(async e=>await c(e,o)?e:void 0))).filter(e=>e!==void 0),d=u[0];if(d!==void 0&&u.length===1)return{device:d,reason:`single-app-installed-local`,source:`local`,candidateCount:1,bootOccurred:!1};throw u.length===0?new t(`APP_NOT_INSTALLED`,`No booted iOS simulator has ${o} installed`,{appTarget:o,...g(l),hint:`Install the app on a booted simulator, or pass --udid to select the intended device explicitly.`,retrySelectors:_(l)}):new t(`AMBIGUOUS_MATCH`,`Multiple booted iOS simulators have ${o} installed`,{appTarget:o,...g(u),hint:`Pass --udid to select the intended simulator explicitly.`,retrySelectors:_(u)})}function h(e,n){return!(e instanceof t)||e.code!==`AMBIGUOUS_MATCH`?e:new t(e.code,e.message,{...e.details??{},...g(n),retrySelectors:_(n)},e)}function g(e){return{devices:e.slice(0,10).map(e=>({id:e.id,name:e.name}))}}function _(e){return e.slice(0,10).flatMap(e=>[{flag:i(e.platform)?`--serial`:`--udid`,value:e.id},{flag:`--device`,value:e.name}])}export{u as n,l as r,s as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{g as n,l as r,m as i,o as a,x as o}from"./sdk-device.js";var s=e({markSelectionBootOccurred:()=>u,resolveExistingSessionDeviceSelection:()=>l,resolveInventoryDeviceSelection:()=>c});async function c(e){let{devices:t,selector:r,source:i}=e,s=a(r);if(i===`provider`&&!s)return p(t,r);if(i===`local`&&!s){let n=await m(t,r,e.appleSimulatorAppTarget);if(n)return n}let c=t.filter(e=>n(e,r,{includeExplicitSelectors:s}));try{return d(await o([...t],r),c,{explicitSelector:s,source:i})}catch(e){throw h(e,c)}}function l(e){return{device:e,reason:`existing-session`,source:`session`,candidateCount:1,bootOccurred:!1}}function u(e){if(!e||e.source!==`local`)return e;let{device:t}=e;return t.booted!==!0&&(t.kind===`simulator`||t.kind===`emulator`)?{...e,bootOccurred:!0}:e}function d(e,t,n){return{device:e,reason:n.explicitSelector?`explicit-selector`:n.source===`provider`?`single-provider-device`:f(e,t),source:n.source,candidateCount:t.length,bootOccurred:!1}}function f(e,t){return e.booted===!0&&t.filter(e=>e.booted===!0).length===1?`single-booted-local`:!e.booted&&t.length===1?`single-bootable-local`:`preferred-local`}async function p(e,r){let i=e.filter(e=>n(e,r)),a=i[0];if(a!==void 0&&i.length===1)return d(a,i,{explicitSelector:!1,source:`provider`});try{await o([...e],r)}catch(e){throw h(e,i)}throw new t(`AMBIGUOUS_MATCH`,`Multiple provider devices match this request.`,{...g(i),matches:i.length,hint:`Select the leased provider device explicitly with --device, --udid, or --serial.`,retrySelectors:_(i)})}async function m(e,i,a){let o=a?.trim();if(!o)return;let{readInstalledAppProbe:s}=await import(`./device-inventory-context.js`).then(e=>e.t),c=s();if(!c)return;let l=e.filter(e=>n(e,i)&&r(e)&&e.kind===`simulator`&&e.booted===!0);if(l.length<2)return;let u=(await Promise.all(l.map(async e=>await c(e,o)?e:void 0))).filter(e=>e!==void 0),d=u[0];if(d!==void 0&&u.length===1)return{device:d,reason:`single-app-installed-local`,source:`local`,candidateCount:1,bootOccurred:!1};throw u.length===0?new t(`APP_NOT_INSTALLED`,`No booted iOS simulator has ${o} installed`,{appTarget:o,...g(l),hint:`Install the app on a booted simulator, or pass --udid to select the intended device explicitly.`,retrySelectors:_(l)}):new t(`AMBIGUOUS_MATCH`,`Multiple booted iOS simulators have ${o} installed`,{appTarget:o,...g(u),hint:`Pass --udid to select the intended simulator explicitly.`,retrySelectors:_(u)})}function h(e,n){return!(e instanceof t)||e.code!==`AMBIGUOUS_MATCH`?e:new t(e.code,e.message,{...e.details??{},...g(n),retrySelectors:_(n)},e)}function g(e){return{devices:e.slice(0,10).map(e=>({id:e.id,name:e.name}))}}function _(e){return e.slice(0,10).flatMap(e=>[{flag:i(e.platform)?`--serial`:`--udid`,value:e.id},{flag:`--device`,value:e.name}])}export{u as n,l as r,s as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{r as n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{n as o,r as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=P({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(I).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(o(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw R(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n),await d(t);return}await this.session.client.typeText(e)}async fill(e,t,n){await this.tap(e,t),await this.session.client.typeText(n)}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await s(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw R(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw R(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw R(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw R(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw R(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw R(`alert`,L)}async awaitAlert(){throw R(`alert`,L)}async acceptAlert(){throw R(`alert`,L)}async dismissAlert(){throw R(`alert`,L)}async readClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw R(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250];function P(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??F(e.beforeInstallApps,e.afterInstallApps)}function F(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>I(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function I(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const L=`Limrun iOS direct sessions do not expose alert inspection yet.`;function R(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function z(e){return e.platform===`android`?B(e):V(e)}function B(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...H(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function V(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||I(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...H(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function H(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,z as t};
1
+ import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{r as n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{n as o,r as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=P({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(I).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(o(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw R(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n),await d(t);return}await this.session.client.typeText(e)}async fill(e,t,n){await this.tap(e,t),await this.session.client.typeText(n)}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await s(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw R(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw R(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw R(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw R(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw R(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw R(`alert`,L)}async awaitAlert(){throw R(`alert`,L)}async acceptAlert(){throw R(`alert`,L)}async dismissAlert(){throw R(`alert`,L)}async readClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw R(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250];function P(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??F(e.beforeInstallApps,e.afterInstallApps)}function F(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>I(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function I(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const L=`Limrun iOS direct sessions do not expose alert inspection yet.`;function R(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function z(e){return e.platform===`android`?B(e):V(e)}function B(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...H(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function V(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||I(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...H(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function H(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,z as t};
@@ -1,3 +1,3 @@
1
- import{y as e}from"./sdk-contracts.js";import{v as t}from"./sdk-device.js";import{r as n}from"./command.js";import{i as r,n as i,t as a}from"./device-claim-inspection.js";import{t as o}from"./shared.js";const s=async({positionals:t,flags:n})=>{if(t.length!==1||t[0]!==`status`&&t[0]!==`release`)throw new e(`INVALID_ARGS`,`device accepts only: status, release`);if(t[0]===`release`)return await c(n);let s=r({platform:n.platform,device:n.device,udid:n.udid,serial:n.serial}),l=s.filter(e=>i(e.classification)),u=(n.stale?l:s.filter(e=>!i(e.classification))).map(m),d={claims:u,...n.stale?{}:{hiddenStaleClaims:l.length}};return await o(n,d,()=>g(u,{staleOnly:n.stale===!0,hiddenStaleClaims:l.length,staleCommand:x(n,`status`),releasableClaims:l.filter(e=>a(e.classification)).length,releaseCommand:x(n,`release`)})),!0};async function c(t){if(t.stale!==!0)throw new e(`INVALID_ARGS`,`device release only releases provably stale claims; pass --stale to confirm.`,{hint:`A live owner is released by closing its session from its own workspace, or by stopping its daemon: agent-device daemon stop --state-dir <owner state dir>.`});let{runStaleDeviceClaimRelease:n}=await import(`./device-release.js`),r=await n({platform:t.platform,device:t.device,udid:t.udid,serial:t.serial}),i={released:r.filter(e=>e.status===`released`).map(l),retained:r.filter(e=>e.status===`retained`).map(l),refused:r.filter(e=>e.status===`refused`).map(l),changed:r.filter(e=>e.status===`changed`).map(l)};return await o(t,i,()=>u(r)),!0}function l(e){let{device:t,...n}=e;return{...n,...t?{device:h(t)}:{}}}function u(e){return e.length===0?`No local device claims matched.`:e.map(d).join(`
1
+ import{C as e}from"./sdk-contracts.js";import{v as t}from"./sdk-device.js";import{r as n}from"./command.js";import{i as r,n as i,t as a}from"./device-claim-inspection.js";import{t as o}from"./shared.js";const s=async({positionals:t,flags:n})=>{if(t.length!==1||t[0]!==`status`&&t[0]!==`release`)throw new e(`INVALID_ARGS`,`device accepts only: status, release`);if(t[0]===`release`)return await c(n);let s=r({platform:n.platform,device:n.device,udid:n.udid,serial:n.serial}),l=s.filter(e=>i(e.classification)),u=(n.stale?l:s.filter(e=>!i(e.classification))).map(m),d={claims:u,...n.stale?{}:{hiddenStaleClaims:l.length}};return await o(n,d,()=>g(u,{staleOnly:n.stale===!0,hiddenStaleClaims:l.length,staleCommand:x(n,`status`),releasableClaims:l.filter(e=>a(e.classification)).length,releaseCommand:x(n,`release`)})),!0};async function c(t){if(t.stale!==!0)throw new e(`INVALID_ARGS`,`device release only releases provably stale claims; pass --stale to confirm.`,{hint:`A live owner is released by closing its session from its own workspace, or by stopping its daemon: agent-device daemon stop --state-dir <owner state dir>.`});let{runStaleDeviceClaimRelease:n}=await import(`./device-release.js`),r=await n({platform:t.platform,device:t.device,udid:t.udid,serial:t.serial}),i={released:r.filter(e=>e.status===`released`).map(l),retained:r.filter(e=>e.status===`retained`).map(l),refused:r.filter(e=>e.status===`refused`).map(l),changed:r.filter(e=>e.status===`changed`).map(l)};return await o(t,i,()=>u(r)),!0}function l(e){let{device:t,...n}=e;return{...n,...t?{device:h(t)}:{}}}function u(e){return e.length===0?`No local device claims matched.`:e.map(d).join(`
2
2
  `)}function d(e){let n=e.device?`${t({platform:e.device.family,appleOs:e.device.appleOs})} ${e.device.name}`:e.deviceKey??e.fileName,r=f(e);switch(e.status){case`released`:return`released ${n}${r}`;case`retained`:return`retained ${n}${r} — resources not settled (${e.reason}); the claim stays until they are.`;case`refused`:return`refused ${n}${r} — ${e.reason} (${e.classification}); ${p(e)}`;case`changed`:return`changed ${n} — the claim changed while releasing; re-run device status.`}}function f(e){return e.allocator?` allocator=${e.allocator.instanceId} incarnation=${e.allocator.identityIncarnationId}`:e.session?` session=${e.session} workspace=${e.workspace}`:``}function p(e){return e.classification===`allocator-held`?`held by its managed-device allocator; it is cleared only after the allocator proves the identity removed.`:e.classification===`live`||e.classification===`owner-state-dir-gone`?e.stateDir?`close the owning session from its workspace, or stop its daemon: agent-device daemon stop --state-dir ${n(e.stateDir)}`:`close the owning session from its workspace first.`:`only provably dead owners are released; nothing was changed.`}function m(e){let t=e.claim??e.allocatorClaim;return{...e.deviceKey?{deviceKey:e.deviceKey}:{},...t?{}:{fileName:e.fileName},classification:e.classification,...t?{device:h(t.device)}:{},...e.claim?{owner:{session:e.claim.session,workspace:e.claim.workspace,stateDir:e.claim.stateDir,pid:e.claim.ownerPid,startTime:e.claim.ownerStartTime}}:{},...e.allocatorClaim?{owner:{kind:`allocator`,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}}:{},...e.error?{error:e.error}:{}}}function h(e){let{family:n,...r}=e;return{...r,platform:t({platform:n,appleOs:e.appleOs})}}function g(e,t){let n=e.map(v);if(n.length===0){if(t.staleOnly)return`No stale local device claims found.`;if(t.hiddenStaleClaims===0)return`No local device claims found.`}return[...n.length===0?[`No live local device claims found.`]:n,..._(t)].join(`
3
3
  `)}function _(e){if(e.staleOnly)return e.releasableClaims>0?[`Release provably dead owners with: ${e.releaseCommand}`]:[];if(e.hiddenStaleClaims===0)return[];let t=e.hiddenStaleClaims===1?`claim`:`claims`;return[`${e.hiddenStaleClaims} stale ${t} hidden; inspect with: ${e.staleCommand}`]}function v(e){return`${y(e)}: ${e.classification}${b(e.owner)}`}function y(e){let t=e.device;return t?`${t.platform??`unknown`} ${t.name??t.id??`claim`}`:String(e.deviceKey??e.fileName??`claim`)}function b(e){if(!e||typeof e!=`object`)return``;let t=e;return t.allocator?` allocator=${t.allocator.instanceId} incarnation=${t.allocator.identityIncarnationId} installation=${t.stateDir}`:` session=${t.session} workspace=${t.workspace}`}function x(e,t){let r=[e.platform?`--platform ${n(e.platform)}`:null,e.device?`--device ${n(e.device)}`:null,e.udid?`--udid ${n(e.udid)}`:null,e.serial?`--serial ${n(e.serial)}`:null].filter(e=>!!e);return[`agent-device device ${t}`,...r,`--stale`].join(` `)}export{s as deviceCommand};
@@ -1,3 +1,3 @@
1
- import{F as e}from"./sdk-contracts.js";import t from"node:path";import n from"node:fs";import r from"node:crypto";import{AsyncLocalStorage as i}from"node:async_hooks";import a from"node:os";const o=new i;function s(){return r.randomBytes(8).toString(`hex`)}function c(){return`${Date.now().toString(36)}-${r.randomBytes(4).toString(`hex`)}`}async function l(e,t){let n={...e,diagnosticId:c(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set,ensuredDirectories:new Set};return await o.run(n,t)}function u(e){let t=o.getStore();t&&Object.assign(t,e)}function d(){let e=o.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}}function f(e){if(!e)return;let t=o.getStore();t&&(t.sensitiveValues.add(e),t.sortedSensitiveValues=void 0)}function p(e){let t=o.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function m(e){let t=o.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function h(e,t,n){let r=Date.now();try{let i=await t();return m({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw m({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function g(e={}){let r=o.getStore();if(!r||!e.force&&!r.debug&&!r.flushOnSuccess||r.events.length===0)return null;let i=_(r);try{if(r.logPath){let e=r.events.slice(r.liveWrittenEventCount);if(e.length>0){let t=e.map(e=>JSON.stringify(y(e,i)));x(r,r.logPath,`${t.join(`
1
+ import{z as e}from"./sdk-contracts.js";import t from"node:path";import n from"node:fs";import r from"node:crypto";import{AsyncLocalStorage as i}from"node:async_hooks";import a from"node:os";const o=new i;function s(){return r.randomBytes(8).toString(`hex`)}function c(){return`${Date.now().toString(36)}-${r.randomBytes(4).toString(`hex`)}`}async function l(e,t){let n={...e,diagnosticId:c(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set,ensuredDirectories:new Set};return await o.run(n,t)}function u(e){let t=o.getStore();t&&Object.assign(t,e)}function d(){let e=o.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}}function f(e){if(!e)return;let t=o.getStore();t&&(t.sensitiveValues.add(e),t.sortedSensitiveValues=void 0)}function p(e){let t=o.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function m(e){let t=o.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function h(e,t,n){let r=Date.now();try{let i=await t();return m({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw m({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function g(e={}){let r=o.getStore();if(!r||!e.force&&!r.debug&&!r.flushOnSuccess||r.events.length===0)return null;let i=_(r);try{if(r.logPath){let e=r.events.slice(r.liveWrittenEventCount);if(e.length>0){let t=e.map(e=>JSON.stringify(y(e,i)));x(r,r.logPath,`${t.join(`
2
2
  `)}\n`)}let t=r.logRecord;return r.events=[],r.liveWrittenEventCount=0,{path:r.logPath,...t?{ref:t}:{}}}let e=b(r.session??`default`),o=new Date().toISOString().slice(0,10),s=t.join(a.homedir(),`.agent-device`,`logs`,e,o);n.mkdirSync(s,{recursive:!0});let c=new Date().toISOString().replaceAll(/[:.]/g,`-`),l=t.join(s,`${c}-${r.diagnosticId}.ndjson`),u=r.events.map(e=>JSON.stringify(y(e,i)));return n.writeFileSync(l,`${u.join(`
3
3
  `)}\n`),r.events=[],{path:l}}catch{return null}}function _(e){return e.sortedSensitiveValues??=[...e.sensitiveValues].sort((e,t)=>t.length-e.length),e.sortedSensitiveValues}function v(t,n){return y(e(n),_(t))}function y(e,t){return typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>y(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,y(n,t)]))}function b(e){return e.replaceAll(/[^a-zA-Z0-9._-]/g,`_`)}function x(e,r,i){let a=t.dirname(r);e.ensuredDirectories.has(a)||(n.mkdirSync(a,{recursive:!0}),e.ensuredDirectories.add(a)),n.appendFileSync(r,i,`utf8`)}export{d as a,h as c,g as i,l,s as n,f as o,m as r,u as s,p as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{b as t,c as n,o as r}from"./sdk-device.js";import{c as i}from"./diagnostics.js";import"./diagnostics2.js";import{n as a,r as o}from"./device-isolation.js";import{a as s,i as c,r as l}from"./device-inventory-context.js";import{AsyncLocalStorage as u}from"node:async_hooks";async function d(e){let{resolveInventoryDeviceSelection:t}=await import(`./device-selection-resolver.js`).then(e=>e.t);return await t(e)}const f=new u;function p(t,n){return!r(n)&&t instanceof e&&t.code===`DEVICE_NOT_FOUND`}function m(e,t){return!r(e)&&(!e.platform||e.platform===`apple`||e.platform===`ios`)&&e.target!==`desktop`&&(!t||t.kind===`device`)}async function h(e,t={}){return(await g(e,t)).device}async function g(e,t={}){let r={...y(e),androidAvdSelection:t.androidAvdSelection??`running-only`},{iosSimulatorSetPath:a,...o}=r,s=C(r,t),l={platform:r.platform,target:e.target,cacheHit:!1};return await i(`resolve_target_device`,async()=>{let e=x(s);if(e)return l.cacheHit=!0,e;let i=await c(r),u=[...i.devices];if(n(o.platform)&&i.source===`local`){let e=await _(u,o,{simulatorSetPath:a,appleSimulatorAppTarget:t.appleSimulatorAppTarget});return S(s,e)}return S(s,await d({devices:u,selector:o,source:i.source}))},l)}async function _(t,n,r){let i;try{i=await d({devices:t,selector:n,source:`local`,appleSimulatorAppTarget:r.appleSimulatorAppTarget})}catch(e){if(!p(e,n))throw e}let a=await v(n,r,i?.device);if(a)return a;if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No devices found`,{selector:n})}async function v(e,t,n){if(m(e,n))try{return await d({devices:await l({platform:e.platform??`ios`,target:e.target,iosSimulatorSetPath:t.simulatorSetPath,kind:`simulator`}),selector:e,source:`local`})}catch(e){if(s(e))throw e;return}}function y(n){let r=n.platform;if(n.target&&!r)throw new e(`INVALID_ARGS`,`Device target selector requires --platform. Use --platform ios|macos|android|vega|linux|apple with --target mobile|tv|desktop.`);let i=t({simulatorSetPath:o(n.iosSimulatorDeviceSet),platform:r,target:n.target}),s=a(n.androidDeviceAllowlist);return{platform:r,target:n.target,deviceName:n.device,udid:n.udid,serial:n.serial,leaseId:n.leaseId,leaseProvider:n.leaseProvider,deviceKey:n.deviceKey,clientId:n.clientId,iosSimulatorSetPath:i,androidSerialAllowlist:s?Array.from(s).sort():void 0}}async function b(e){return f.getStore()?await e():await f.run(new Map,e)}function x(e){let t=f.getStore()?.get(e);if(t)return{...t,device:{...t.device}}}function S(e,t){return f.getStore()?.set(e,{...t,device:{...t.device}}),t}function C(e,t){let{appleSimulatorAppTarget:n,...r}=t;return JSON.stringify({request:e,options:r})}export{b as i,h as n,g as r,y as t};
1
+ import{C as e}from"./sdk-contracts.js";import{b as t,c as n,o as r}from"./sdk-device.js";import{c as i}from"./diagnostics.js";import"./diagnostics2.js";import{n as a,r as o}from"./device-isolation.js";import{a as s,i as c,r as l}from"./device-inventory-context.js";import{AsyncLocalStorage as u}from"node:async_hooks";async function d(e){let{resolveInventoryDeviceSelection:t}=await import(`./device-selection-resolver.js`).then(e=>e.t);return await t(e)}const f=new u;function p(t,n){return!r(n)&&t instanceof e&&t.code===`DEVICE_NOT_FOUND`}function m(e,t){return!r(e)&&(!e.platform||e.platform===`apple`||e.platform===`ios`)&&e.target!==`desktop`&&(!t||t.kind===`device`)}async function h(e,t={}){return(await g(e,t)).device}async function g(e,t={}){let r={...y(e),androidAvdSelection:t.androidAvdSelection??`running-only`},{iosSimulatorSetPath:a,...o}=r,s=C(r,t),l={platform:r.platform,target:e.target,cacheHit:!1};return await i(`resolve_target_device`,async()=>{let e=x(s);if(e)return l.cacheHit=!0,e;let i=await c(r),u=[...i.devices];if(n(o.platform)&&i.source===`local`){let e=await _(u,o,{simulatorSetPath:a,appleSimulatorAppTarget:t.appleSimulatorAppTarget});return S(s,e)}return S(s,await d({devices:u,selector:o,source:i.source}))},l)}async function _(t,n,r){let i;try{i=await d({devices:t,selector:n,source:`local`,appleSimulatorAppTarget:r.appleSimulatorAppTarget})}catch(e){if(!p(e,n))throw e}let a=await v(n,r,i?.device);if(a)return a;if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No devices found`,{selector:n})}async function v(e,t,n){if(m(e,n))try{return await d({devices:await l({platform:e.platform??`ios`,target:e.target,iosSimulatorSetPath:t.simulatorSetPath,kind:`simulator`}),selector:e,source:`local`})}catch(e){if(s(e))throw e;return}}function y(n){let r=n.platform;if(n.target&&!r)throw new e(`INVALID_ARGS`,`Device target selector requires --platform. Use --platform ios|macos|android|vega|linux|apple with --target mobile|tv|desktop.`);let i=t({simulatorSetPath:o(n.iosSimulatorDeviceSet),platform:r,target:n.target}),s=a(n.androidDeviceAllowlist);return{platform:r,target:n.target,deviceName:n.device,udid:n.udid,serial:n.serial,leaseId:n.leaseId,leaseProvider:n.leaseProvider,deviceKey:n.deviceKey,clientId:n.clientId,iosSimulatorSetPath:i,androidSerialAllowlist:s?Array.from(s).sort():void 0}}async function b(e){return f.getStore()?await e():await f.run(new Map,e)}function x(e){let t=f.getStore()?.get(e);if(t)return{...t,device:{...t.device}}}function S(e,t){return f.getStore()?.set(e,{...t,device:{...t.device}}),t}function C(e,t){let{appleSimulatorAppTarget:n,...r}=t;return JSON.stringify({request:e,options:r})}export{b as i,h as n,g as r,y as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{r as t,t as n}from"./toolchain-probe.js";import{t as r}from"./tool-provider3.js";async function i(e){let i=r();if(!await i.isAvailable())return{id:`toolchain`,status:`info`,summary:`Vega toolchain: Vega CLI not found.`,hint:`Install Vega Developer Tools or ensure ~/vega/bin/vega is executable.`,command:`vega --version`};let o=await i.version({allowFailure:!0,timeoutMs:n}),s=await a(e),l=t(o.stdout),u=s.devices.some(e=>e.platform===`vega`&&e.kind===`emulator`&&e.target===`tv`&&e.booted===!0);return{id:`toolchain`,status:o.exitCode===0?`pass`:`info`,summary:l?`Vega toolchain: ${l}; ${u?`VVD running`:`no running VVD`}.`:`Vega toolchain: CLI found but version check failed.`,hint:u?void 0:`Start the Vega Virtual Device and retry doctor.`,evidence:{vegaVersion:l??null,deviceList:c(s)}}}async function a(e){try{return{devices:await e.listLocalDeviceInventory({platform:`vega`,target:`tv`}),listedSerials:[]}}catch(t){if(e.shouldPropagateInventoryProbeError(t))throw t;return{devices:[],listedSerials:o(t)}}}function o(t){if(!(t instanceof e)||t.code!==`DEVICE_NOT_FOUND`)return[];let n=t.details?.listedSerials;return s(n)?n:[]}function s(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function c(e){return(e.devices.length>0?e.devices.map(e=>e.id):e.listedSerials).join(`, `)||null}export{i as vegaToolchainCheck};
1
+ import{C as e}from"./sdk-contracts.js";import{r as t,t as n}from"./toolchain-probe.js";import{t as r}from"./tool-provider3.js";async function i(e){let i=r();if(!await i.isAvailable())return{id:`toolchain`,status:`info`,summary:`Vega toolchain: Vega CLI not found.`,hint:`Install Vega Developer Tools or ensure ~/vega/bin/vega is executable.`,command:`vega --version`};let o=await i.version({allowFailure:!0,timeoutMs:n}),s=await a(e),l=t(o.stdout),u=s.devices.some(e=>e.platform===`vega`&&e.kind===`emulator`&&e.target===`tv`&&e.booted===!0);return{id:`toolchain`,status:o.exitCode===0?`pass`:`info`,summary:l?`Vega toolchain: ${l}; ${u?`VVD running`:`no running VVD`}.`:`Vega toolchain: CLI found but version check failed.`,hint:u?void 0:`Start the Vega Virtual Device and retry doctor.`,evidence:{vegaVersion:l??null,deviceList:c(s)}}}async function a(e){try{return{devices:await e.listLocalDeviceInventory({platform:`vega`,target:`tv`}),listedSerials:[]}}catch(t){if(e.shouldPropagateInventoryProbeError(t))throw t;return{devices:[],listedSerials:o(t)}}}function o(t){if(!(t instanceof e)||t.code!==`DEVICE_NOT_FOUND`)return[];let n=t.details?.listedSerials;return s(n)?n:[]}function s(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function c(e){return(e.devices.length>0?e.devices.map(e=>e.id):e.listedSerials).join(`, `)||null}export{i as vegaToolchainCheck};
package/dist/src/error.js CHANGED
@@ -1,2 +1,2 @@
1
- import{O as e,j as t,y as n}from"./sdk-contracts.js";import{r}from"./replay-divergence.js";function i(i,o={}){let s=i instanceof n?e(i):i;if(process.stderr.write(`Error (${s.code}): ${s.message}\n`),s.cause){let e=s.cause.code?`${s.cause.code} `:``;process.stderr.write(`Cause: ${e}${s.cause.message}\n`)}s.hint&&process.stderr.write(`Hint: ${s.hint}\n`);let c=a(t(s.details));c.length>0&&process.stderr.write(`${c.join(`
1
+ import{C as e,F as t,M as n}from"./sdk-contracts.js";import{r}from"./replay-divergence.js";function i(i,o={}){let s=i instanceof e?n(i):i;if(process.stderr.write(`Error (${s.code}): ${s.message}\n`),s.cause){let e=s.cause.code?`${s.cause.code} `:``;process.stderr.write(`Cause: ${e}${s.cause.message}\n`)}s.hint&&process.stderr.write(`Hint: ${s.hint}\n`);let c=a(t(s.details));c.length>0&&process.stderr.write(`${c.join(`
2
2
  `)}\n`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}\n`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}\n`),s.logPathUnavailable&&process.stderr.write(`Remote Diagnostics: unavailable (${s.logPathUnavailable})\n`);let l=r(s.details);l&&process.stderr.write(`${l}\n`),o.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}\n`)}function a(e){return e.flatMap(e=>{if(e.kind===`element-match`){let t=e.matches-e.candidates.length;return[`Candidates:`,...e.candidates.map(t=>` ${o(t,e.refsGeneration)}`),...t>0?[` +${t} more`]:[]]}return[`Devices:`,...e.devices.map(e=>` ${e.id} ${e.name}`)]})}function o(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}export{i as printHumanError};
package/dist/src/exec.js CHANGED
@@ -1 +1 @@
1
- import{x as e,y as t}from"./sdk-contracts.js";import{o as n}from"./sdk-remote-config.js";import{a as r,r as i,s as a}from"./diagnostics.js";import o from"node:path";import{constants as s}from"node:fs";import{AsyncLocalStorage as c}from"node:async_hooks";import{access as l,stat as u}from"node:fs/promises";import{spawn as d,spawnSync as f}from"node:child_process";import{Readable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";const h=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,g=[`.com`,`.exe`,`.bat`,`.cmd`],_=new c;async function v(e,t){return e?await _.run(e,t):await t()}async function y(e){return await _.run(void 0,e)}async function b(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}async function x(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}function S(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function C(e,t,n={}){let r=P(e),i=j();return new Promise((a,o)=>{let s=d(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,f=!1,p=Z(n.timeoutMs),m=p?setTimeout(()=>{f=!0,$(s,n.detached)},p):null,h=Q(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),te(s,n.stdin).catch(i=>{h.didAbort||f||ne(i)||(o(ee(r,e,t,i)),$(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(U(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let d=s??1;if(!h.didAbort&&f&&p){o(z(r,e,t,p,d,c,u));return}let g=W(h,r,e,t,d,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:d,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function w(e){let t=K(e);if(!t)return!1;if(o.isAbsolute(t))return Y(t);let n=process.env.PATH;if(!n)return!1;let r=q();for(let e of n.split(o.delimiter)){let n=e.trim();if(n){for(let e of J(t,r))if(await Y(o.join(n,e)))return!0}}return!1}async function T(e,n){let r=G(e,n,`executable`);if(r){if(!await Y(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function E(e,n){let r=G(e,n,`file`);if(r){if(!await X(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function D(e,n,r={}){let i=P(e),a=f(i,n,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:Z(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new t(`COMMAND_FAILED`,`${i} timed out after ${Z(r.timeoutMs)}ms`,{cmd:e,args:n,timeoutMs:Z(r.timeoutMs)},a.error):o===`ENOENT`?I(i,e,a.error):L(i,e,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw B(i,e,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function O(e,t,n={}){return k(e,t,n).pid}function k(e,t,n={}){let r=P(e),i=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),a=i.pid??0,o=new Promise(e=>{i.once(`error`,t=>{e({pid:a,error:t.message})}),i.once(`exit`,(t,n)=>{e({pid:a,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return i.unref(),{pid:a,exited:o}}function A(e,t,n={}){let r=P(e),i=j(),a=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=Q(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(U(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=W(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function j(){let e=r(),t=e.debug===!0,i=n(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!i)return M();i&&e.flushOnSuccess!==!0&&a({flushOnSuccess:!0});let o=Date.now(),s=!1;return{emitForegroundCompletion:(e,t)=>{s||(s=!0,N({cmd:e,args:t,startedAtMs:o}))},emitBackgroundSpawn:(e,t)=>{N({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{s||(s=!0,N({cmd:e,args:t,startedAtMs:o,data:{event:n}}))}}}function M(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function N(e){let t=e.args.slice(0,6);i({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function P(e){let n=K(e);if(!n)throw new t(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function F(e,t,n,r){return r.code===`ENOENT`?I(e,t,r):L(e,t,n,r)}function I(e,n,r){return new t(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:n},r)}function L(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:n,args:r},i)}function ee(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function R(t,n,r){return e({cmd:n,args:r,executable:t})}function z(e,n,r,i,a,o,s){return new t(`COMMAND_FAILED`,`${e} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function B(e,n,r,i,a,o){return new t(`COMMAND_FAILED`,`${e} exited with code ${i}`,H({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}function V(e,n,r){if(e.exitCode===0)return e;throw new t(`COMMAND_FAILED`,n,H(e,typeof r==`function`?r(e):r))}function H(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function U(e,t,n,r,i){return e.didAbort?R(t,n,r):F(t,n,r,i)}function W(e,t,n,r,i,a,o,s){return e.didAbort?R(t,n,r):i!==0&&!a?B(t,n,r,i,o,s):null}function G(e,n,r){let i=e?.trim();if(i){if(!o.isAbsolute(i)||i.includes(`\0`))throw new t(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(e)}`,{envName:n,path:e});return i}}function K(e){let t=e.trim();return!t||t.includes(`\0`)?null:o.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:h.test(t)?t:null}function q(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return g;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:g}function J(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function Y(e){try{return await X(e)?(await l(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function X(e){try{return(await u(e)).isFile()}catch{return!1}}function Z(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function Q(e,t){let n=!1,r=()=>{n=!0,$(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function $(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function te(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await m(p.from([t]),e.stdin)}}function ne(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}export{T as a,A as c,x as d,D as f,y as h,V as i,O as l,v as m,H as n,E as o,w as p,Y as r,b as s,S as t,k as u};
1
+ import{C as e,T as t}from"./sdk-contracts.js";import{o as n}from"./sdk-remote-config.js";import{a as r,r as i,s as a}from"./diagnostics.js";import o from"node:path";import{constants as s}from"node:fs";import{AsyncLocalStorage as c}from"node:async_hooks";import{access as l,stat as u}from"node:fs/promises";import{spawn as d,spawnSync as f}from"node:child_process";import{Readable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";const h=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,g=[`.com`,`.exe`,`.bat`,`.cmd`],_=new c;async function v(e,t){return e?await _.run(e,t):await t()}async function y(e){return await _.run(void 0,e)}async function b(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}async function x(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}function S(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function C(e,t,n={}){let r=N(e),i=A();return new Promise((a,o)=>{let s=d(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,f=!1,p=Z(n.timeoutMs),m=p?setTimeout(()=>{f=!0,$(s,n.detached)},p):null,h=Q(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),ne(s,n.stdin).catch(i=>{h.didAbort||f||re(i)||(o(te(r,e,t,i)),$(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(U(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let d=s??1;if(!h.didAbort&&f&&p){o(R(r,e,t,p,d,c,u));return}let g=W(h,r,e,t,d,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:d,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function w(e){let t=K(e);if(!t)return!1;if(o.isAbsolute(t))return Y(t);let n=process.env.PATH;if(!n)return!1;let r=q();for(let e of n.split(o.delimiter)){let n=e.trim();if(n){for(let e of J(t,r))if(await Y(o.join(n,e)))return!0}}return!1}async function ee(t,n){let r=G(t,n,`executable`);if(r){if(!await Y(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function T(t,n){let r=G(t,n,`file`);if(r){if(!await X(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function E(t,n,r={}){let i=N(t),a=f(i,n,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:Z(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new e(`COMMAND_FAILED`,`${i} timed out after ${Z(r.timeoutMs)}ms`,{cmd:t,args:n,timeoutMs:Z(r.timeoutMs)},a.error):o===`ENOENT`?F(i,t,a.error):I(i,t,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw B(i,t,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function D(e,t,n={}){return O(e,t,n).pid}function O(e,t,n={}){let r=N(e),i=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),a=i.pid??0,o=new Promise(e=>{i.once(`error`,t=>{e({pid:a,error:t.message})}),i.once(`exit`,(t,n)=>{e({pid:a,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return i.unref(),{pid:a,exited:o}}function k(e,t,n={}){let r=N(e),i=A(),a=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=Q(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(U(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=W(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function A(){let e=r(),t=e.debug===!0,i=n(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!i)return j();i&&e.flushOnSuccess!==!0&&a({flushOnSuccess:!0});let o=Date.now(),s=!1;return{emitForegroundCompletion:(e,t)=>{s||(s=!0,M({cmd:e,args:t,startedAtMs:o}))},emitBackgroundSpawn:(e,t)=>{M({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{s||(s=!0,M({cmd:e,args:t,startedAtMs:o,data:{event:n}}))}}}function j(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function M(e){let t=e.args.slice(0,6);i({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function N(t){let n=K(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function P(e,t,n,r){return r.code===`ENOENT`?F(e,t,r):I(e,t,n,r)}function F(t,n,r){return new e(`TOOL_MISSING`,`${t} not found in PATH`,{cmd:n},r)}function I(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to run ${t}`,{cmd:n,args:r},i)}function te(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to write stdin for ${t}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function L(e,n,r){return t({cmd:n,args:r,executable:e})}function R(t,n,r,i,a,o,s){return new e(`COMMAND_FAILED`,`${t} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function z(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&typeof t.details?.timeoutMs==`number`}function B(t,n,r,i,a,o){return new e(`COMMAND_FAILED`,`${t} exited with code ${i}`,H({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}function V(t,n,r){if(t.exitCode===0)return t;throw new e(`COMMAND_FAILED`,n,H(t,typeof r==`function`?r(t):r))}function H(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function U(e,t,n,r,i){return e.didAbort?L(t,n,r):P(t,n,r,i)}function W(e,t,n,r,i,a,o,s){return e.didAbort?L(t,n,r):i!==0&&!a?B(t,n,r,i,o,s):null}function G(t,n,r){let i=t?.trim();if(i){if(!o.isAbsolute(i)||i.includes(`\0`))throw new e(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(t)}`,{envName:n,path:t});return i}}function K(e){let t=e.trim();return!t||t.includes(`\0`)?null:o.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:h.test(t)?t:null}function q(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return g;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:g}function J(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function Y(e){try{return await X(e)?(await l(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function X(e){try{return(await u(e)).isFile()}catch{return!1}}function Z(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function Q(e,t){let n=!1,r=()=>{n=!0,$(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function $(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function ne(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await m(p.from([t]),e.stdin)}}function re(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}export{V as a,b as c,O as d,x as f,y as g,v as h,Y as i,k as l,w as m,H as n,ee as o,E as p,z as r,T as s,S as t,D as u};
package/dist/src/file.js CHANGED
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{D as t,t as n}from"./owner-identity.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";async function o(t){let{lockDirPath:n,owner:o}=t,l=i.join(n,`owner.json`),d=Date.now()+(t.timeoutMs??3e4),f=t.pollMs??100,p=t.ownerGraceMs??5e3,m=t.description??`process lock`;for(a.mkdirSync(i.dirname(n),{recursive:!0});Date.now()<d;)try{a.mkdirSync(n),s(l,o);let e=!1;return async()=>{e||(e=!0,a.rmSync(n,{recursive:!0,force:!0}))}}catch(e){let t=e;if(t.code!==`EEXIST`)throw t;if(c(n,l,p))continue;await r(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:n,...u(n,l)})}function s(e,n){t({destination:e,contents:JSON.stringify(n)})}function c(e,t,n){let r=null;try{r=a.statSync(e)}catch{return!0}let i=l(t);return i?!d(i)&&(a.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0)}function l(e){try{return JSON.parse(a.readFileSync(e,`utf8`))}catch{return null}}function u(e,t){let r=Date.now(),i=l(t),o;try{o=Math.max(0,Math.round(r-a.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...i?{ownerPid:i.pid,ownerStartTime:i.startTime,ownerAgeMs:Math.max(0,Math.round(r-i.acquiredAtMs)),ownerLiveness:n({owner:i})}:{}}}function d(e){let t=n({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}export{o as t};
1
+ import{C as e}from"./sdk-contracts.js";import{D as t,t as n}from"./owner-identity.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";async function o(t){let{lockDirPath:n,owner:o}=t,l=i.join(n,`owner.json`),d=Date.now()+(t.timeoutMs??3e4),f=t.pollMs??100,p=t.ownerGraceMs??5e3,m=t.description??`process lock`;for(a.mkdirSync(i.dirname(n),{recursive:!0});Date.now()<d;)try{a.mkdirSync(n),s(l,o);let e=!1;return async()=>{e||(e=!0,a.rmSync(n,{recursive:!0,force:!0}))}}catch(e){let t=e;if(t.code!==`EEXIST`)throw t;if(c(n,l,p))continue;await r(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:n,...u(n,l)})}function s(e,n){t({destination:e,contents:JSON.stringify(n)})}function c(e,t,n){let r=null;try{r=a.statSync(e)}catch{return!0}let i=l(t);return i?!d(i)&&(a.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0)}function l(e){try{return JSON.parse(a.readFileSync(e,`utf8`))}catch{return null}}function u(e,t){let r=Date.now(),i=l(t),o;try{o=Math.max(0,Math.round(r-a.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...i?{ownerPid:i.pid,ownerStartTime:i.startTime,ownerAgeMs:Math.max(0,Math.round(r-i.acquiredAtMs)),ownerLiveness:n({owner:i})}:{}}}function d(e){let t=n({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}export{o as t};
package/dist/src/find.js CHANGED
@@ -1 +1 @@
1
- import{d as e}from"./sdk-contracts.js";import{Dn as t,Mn as n,On as r,Pt as i,kn as a,mt as o}from"./sdk-batch.js";import{c as s}from"./session-store.js";import{f as c,g as l,h as u,m as d,y as f}from"./runtime.js";import{n as p,t as m}from"./success-text.js";import{d as h}from"./app-inventory-contract.js";import{a as g,i as _}from"./request-runtime-binding.js";import{C as v,b as y,y as b}from"./session-snapshot.js";import{t as x}from"./snapshot-quality-verdict.js";import{t as S}from"./internal/daemon.js";import{t as C}from"./snapshot-runtime-binding.js";import{l as w,n as T,u as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(t,n){let r=n[0]?.rect;if(!r)return t;let i=t.filter(t=>{if(!t.rect)return!1;let n=e(t.rect);return n.x>=r.x&&n.x<=r.x+r.width&&n.y>=r.y&&n.y<=r.y+r.height}),a=i.length>0?i:t;return a.length<2?a:k(a,n,u(n))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!l(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!l(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,t,n){let r={matches:e.length,candidates:e.slice(0,5).map(e=>h(e,0,!1))};return _(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${n}". Use a more specific locator or selector.`,{locator:t,query:n,...r})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:t,locator:n,query:i,selectorExpression:a,flags:o,platform:s}=e,u=f.findAct,d=t.filter(e=>!l(e,t[0])),p=u.resolution,m;if(m=a?c(u,d,a,{platform:s}).list?.matchedNodes??[]:r(d,n,i,{requireRect:p.requireRect}).matches,m=O(m,t),m.length>1){P(p);let e=I(m,o);if(!e)return{ok:!1,response:N(m,n,i)};m=e}let h=m[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:_(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,session:n,req:r,logPath:i,locator:a,query:o,sessionStore:s,sessionName:c}=e,l=w({device:t,session:n,sessionStore:s,sessionName:c,req:r,logPath:i,capture:e.capture});return async()=>{let{snapshot:e}=await l.capture({flags:{...r.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:o,shouldScope:z(a)},sparseVerdictQueryScope:{query:o,shouldScope:z(a)}}});return{nodes:e.nodes,snapshotQuality:e.snapshotQuality,systemSurfaceOnly:e.systemSurfaceOnly}}}function R(e){return _(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(e){let{req:r,sessionName:s,logPath:c,sessionStore:l,invoke:u}=e,p=r.command;if(p!==`find`)return null;let m=r.positionals??[],h=t(m,r.flags);if(!h.ok)return _(h.code,h.message);let{locator:v,query:y,action:b,value:S}=h.parsed;if(r.flags?.record&&!a(b))return _(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let w=await T({req:r,sessionName:s,logPath:c,sessionStore:l,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(w)return w;let D=l.get(s);if(!D)return g();let O=D.device,k=await C({command:`find`,device:O,session:D,plan:i({hasActiveApp:D.appBundleId!==void 0,intent:o(b)}),inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!k.ok)return k.response;let A=n(v,y),j=L({device:O,session:D,req:r,logPath:c,locator:v,query:y,sessionStore:l,sessionName:s,capture:k.capture}),M={req:r,sessionName:s,logPath:c,sessionStore:l,invoke:u,session:D,device:O,command:p,locator:v,query:y,publicFlags:X(r.flags),boundFocusPoint:k.focusPoint,boundTypeText:k.typeText},N=await j();if(x(N.snapshotQuality))return R(N.snapshotQuality);let{nodes:P}=N,I=F({nodes:P,locator:v,query:y,selectorExpression:A,flags:r.flags,platform:O.platform});if(!I.ok)return E(I.response,N);let z=I.node,B=await d(f.findAct,P,z),H=B.node,U=await V(M,{node:z,resolvedNode:H,ref:`@${H.ref}`,nodes:P,actionFlags:{...r.flags??{},noRecord:!0},...B.kind===`occluded`?{occludedNode:B.node}:{}},b,S);return U&&E(U,N)}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes}}async function U(t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,locator:u,query:d,publicFlags:f}=t,h=await c({token:r.token,session:i,command:`click`,positionals:[n.ref],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});if(!h.ok)return h;let g=n.resolvedNode.rect?e(n.resolvedNode.rect):n.node.rect?e(n.node.rect):null,_={ref:n.ref,locator:u,query:d};g&&(_.x=g.x,_.y=g.y);let v=m(h.data)??`Tapped ${n.ref}${g?` (${g.x}, ${g.y})`:``}`;return Object.assign(_,p(v)),s(a,o,r,l,{ref:n.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,publicFlags:u}=e;if(n===void 0)return _(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let d=await c({token:r.token,session:i,command:`fill`,positionals:[t.ref,n],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});return d.ok&&s(a,o,r,l,{ref:t.ref,action:`fill`},{flags:u}),d}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,t,n){let{req:r,logPath:i,session:a}=e;if(!n)return _(`INVALID_ARGS`,`find type requires text`);let o=await q(e,t);if(!o.ok)return o;v(a);let s=e.boundTypeText;if(!s)return _(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let c=await D({operations:{typeText:s}},[n],y(i,r.flags,a.appBundleId,a.trace?.outPath));return Y(e,t,`type`),{ok:!0,data:c??{ref:t.ref}}}async function q(t,n){let{req:r,logPath:i,session:a}=t,o=J(n,`be focused`);if(o)return o;let s=n.resolvedNode.rect?e(n.resolvedNode.rect):null;if(!s)return _(`COMMAND_FAILED`,`matched element has no bounds`);v(a);let c=t.boundFocusPoint;return c?{ok:!0,data:await S({operations:{focusPoint:c}},s,y(i,r.flags,a.appBundleId,a.trace?.outPath))??{ref:n.ref}}:_(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,t){let n=e.occludedNode;return n?_(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${t} safely`,{ref:`@${n.ref}`,interactionBlocked:n.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,session:a,command:o,publicFlags:c}=e;s(i,a,r,o,{ref:t.ref,action:n},{flags:c})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
1
+ import{p as e}from"./sdk-contracts.js";import{Dn as t,Mn as n,On as r,Pt as i,kn as a,mt as o}from"./sdk-batch.js";import{c as s}from"./session-store.js";import{f as c,g as l,m as u,p as d,u as f}from"./runtime.js";import{n as p,t as m}from"./success-text.js";import{f as h}from"./app-inventory-contract.js";import{a as g,i as _}from"./request-runtime-binding.js";import{S as v,T as y,x as b}from"./session-snapshot.js";import{t as x}from"./snapshot-quality-verdict.js";import{t as S}from"./internal/daemon.js";import{t as C}from"./snapshot-runtime-binding.js";import{l as w,n as T,u as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(t,n){let r=n[0]?.rect;if(!r)return t;let i=t.filter(t=>{if(!t.rect)return!1;let n=e(t.rect);return n.x>=r.x&&n.x<=r.x+r.width&&n.y>=r.y&&n.y<=r.y+r.height}),a=i.length>0?i:t;return a.length<2?a:k(a,n,d(n))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!u(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!u(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,t,n){let r={matches:e.length,candidates:e.slice(0,5).map(e=>h(e,0,!1))};return _(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${n}". Use a more specific locator or selector.`,{locator:t,query:n,...r})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:t,locator:n,query:i,selectorExpression:a,flags:o,platform:s}=e,c=l.findAct,d=t.filter(e=>!u(e,t[0])),p=c.resolution,m;if(m=a?f(c,d,a,{platform:s}).list?.matchedNodes??[]:r(d,n,i,{requireRect:p.requireRect}).matches,m=O(m,t),m.length>1){P(p);let e=I(m,o);if(!e)return{ok:!1,response:N(m,n,i)};m=e}let h=m[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:_(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,session:n,req:r,logPath:i,locator:a,query:o,sessionStore:s,sessionName:c}=e,l=w({device:t,session:n,sessionStore:s,sessionName:c,req:r,logPath:i,capture:e.capture});return async()=>{let{snapshot:e}=await l.capture({flags:{...r.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:o,shouldScope:z(a)},sparseVerdictQueryScope:{query:o,shouldScope:z(a)}}});return{nodes:e.nodes,snapshotQuality:e.snapshotQuality,systemSurfaceOnly:e.systemSurfaceOnly,iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}}}function R(e){return _(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(e){let{req:r,sessionName:s,logPath:u,sessionStore:d,invoke:f}=e,p=r.command;if(p!==`find`)return null;let m=r.positionals??[],h=t(m,r.flags);if(!h.ok)return _(h.code,h.message);let{locator:v,query:y,action:b,value:S}=h.parsed;if(r.flags?.record&&!a(b))return _(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let w=await T({req:r,sessionName:s,logPath:u,sessionStore:d,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(w)return w;let D=d.get(s);if(!D)return g();let O=D.device,k=await C({command:`find`,device:O,session:D,plan:i({hasActiveApp:D.appBundleId!==void 0,intent:o(b)}),inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!k.ok)return k.response;let A=n(v,y),j=L({device:O,session:D,req:r,logPath:u,locator:v,query:y,sessionStore:d,sessionName:s,capture:k.capture}),M={req:r,sessionName:s,logPath:u,sessionStore:d,invoke:f,session:D,device:O,command:p,locator:v,query:y,publicFlags:X(r.flags),boundFocusPoint:k.focusPoint,boundTypeText:k.typeText},N=await j();if(x(N.snapshotQuality))return R(N.snapshotQuality);let{nodes:P}=N,I=F({nodes:P,locator:v,query:y,selectorExpression:A,flags:r.flags,platform:O.platform});if(!I.ok)return E(I.response,N);let z=I.node,B=await c(l.findAct,P,z),H=B.node,U=`@${H.ref}`,W={...r.flags??{},noRecord:!0},G=await V(M,{node:z,resolvedNode:H,ref:U,nodes:P,...N.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:N.iosSystemSurfaceBundleId}:{},actionFlags:W,...B.kind===`occluded`?{occludedNode:B.node}:{}},b,S);return G&&E(G,N)}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes,...e.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}:{}}}async function U(t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,locator:u,query:d,publicFlags:f}=t,h=await c({token:r.token,session:i,command:`click`,positionals:[n.ref],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});if(!h.ok)return h;let g=n.resolvedNode.rect?e(n.resolvedNode.rect):n.node.rect?e(n.node.rect):null,_={ref:n.ref,locator:u,query:d};g&&(_.x=g.x,_.y=g.y);let v=m(h.data)??`Tapped ${n.ref}${g?` (${g.x}, ${g.y})`:``}`;return Object.assign(_,p(v)),s(a,o,r,l,{ref:n.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,publicFlags:u}=e;if(n===void 0)return _(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let d=await c({token:r.token,session:i,command:`fill`,positionals:[t.ref,n],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});return d.ok&&s(a,o,r,l,{ref:t.ref,action:`fill`},{flags:u}),d}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,t,n){let{req:r,logPath:i,session:a}=e;if(!n)return _(`INVALID_ARGS`,`find type requires text`);let o=await q(e,t);if(!o.ok)return o;y(a);let s=e.boundTypeText;if(!s)return _(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let c=await D({operations:{typeText:s}},[n],v(i,r.flags,a.appBundleId,a.trace?.outPath));return Y(e,t,`type`),{ok:!0,data:c??{ref:t.ref}}}async function q(t,n){let{req:r,logPath:i,session:a}=t,o=J(n,`be focused`);if(o)return o;let s=n.resolvedNode.rect?e(n.resolvedNode.rect):null;if(!s)return _(`COMMAND_FAILED`,`matched element has no bounds`);y(a);let c=t.boundFocusPoint;return c?{ok:!0,data:await S({operations:{focusPoint:c}},s,v(i,r.flags,a.appBundleId,a.trace?.outPath))??{ref:n.ref}}:_(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,t){let n=e.occludedNode;return n?_(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${t} safely`,{ref:`@${n.ref}`,interactionBlocked:n.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,session:a,command:o,publicFlags:c}=e;s(i,a,r,o,{ref:t.ref,action:n},{flags:c})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
@@ -1 +1 @@
1
- import{f as e}from"./sdk-batch.js";import{t}from"./session-snapshot.js";import{i as n,r}from"./interaction-ref-policy.js";import{captureSnapshotForSession as i,createInteractionRuntime as a}from"./interaction.js";function o(t){if(!e(t.command))return{};let i=n(t.command,t.flags);if(i)return{response:i};let a=r(t.flags);if(!a)return{};let o=t.session.snapshot?.nodes??[];return{observe:async()=>await s(t,a,o)}}async function s(e,n,r){let i=c(e);if(!i)return;let a=await i.interactions.settleObservation({...n,baselineNodes:r,session:e.sessionName,requestId:e.req.meta?.requestId}),o=t(e.session,a);return o===void 0?a:{...a,refsGeneration:o}}function c(e){try{return a({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,contextFromFlags:e.contextFromFlags,captureSnapshotForSession:i})}catch{return}}export{o as planGenericSettleObservation};
1
+ import{f as e}from"./sdk-batch.js";import{t}from"./session-snapshot.js";import{i as n,r}from"./interaction-ref-policy.js";import{captureSnapshotForSession as i,createInteractionRuntime as a}from"./interaction.js";function o(t){if(!e(t.command))return{};let i=n(t.command,t.flags);if(i)return{response:i};let a=r(t.flags);if(!a)return{};let o=t.session.snapshot,c={nodes:o?.nodes??[],...o?.iosSystemSurfaceBundleId?{surfaceBundleId:o.iosSystemSurfaceBundleId}:{}};return{observe:async()=>await s(t,a,c)}}async function s(e,n,r){let i=c(e);if(!i)return;let a=await i.interactions.settleObservation({...n,baseline:r,session:e.sessionName,requestId:e.req.meta?.requestId}),o=t(e.session,a);return o===void 0?a:{...a,refsGeneration:o}}function c(e){try{return a({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,contextFromFlags:e.contextFromFlags,captureSnapshotForSession:i})}catch{return}}export{o as planGenericSettleObservation};