agent-device 0.21.23 → 0.21.25

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 (435) hide show
  1. package/README.md +6 -6
  2. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.23.apk → agent-device-android-ime-helper-0.21.25.apk} +0 -0
  3. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.25.apk.sha256 +1 -0
  4. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.23.manifest.json → agent-device-android-ime-helper-0.21.25.manifest.json} +4 -4
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.25.apk +0 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.25.apk.sha256 +1 -0
  7. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.25.manifest.json +16 -0
  8. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +12 -6
  9. package/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/RectResponseTests.swift +21 -0
  10. package/apple/snapshot-bridge/README.md +9 -7
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +159 -4
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerHttpRequestFraming.swift +139 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerListenerPeer.swift +41 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerListenerToken.swift +25 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +56 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +14 -5
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +18 -11
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +8 -0
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +12 -0
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +25 -1
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCaptureTarget.swift +1 -1
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotExecution.swift +29 -5
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +0 -3
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +35 -13
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +59 -26
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +19 -5
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +50 -106
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +142 -54
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +4 -1
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +21 -19
  31. package/dist/src/absence-observation-errors.js +1 -0
  32. package/dist/src/adapter.js +1 -1
  33. package/dist/src/adb-executor.js +2 -2
  34. package/dist/src/adb-failure.js +2 -2
  35. package/dist/src/adb.js +1 -1
  36. package/dist/src/agent-browser-lifecycle.js +1 -1
  37. package/dist/src/agent-browser-process-record.js +1 -1
  38. package/dist/src/agent-browser-provider.js +1 -1
  39. package/dist/src/agent-browser-tool.js +1 -1
  40. package/dist/src/agent-device-client.js +2 -2
  41. package/dist/src/alert.js +1 -1
  42. package/dist/src/android-adb.d.ts +3 -2
  43. package/dist/src/android-adb.js +1 -1
  44. package/dist/src/android-input-ownership.js +1 -1
  45. package/dist/src/android-system-surface-disclosure.js +1 -0
  46. package/dist/src/android-text-entry.js +1 -0
  47. package/dist/src/android.js +1 -1
  48. package/dist/src/app-backend.js +1 -1
  49. package/dist/src/app-helpers.js +1 -1
  50. package/dist/src/app-inventory.d.ts +4 -0
  51. package/dist/src/app-launch.js +1 -1
  52. package/dist/src/app-lifecycle.js +4 -3
  53. package/dist/src/app-lifecycle2.js +2 -2
  54. package/dist/src/app-log-files.js +1 -1
  55. package/dist/src/app-log-reconnect.js +1 -1
  56. package/dist/src/app-log-runtime2.js +3 -3
  57. package/dist/src/app-resolution-facade.js +1 -1
  58. package/dist/src/app-resolution.js +2 -2
  59. package/dist/src/app-state-runtime.d.ts +15 -0
  60. package/dist/src/apple-runner-platform.js +1 -1
  61. package/dist/src/application-lifecycle-interaction.js +1 -1
  62. package/dist/src/artifact-download.js +1 -1
  63. package/dist/src/auth.js +1 -1
  64. package/dist/src/aws-device-farm-connection.js +1 -0
  65. package/dist/src/back-mode.js +1 -1
  66. package/dist/src/backend-snapshot-options.js +1 -1
  67. package/dist/src/boot-diagnostics.js +1 -1
  68. package/dist/src/browserstack-connection.js +1 -0
  69. package/dist/src/capture-disclosure.js +1 -0
  70. package/dist/src/cli-config.js +1 -1
  71. package/dist/src/cli-help.js +36 -17
  72. package/dist/src/cli-output.js +1 -1
  73. package/dist/src/cli-runner.js +3 -1
  74. package/dist/src/cli.js +3 -4
  75. package/dist/src/client-companion-tunnel.js +1 -0
  76. package/dist/src/client-metro.js +1 -1
  77. package/dist/src/client-types.d.ts +15 -7
  78. package/dist/src/cloud-artifacts.d.ts +3 -2
  79. package/dist/src/code-signature-cache.js +1 -1
  80. package/dist/src/code-signature.js +1 -1
  81. package/dist/src/command-metadata.js +73 -1
  82. package/dist/src/command-policy.js +1 -0
  83. package/dist/src/command-schema.js +3 -3
  84. package/dist/src/command-surface.js +1 -1
  85. package/dist/src/command-tools.js +2 -2
  86. package/dist/src/connection-runtime.js +1 -1
  87. package/dist/src/connection-verification.js +1 -0
  88. package/dist/src/connection.js +5 -5
  89. package/dist/src/contracts.d.ts +1 -1
  90. package/dist/src/contracts.js +1 -1
  91. package/dist/src/daemon-client-lease-beat.js +1 -1
  92. package/dist/src/daemon-client-lifecycle.js +1 -1
  93. package/dist/src/daemon-client-liveness-probe.js +1 -1
  94. package/dist/src/daemon-policy-file.js +1 -1
  95. package/dist/src/daemon-registration-owner.js +1 -1
  96. package/dist/src/daemon-registration.js +1 -1
  97. package/dist/src/daemon-resolution.js +3 -1
  98. package/dist/src/debug-symbols-facade.js +1 -1
  99. package/dist/src/device-claim-inspection.js +1 -1
  100. package/dist/src/device-input-state.d.ts +6 -17
  101. package/dist/src/device-inventory-context.js +1 -1
  102. package/dist/src/device-readiness-runtime.js +1 -1
  103. package/dist/src/device-release.js +1 -1
  104. package/dist/src/device-selection-resolver.js +1 -1
  105. package/dist/src/device-shell.js +1 -1
  106. package/dist/src/device.js +3 -1
  107. package/dist/src/devicectl.js +1 -1
  108. package/dist/src/diagnostics.js +1 -1
  109. package/dist/src/doctor-facade.js +1 -1
  110. package/dist/src/durable-capture-resource.js +1 -1
  111. package/dist/src/durable-resource.js +1 -1
  112. package/dist/src/engine-eval-script.js +1 -1
  113. package/dist/src/error.js +1 -1
  114. package/dist/src/exec.js +1 -1
  115. package/dist/src/expo-dev-client-launch.js +1 -0
  116. package/dist/src/file.js +3 -1
  117. package/dist/src/find.js +1 -1
  118. package/dist/src/finders.js +1 -1
  119. package/dist/src/generic-settle.js +1 -1
  120. package/dist/src/generic.js +1 -1
  121. package/dist/src/gesture-admission.js +1 -1
  122. package/dist/src/gesture-plan-types.d.ts +2 -5
  123. package/dist/src/gesture-plan.js +1 -1
  124. package/dist/src/gesture-runtime.js +1 -1
  125. package/dist/src/harmonyos.js +1 -1
  126. package/dist/src/hdc.js +1 -1
  127. package/dist/src/helper.js +2 -2
  128. package/dist/src/human-control.js +1 -1
  129. package/dist/src/ime-rebind.js +1 -1
  130. package/dist/src/ime-state.js +1 -1
  131. package/dist/src/index.d.ts +4 -4
  132. package/dist/src/index.js +1 -1
  133. package/dist/src/input-actions.js +1 -1
  134. package/dist/src/input-actions2.js +2 -2
  135. package/dist/src/install-source-network-transport.js +1 -1
  136. package/dist/src/install-source2.js +1 -1
  137. package/dist/src/interaction-error.js +1 -0
  138. package/dist/src/interaction-positionals.js +1 -1
  139. package/dist/src/interaction.js +1 -1
  140. package/dist/src/interaction2.js +1 -1
  141. package/dist/src/interactor-operation-catalog.js +1 -1
  142. package/dist/src/interactor.js +5 -5
  143. package/dist/src/interactor2.js +1 -1
  144. package/dist/src/interactors.js +1 -1
  145. package/dist/src/internal/bin.js +1 -1
  146. package/dist/src/internal/daemon.js +5 -1
  147. package/dist/src/internal/png-worker.js +1 -1
  148. package/dist/src/inventory.js +2 -2
  149. package/dist/src/inventory2.js +1 -1
  150. package/dist/src/inventory6.js +1 -1
  151. package/dist/src/io.d.ts +2 -2
  152. package/dist/src/ios-client.js +1 -1
  153. package/dist/src/ios-settings.js +1 -1
  154. package/dist/src/ios-snapshot-acquisition.js +1 -1
  155. package/dist/src/ios-snapshot-adapter.js +1 -1
  156. package/dist/src/ios-snapshot-engine.js +1 -1
  157. package/dist/src/ios-snapshot-runtime.js +1 -1
  158. package/dist/src/keyed-lock.js +1 -1
  159. package/dist/src/launch-confirmation.js +1 -1
  160. package/dist/src/lease.js +1 -1
  161. package/dist/src/limrun-runtime-dependencies.js +1 -1
  162. package/dist/src/limrun.d.ts +5 -564
  163. package/dist/src/limrun.js +1 -1
  164. package/dist/src/linux.js +1 -1
  165. package/dist/src/load.js +1 -1
  166. package/dist/src/local-interactor-operation-set.js +1 -1
  167. package/dist/src/log-stream.js +9 -9
  168. package/dist/src/mechanics.js +16 -16
  169. package/dist/src/metro.js +1 -1
  170. package/dist/src/metro2.js +1 -1
  171. package/dist/src/mobile-snapshot-semantics.js +1 -1
  172. package/dist/src/observability.js +1 -1
  173. package/dist/src/observation.js +1 -2
  174. package/dist/src/open-target-resolution.js +1 -1
  175. package/dist/src/output-path.js +1 -1
  176. package/dist/src/overlay.js +1 -3
  177. package/dist/src/perf-facade.js +1 -1
  178. package/dist/src/perf-runtime-operation-builder.js +1 -1
  179. package/dist/src/perf-runtime.js +1 -1
  180. package/dist/src/perf-target.js +1 -1
  181. package/dist/src/physical-device-control.js +1 -1
  182. package/dist/src/platform-request-scope.js +1 -1
  183. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  184. package/dist/src/platform-runtime-app-log-android-transport.js +1 -1
  185. package/dist/src/platform-runtime-apple-resources.js +1 -0
  186. package/dist/src/platform-runtime-claim-recovery.js +1 -0
  187. package/dist/src/platform-runtime-daemon-services.js +1 -0
  188. package/dist/src/platform-runtime-host.js +1 -1
  189. package/dist/src/platform-runtime-network-web-transport.js +1 -1
  190. package/dist/src/platform-runtime-open-target.js +1 -1
  191. package/dist/src/platform-runtime-operation-host.js +4 -4
  192. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  193. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  194. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  195. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  196. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  197. package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
  198. package/dist/src/platform-runtime-screen-recording-web-host.js +1 -1
  199. package/dist/src/platform-runtime-unavailable.js +1 -1
  200. package/dist/src/platform-runtime.js +1 -1
  201. package/dist/src/platform-runtime2.js +1 -1
  202. package/dist/src/plugin.js +1 -0
  203. package/dist/src/plugins/webdriver.d.ts +111 -0
  204. package/dist/src/plugins/webdriver.js +1 -0
  205. package/dist/src/plugins.d.ts +2 -1
  206. package/dist/src/plugins2.js +1 -1
  207. package/dist/src/png-crop-bytes.js +1 -1
  208. package/dist/src/png-resize.js +1 -0
  209. package/dist/src/png-worker-client.js +1 -1
  210. package/dist/src/png-worker-contract.js +1 -1
  211. package/dist/src/process-entry.js +1 -1
  212. package/dist/src/process-exit.js +1 -1
  213. package/dist/src/process.js +1 -1
  214. package/dist/src/provider-credential-fingerprint.js +1 -1
  215. package/dist/src/provider-device-admission.js +1 -1
  216. package/dist/src/provider-device-runtime.d.ts +556 -0
  217. package/dist/src/provider-policy.js +1 -0
  218. package/dist/src/provider-profile-fields.js +1 -1
  219. package/dist/src/provider-webdriver.js +1 -2
  220. package/dist/src/proxy.js +2 -2
  221. package/dist/src/quality-warnings.js +1 -1
  222. package/dist/src/react-devtools.js +2 -0
  223. package/dist/src/react-native-overlay2.js +3 -0
  224. package/dist/src/react-native.js +1 -1
  225. package/dist/src/record-runtime.js +1 -1
  226. package/dist/src/record-trace.js +1 -1
  227. package/dist/src/recording.js +2 -2
  228. package/dist/src/register-builtins.js +1 -1
  229. package/dist/src/remote-bridge.js +1 -0
  230. package/dist/src/remote-config-core.js +1 -0
  231. package/dist/src/remote-config.js +1 -1
  232. package/dist/src/remote-config2.js +1 -1
  233. package/dist/src/replay-backend-registry.js +1 -0
  234. package/dist/src/replay-divergence.js +1 -1
  235. package/dist/src/replay-maestro-backend.js +117 -0
  236. package/dist/src/replay-script-selection.js +1 -0
  237. package/dist/src/replay.js +1 -3
  238. package/dist/src/replay2.js +1 -0
  239. package/dist/src/reporting.js +3 -3
  240. package/dist/src/request-cancel.js +1 -1
  241. package/dist/src/request-providers.js +1 -1
  242. package/dist/src/request-runtime-binding.js +1 -1
  243. package/dist/src/result-serialization.js +1 -1
  244. package/dist/src/retry.js +1 -1
  245. package/dist/src/retry2.js +1 -0
  246. package/dist/src/runner-artifact-manifest.js +1 -1
  247. package/dist/src/runner-cache-retention.js +1 -0
  248. package/dist/src/runner-cache-trim.js +1 -0
  249. package/dist/src/runner-client.js +1 -1
  250. package/dist/src/runner-dev-tools-security.js +1 -1
  251. package/dist/src/runner-device-readiness.js +1 -1
  252. package/dist/src/runner-device-set.js +1 -0
  253. package/dist/src/runner-error-classification.js +3 -3
  254. package/dist/src/runner-exchange.js +1 -1
  255. package/dist/src/runner-lease.js +1 -0
  256. package/dist/src/runner-operations-facade.js +1 -1
  257. package/dist/src/runner-retention.js +1 -0
  258. package/dist/src/runner-start-budget.js +1 -1
  259. package/dist/src/runner-startup-transport.js +1 -0
  260. package/dist/src/runner-toolchain-probe.js +2 -0
  261. package/dist/src/runner.js +2 -1
  262. package/dist/src/runtime-command-surface.js +1 -0
  263. package/dist/src/runtime-deployment.js +1 -0
  264. package/dist/src/runtime-factory.js +1 -0
  265. package/dist/src/runtime-session.js +1 -0
  266. package/dist/src/runtime-transport-hints.js +1 -1
  267. package/dist/src/runtime.js +2 -1
  268. package/dist/src/runtime10.js +2 -2
  269. package/dist/src/runtime2.js +4 -4
  270. package/dist/src/runtime3.js +1 -1
  271. package/dist/src/runtime4.js +5 -5
  272. package/dist/src/runtime5.js +1 -1
  273. package/dist/src/runtime6.js +1 -1
  274. package/dist/src/runtime7.js +1 -1
  275. package/dist/src/runtime8.js +1 -1
  276. package/dist/src/runtime9.js +1 -1
  277. package/dist/src/screen-recording-transport.js +1 -1
  278. package/dist/src/screenshot-density.js +1 -1
  279. package/dist/src/screenshot-image.js +1 -1
  280. package/dist/src/screenshot-runtime.js +1 -1
  281. package/dist/src/screenshot3.js +5 -5
  282. package/dist/src/sdk-batch-runner.js +2 -2
  283. package/dist/src/sdk-batch.js +2 -2
  284. package/dist/src/sdk-contracts.d.ts +20 -29
  285. package/dist/src/sdk-contracts.js +2 -2
  286. package/dist/src/sdk-device.js +1 -1
  287. package/dist/src/sdk-finders.d.ts +1 -1
  288. package/dist/src/sdk-finders.js +1 -1
  289. package/dist/src/sdk-io.d.ts +4 -2
  290. package/dist/src/sdk-remote-config.d.ts +4 -0
  291. package/dist/src/sdk-remote-config.js +1 -1
  292. package/dist/src/sdk-selectors.d.ts +5 -6
  293. package/dist/src/sdk-selectors.js +1 -1
  294. package/dist/src/selection.js +0 -0
  295. package/dist/src/selector-pipeline-policy.js +1 -1
  296. package/dist/src/selector-runtime.js +1 -1
  297. package/dist/src/selectors.js +1 -1
  298. package/dist/src/server.js +2 -2
  299. package/dist/src/session-allocation.js +1 -1
  300. package/dist/src/session-replay-runtime-failure-response.js +1 -0
  301. package/dist/src/session-runtime-admission.js +1 -1
  302. package/dist/src/session.js +1 -1
  303. package/dist/src/session2.js +5 -5
  304. package/dist/src/settings.js +1 -1
  305. package/dist/src/settings2.js +1 -1
  306. package/dist/src/simctl-settings.js +1 -1
  307. package/dist/src/simctl.js +1 -1
  308. package/dist/src/simulator-boot.js +1 -1
  309. package/dist/src/simulator-state.js +1 -1
  310. package/dist/src/simulator.js +1 -1
  311. package/dist/src/snapshot-capture-annotations.js +1 -1
  312. package/dist/src/snapshot-chrome.js +1 -0
  313. package/dist/src/snapshot-desktop-projection.js +1 -1
  314. package/dist/src/snapshot-evidence.js +1 -0
  315. package/dist/src/snapshot-node-lookup.js +1 -0
  316. package/dist/src/snapshot-occlusion.js +1 -0
  317. package/dist/src/snapshot-quality-verdict.js +1 -0
  318. package/dist/src/snapshot-runtime-binding.js +1 -1
  319. package/dist/src/snapshot-runtime.js +1 -1
  320. package/dist/src/snapshot-state.js +1 -1
  321. package/dist/src/snapshot.js +1 -1
  322. package/dist/src/snapshot2.js +1 -1
  323. package/dist/src/snapshot3.js +1 -1
  324. package/dist/src/src.js +5 -1
  325. package/dist/src/src2.js +1 -1
  326. package/dist/src/src3.js +2 -1
  327. package/dist/src/store.js +1 -1
  328. package/dist/src/surface-snapshot2.js +1 -1
  329. package/dist/src/target-evidence-tree.js +1 -0
  330. package/dist/src/target-evidence.js +1 -1
  331. package/dist/src/text-entry-focus.js +1 -1
  332. package/dist/src/tool-provider2.js +1 -1
  333. package/dist/src/touch-runtime.js +1 -1
  334. package/dist/src/touch-runtime2.js +1 -1
  335. package/dist/src/tree.js +1 -1
  336. package/dist/src/tv-remote.js +1 -1
  337. package/dist/src/type-text-runtime.js +1 -1
  338. package/dist/src/undici.js +8 -8
  339. package/dist/src/update-check.js +1 -1
  340. package/dist/src/vars.js +1 -1
  341. package/dist/src/version.js +1 -1
  342. package/dist/src/video.js +2 -2
  343. package/dist/src/wait.js +1 -0
  344. package/dist/src/web.js +1 -1
  345. package/dist/src/web2.js +1 -1
  346. package/package.json +22 -19
  347. package/server.json +2 -2
  348. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.23.apk.sha256 +0 -1
  349. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.23.apk +0 -0
  350. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.23.apk.sha256 +0 -1
  351. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.23.manifest.json +0 -16
  352. package/dist/src/adb-transport.js +0 -1
  353. package/dist/src/alert-runtime.js +0 -1
  354. package/dist/src/app-deployment-resolution.js +0 -2
  355. package/dist/src/app-inventory-contract.js +0 -1
  356. package/dist/src/app-log-session-resource.js +0 -1
  357. package/dist/src/application-lifecycle-runtime.js +0 -1
  358. package/dist/src/auth-session.js +0 -1
  359. package/dist/src/cache.js +0 -1
  360. package/dist/src/capabilities.js +0 -1
  361. package/dist/src/capture.js +0 -1
  362. package/dist/src/catalog.js +0 -1
  363. package/dist/src/click-button.js +0 -1
  364. package/dist/src/client-metro-companion.js +0 -1
  365. package/dist/src/client-options.js +0 -3
  366. package/dist/src/compatibility-policy.js +0 -1
  367. package/dist/src/daemon-artifacts.js +0 -1
  368. package/dist/src/daemon-client-transport.js +0 -1
  369. package/dist/src/daemon-http.js +0 -1
  370. package/dist/src/device-claim-rule.js +0 -1
  371. package/dist/src/device-rotation.js +0 -1
  372. package/dist/src/device-session.js +0 -3
  373. package/dist/src/device2.js +0 -1
  374. package/dist/src/device3.js +0 -3
  375. package/dist/src/dispatch-resolve.js +0 -4
  376. package/dist/src/format.js +0 -1
  377. package/dist/src/gesture-plan-types.js +0 -1
  378. package/dist/src/host.js +0 -1
  379. package/dist/src/human-control-contract.js +0 -1
  380. package/dist/src/interaction-ref-policy.js +0 -1
  381. package/dist/src/interactor-operation-binding.js +0 -1
  382. package/dist/src/keyboard-actions.js +0 -1
  383. package/dist/src/lease-context.js +0 -1
  384. package/dist/src/lease-registry-scope.js +0 -1
  385. package/dist/src/lease-scope.js +0 -1
  386. package/dist/src/managed-device-scope.js +0 -1
  387. package/dist/src/observe-until.js +0 -1
  388. package/dist/src/output-common.js +0 -5
  389. package/dist/src/owner-identity.js +0 -3
  390. package/dist/src/path-resolution.js +0 -1
  391. package/dist/src/perf-runtime-plan.js +0 -1
  392. package/dist/src/platform-runtime-app-log-process.js +0 -1
  393. package/dist/src/platform-runtime-managed-owner.js +0 -1
  394. package/dist/src/platform-runtime-screen-recording-process-host.js +0 -1
  395. package/dist/src/png.js +0 -1
  396. package/dist/src/prepare-kind.js +0 -1
  397. package/dist/src/provider-device-runtimes.js +0 -1
  398. package/dist/src/provider-session-ownership.js +0 -2
  399. package/dist/src/providers.js +0 -1
  400. package/dist/src/registry.js +0 -68
  401. package/dist/src/request-admission.js +0 -1
  402. package/dist/src/request-cancellation.js +0 -1
  403. package/dist/src/request-progress-protocol.js +0 -1
  404. package/dist/src/runner-cache-metadata.js +0 -3
  405. package/dist/src/runner-disposal.js +0 -1
  406. package/dist/src/runner-session-types.js +0 -1
  407. package/dist/src/runtime-admission.js +0 -1
  408. package/dist/src/screen-recording-admission-ledger.js +0 -1
  409. package/dist/src/screen-recording-resource-recovery.js +0 -1
  410. package/dist/src/screenshot-result.js +0 -1
  411. package/dist/src/script.js +0 -1
  412. package/dist/src/scroll-command.js +0 -1
  413. package/dist/src/scroll-gesture.js +0 -1
  414. package/dist/src/scroll-indicator.js +0 -1
  415. package/dist/src/session-artifact-paths.js +0 -1
  416. package/dist/src/session-paths.js +0 -1
  417. package/dist/src/session-repair-tombstone.js +0 -1
  418. package/dist/src/session-routing.js +0 -1
  419. package/dist/src/session-snapshot.js +0 -1
  420. package/dist/src/snapshot4.js +0 -1
  421. package/dist/src/src4.js +0 -1
  422. package/dist/src/src5.js +0 -1
  423. package/dist/src/src6.js +0 -1
  424. package/dist/src/src7.js +0 -2
  425. package/dist/src/src8.js +0 -115
  426. package/dist/src/string-enum.js +0 -1
  427. package/dist/src/success-text.js +0 -1
  428. package/dist/src/timeouts.js +0 -1
  429. package/dist/src/touch-reference-frame.js +0 -1
  430. package/dist/src/transport.js +0 -3
  431. package/dist/src/ttl-memo.js +0 -1
  432. package/dist/src/verified-file.js +0 -1
  433. package/dist/src/viewport.js +0 -1
  434. package/dist/src/window-state.js +0 -1
  435. /package/dist/src/{doctor-output.js → doctor-lines.js} +0 -0
@@ -1,3 +0,0 @@
1
- import{P as e}from"./sdk-contracts.js";import{A as t,C as n,D as r,E as i,F as a,I as o,L as s,M as c,N as l,O as u,P as d,R as f,S as p,T as m,_ as h,b as g,g as _,j as v,k as ee,m as te,v as y,w as ne,x as re,y as ie}from"./log-stream.js";import{i as ae,r as oe}from"./ios-client.js";import"./instance-client.js";import{promises as se}from"fs";import"net";import ce from"os";import b,{basename as le}from"path";import ue,{createHash as de}from"crypto";import"child_process";function x(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function S(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let fe=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return fe=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};const pe=/^[a-z][a-z0-9+.-]*:/i,me=e=>pe.test(e);let C=e=>(C=Array.isArray,C(e)),he=C;function ge(e){return typeof e==`object`?e??{}:{}}function _e(e){if(!e)return!0;for(let t in e)return!1;return!0}function ve(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const ye=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new c(`${e} must be an integer`);if(t<0)throw new c(`${e} must be a positive integer`);return t},be=e=>{try{return JSON.parse(e)}catch{return}},w=`0.59.0`;function xe(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const Se=()=>{let e=xe();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":Te(Deno.build.os),"X-Stainless-Arch":we(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":Te(globalThis.process.platform??`unknown`),"X-Stainless-Arch":we(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Ce();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Ce(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const we=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Te=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let Ee;const De=()=>Ee??=Se();function Oe(){if(typeof fetch<`u`)return n.fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Limrun({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ke(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Ae(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ke({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}async function je(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Me=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Ne(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new c(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}const T={off:0,error:200,warn:300,info:400,debug:500},E=(e,t,n)=>{if(e){if(ve(T,e))return e;A(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(T))}`)}};function D(){}function O(e,t,n){return!t||T[e]>T[n]?D:t[e].bind(t)}const Pe={error:D,warn:D,info:D,debug:D};let k=new WeakMap;function A(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Pe;let r=k.get(t);if(r&&r[0]===n)return r[1];let i={error:O(`error`,t,n),warn:O(`warn`,t,n),info:O(`info`,t,n),debug:O(`debug`,t,n)};return k.set(t,[n,i]),i}const j=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function Fe(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(n.status===204)return null;if(t.options.__binaryResponse)return n;let e=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return e?.includes(`application/json`)||e?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return A(e).debug(`[${r}] response parsed`,j({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}var M,Ie=class e extends Promise{constructor(e,t,n=Fe){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,M.set(this,void 0),x(this,M,e,`f`)}_thenUnwrap(t){return new e(S(this,M,`f`),this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(S(this,M,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};M=new WeakMap;var N,Le=class{constructor(e,t,n,r){N.set(this,void 0),x(this,N,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new c("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,N,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(N=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Re=class extends Ie{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Fe(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},P=class extends Le{constructor(e,t,n,r){super(e,t,n,r),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.getPaginatedItems();if(!(typeof this.options.query==`object`&&`endingBefore`in(this.options.query||{}))){let t=e[e.length-1]?.metadata.id;return t?{...this.options,query:{...ge(this.options.query),startingAfter:t}}:null}let t=e[0]?.metadata.id;return t?{...this.options,query:{...ge(this.options.query),endingBefore:t}}:null}};const ze=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function F(e,t,n){return ze(),new File(e,t??`unknown_file`,n)}function Be(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const Ve=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,He=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Ue=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&He(e),We=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Ge(e,t,n){if(ze(),e=await e,Ue(e))return e instanceof File?e:F([await e.arrayBuffer()],e.name);if(We(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),F(await I(r),t,n)}let r=await I(e);if(t||=Be(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return F(r,t,n)}async function I(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(He(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ve(e))for await(let n of e)t.push(...await I(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Ke(e)}`)}return t}function Ke(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var L=class{constructor(e){this._client=e}},qe=class extends L{get(e,t){return this._client.get(`/v1/analytics`,{query:Je(e),...t})}getInstances(e,t){return this._client.get(`/v1/analytics/instances`,{query:Je(e),...t})}};function Je(e){let{startedAt:t,stoppedAt:n,...r}=e,i={...r};for(let[e,r]of Object.entries({startedAt:t,stoppedAt:n}))if(r!==void 0)for(let[t,n]of Object.entries(r))n!==void 0&&(i[`${e}[${t}]`]=n);return i}const Ye=Symbol(`brand.privateNullableHeaders`);function*Xe(e){if(!e)return;if(Ye in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():he(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=he(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const R=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Xe(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Ye]:!0,values:t,nulls:n}};function Ze(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Qe=Object.freeze(Object.create(null)),z=((e=Ze)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Qe)??Qe)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=s.exec(o))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new c(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
2
- `)}\n${a}\n${t}`)}return a})(Ze);var B=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/gradle_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/gradle_instances`,P,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/gradle_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(z`/v1/gradle_instances/${e}`,t)}},V=class extends L{create(e,t){return this._client.post(`/v1/scoped_tokens`,{body:e,...t})}},$e=class extends L{list(e={},t){return this._client.get(`/v1/assets`,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/assets/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}get(e,t={},n){return this._client.get(z`/v1/assets/${e}`,{query:t,...n})}getOrCreate(e,t){return this._client.put(`/v1/assets`,{body:e,...t})}};function et(e,t){if(!t)return{body:e};let n=0;return{body:new ReadableStream({pull(r){if(n>=e.length){r.close();return}let i=e.subarray(n,Math.min(n+262144,e.length));n+=i.length,r.enqueue(i),t(n,e.length)}}),duplex:`half`}}var tt=class extends $e{async getOrUpload(e,t){let r=await this.getOrCreate({name:e.name??le(e.path),kind:e.kind??`App`,...e.platform&&{platform:e.platform},...e.ttl&&{ttl:e.ttl},...e.uploadOptions},t),i=await se.readFile(e.path),a=de(`md5`).update(i).digest(`hex`);if(r.md5&&r.md5===a)return{id:r.id,name:r.name,signedDownloadUrl:r.signedDownloadUrl,kind:r.kind,...r.platform&&{platform:r.platform},md5:r.md5,...r.expiresAt&&{expiresAt:r.expiresAt}};let o=await n.fetch(r.signedUploadUrl,{headers:{...e.onUploadProgress&&{"Content-Length":i.length.toString()},"Content-Type":`application/octet-stream`},method:`PUT`,...et(i,e.onUploadProgress)});if(o.status!==200)throw Error(`Failed to upload asset: ${o.status} ${await o.text()}`);return{id:r.id,name:r.name,signedDownloadUrl:r.signedDownloadUrl,kind:r.kind,...r.platform&&{platform:r.platform},md5:a,...r.expiresAt&&{expiresAt:r.expiresAt}}}},nt=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/ios_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/ios_instances`,P,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/ios_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(z`/v1/ios_instances/${e}`,t)}},rt=class extends nt{listSessionArtifacts(e,t,n){return this._client.get(z`/v1/ios_instances/${e}/session_artifacts`,{query:t?{kind:t}:void 0,...n})}listRecordings(e,t){return this.listSessionArtifacts(e,`recording`,t)}listAppLogs(e,t){return this.listSessionArtifacts(e,`appLog`,t)}listEvents(e,t){return this.listSessionArtifacts(e,`eventLog`,t)}},it=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/android_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/android_instances`,P,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/android_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(z`/v1/android_instances/${e}`,t)}},at=class extends it{listSessionArtifacts(e,t,n){return this._client.get(z`/v1/android_instances/${e}/session_artifacts`,{query:t?{kind:t}:void 0,...n})}listRecordings(e,t){return this.listSessionArtifacts(e,`recording`,t)}listAppLogs(e,t){return this.listSessionArtifacts(e,`appLog`,t)}listEvents(e,t){return this.listSessionArtifacts(e,`eventLog`,t)}},ot=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/xcode_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/xcode_instances`,P,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/xcode_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(z`/v1/xcode_instances/${e}`,t)}};function H(e){let t=e.status.token;if(!t)throw Error(`Instance ${e.metadata.id} came back without its token: the credential used can read it but not control it.`);return t}var U=class extends Error{constructor(e){super(`Instance ${e} was gone before it reported any cache status`),this.instanceId=e,this.name=`XcodeCacheGoneError`}},W=class extends Error{constructor(e,t,n){super(`Timed out after ${Math.round(t/1e3)}s waiting for the cache ${e} to finish`+(n?` (last phase: ${n[e].phase})`:``)),this.side=e,this.timeoutMs=t,this.cache=n,this.name=`XcodeCacheTimeoutError`}};const st={restore:12e5,save:72e4};function ct(e){return e===`disabled`||e===`unsupported`||e===`restored`||e===`skipped`||e===`failed`}function lt(e){return e===`disabled`||e===`published`||e===`skipped`||e===`failed`||e===`timed_out`}function ut(e,t){return t===`restore`?ct(e.restore.phase):lt(e.save.phase)}function dt(e,t={}){let r=t.side??`restore`,i=t.timeoutMs??st[r],a=e.baseURL;for(;a.endsWith(`/`);)a=a.slice(0,-1);let o=`${a}/v1/xcode_instances/${encodeURIComponent(e.instanceId)}/cache`;return new Promise((a,s)=>{let c,l=``,u=!1,d=e=>{if(!u){u=!0,clearTimeout(f),t.signal?.removeEventListener(`abort`,m);try{_.close()}catch{}e()}},f=setTimeout(()=>d(()=>s(new W(r,i,c))),i),m=()=>d(()=>s(t.signal?.reason??Error(`aborted`))),h=!1,g=()=>{h||u||(h=!0,n.fetch(o,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:`application/json`}}).then(async t=>{if(h=!1,t.status!==404){await t.text().catch(()=>void 0);return}d(()=>c?a({cache:c,gone:!0}):s(new U(e.instanceId)))}).catch(()=>{h=!1}))},_=p({url:o,fetch:async(t,r)=>{let i=await n.fetch(t,r);return i.status===404&&d(()=>c?a({cache:c,gone:!0}):s(new U(e.instanceId))),i},onConnect:()=>t.onOpen?.(),headers:{Authorization:`Bearer ${e.apiKey}`,Accept:`text/event-stream`},onMessage:e=>{if(e.event!==`cache`&&e.event!==`gone`)return;let n;try{n=JSON.parse(typeof e.data==`string`?e.data:String(e.data))}catch(e){d(()=>s(Error(`Cache stream sent unreadable data: ${e}`)));return}if(c=n,e.event===`gone`){g();return}let i=`${n.restore.phase}/${n.restore.reason??``}|${n.save.phase}/${n.save.reason??``}`;i!==l&&(l=i,t.onUpdate?.(n)),ut(n,r)&&d(()=>a({cache:n,gone:!1}))}});if(t.signal?.aborted){m();return}t.signal?.addEventListener(`abort`,m,{once:!0})})}var ft=class extends U{constructor(e){super(e),this.name=`XcodeSnapshotGoneError`,this.message=`Instance ${e} was gone before it reported any disk snapshot status`}},pt=class extends W{constructor(e){super(e.side,e.timeoutMs,e.cache),this.name=`XcodeSnapshotTimeoutError`,this.message=e.message.replace(`the cache `,`the disk snapshot `),this.snapshot=e.cache?G(e.cache):void 0}};function G(e){let{cacheKey:t,...n}=e.save;return{...e,save:{...n,...t===void 0?{}:{snapshotKey:t}}}}async function mt(e,t={}){let{onUpdate:n,...r}=t;try{let t=await dt(e,{...r,...n?{onUpdate:e=>n(G(e))}:{}});return{snapshot:G(t.cache),gone:t.gone}}catch(e){throw e instanceof U?new ft(e.instanceId):e instanceof W?new pt(e):e}}function ht(e,t){let n=b.resolve(e),r=`limsync-cache-${b.basename(n)}-${ue.createHash(`sha1`).update(n).digest(`hex`).slice(0,8)}`;return{cacheKey:r,basisCacheDir:t??b.join(ce.tmpdir(),r)}}function K(e,t,n,r){return e.getOrCreate({name:t,ttl:n||`336h`,...r}).catch(e=>{let n=`Failed to create upload URL for asset '${t}': ${e instanceof Error?e.message:e}`;throw Error(n,{cause:e})})}const gt=[`none`,`error`,`warn`,`info`,`debug`];function _t(e,t){let n=gt.indexOf(t),r=e=>n>=gt.indexOf(e);return(t,n)=>{r(t)&&(t===`error`||t===`warn`?console[t](e,n):console.log(e,n))}}function vt(e){return(t,n)=>{if(t.trim()===``)throw Error(`commandLine must not be empty`);if(n?.timeoutSeconds!==void 0&&(!Number.isInteger(n.timeoutSeconds)||n.timeoutSeconds<1||n.timeoutSeconds>21600))throw Error(`timeoutSeconds must be an integer between 1 and 21600`);let r={command:`run`,commandLine:t,cwd:n?.cwd??`.`,...n?.env?.length&&{env:n.env},...n?.timeoutSeconds!==void 0&&{timeoutSeconds:n.timeoutSeconds}};return h(r,e)}}const yt=/^[A-Z0-9_]+$/,bt=4096,xt=65536;function St(e){let t=Object.entries(e);if(t.length>32)throw Error(`too many build settings: got ${t.length}, max 32`);let n=0;for(let[e,r]of t){if(!yt.test(e))throw Error(`invalid build setting key "${e}": keys must match ^[A-Z0-9_]+$`);if(typeof r!=`string`)throw Error(`invalid build setting value for "${e}": value must be a string`);let t=Buffer.byteLength(r,`utf8`);if(t>bt)throw Error(`build setting value for "${e}" is too large: got ${t} bytes, max ${bt} bytes`);if(n+=Buffer.byteLength(e,`utf8`)+t,n>xt)throw Error(`build settings payload is too large: max ${xt} bytes`)}}const Ct=e=>new Promise(t=>setTimeout(t,e)),wt=/failed: (?:502|503|504)\b|\bEOF\b|ECONNRESET|ECONNREFUSED|socket hang up|fetch failed/i;function Tt(e){let t=e instanceof Error?e.message:String(e);return wt.test(t)}async function Et(e,t={}){let n=t.sleep??Ct,r=t.attempts??5,i=t.retryOn??Tt,a;for(let o=1;o<=r;o++)try{return await e()}catch(e){if(!i(e))throw e;if(a=e,o<r){let r=e instanceof Error?e.message:String(e);t.log?.(`Retrying after error (${r.trim()})...`),await n(2e3*o)}}throw a}function Dt(e){if(e===``||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`))throw Error(`invalid sandbox home path from server: ${e}`);let t=e.split(`/`);if(t.some(e=>e===``||e===`.`||e===`..`))throw Error(`invalid sandbox home path from server: ${e}`);return t.join(`/`)}async function Ot(e,t){let r=await J(await n.fetch(`${e}/info`,{method:`GET`,headers:{Authorization:`Bearer ${t}`}}),`GET /info`);if(!r.homeDir)throw Error(`GET /info response is missing homeDir`);return{homeDir:Dt(r.homeDir),...r.xcode?{xcode:r.xcode}:{}}}function kt(e){let t=new URL(e);if(t.protocol===`https:`)t.protocol=`wss:`;else if(t.protocol===`http:`)t.protocol=`ws:`;else throw Error(`Unsupported apiUrl protocol for rbe tunnel: ${t.protocol}`);return t.pathname=`${t.pathname.replace(/\/+$/,``)}/rbe/tunnel`,t.search=``,t.hash=``,t.toString()}var At=class extends c{constructor(e){super(`Remote build execution is not available on this Xcode instance (${e} returned 404). Its limbuild may predate RBE support, or you may be targeting the wrong environment (for example production instead of staging).`),this.name=`RbeUnsupportedError`}},jt=class extends c{constructor(e){super(`Xcode version selection is not available on this sandbox (${e} returned 404): its daemon predates Xcode selection. Create a new sandbox, or omit the Xcode version to build with its default.`),this.name=`XcodeSelectionUnsupportedError`}};function Mt(e,t){return Nt(e,t,e=>new jt(e))}function q(e,t){return Nt(e,t,e=>new At(e))}async function Nt(e,t,n){if(e.status===404)throw await e.text().catch(()=>void 0),n(t);return J(e,t)}async function J(e,t){let n=await e.text();if(!e.ok)throw ie(t,e.status,n,e.headers);if(!n.trim())throw Error(`${t} returned an empty response`);return JSON.parse(n)}var Pt=class extends ot{listBuildLogs(e,t){return this._client.get(z`/v1/xcode_instances/${e}/build_logs`,t)}listBazelBuildLogs(e,t){return this._client.get(z`/v1/xcode_instances/${e}/bazel_build_logs`,t)}create(e,t){if(e.spec?.snapshot!==void 0){let{snapshot:n,cache:r,...i}=e.spec;if(r!==void 0)throw Error(`Use either spec.snapshot or the legacy spec.cache, not both.`);return super.create({...e,spec:{...i,cache:n}},t)}return super.create(e,t)}getSnapshot(e,t){return this.getCache(e,t)._thenUnwrap(G)}bindSnapshotKey(e,t,n){return this.bindCacheKey(e,t,n)._thenUnwrap(G)}followSnapshot(e,t){let n=this._client.apiKey;if(!n)throw Error(`Following disk snapshot status needs an API key on the client`);return mt({baseURL:this._client.baseURL,apiKey:n,instanceId:e},t)}getCache(e,t){return this._client.get(z`/v1/xcode_instances/${e}/cache`,t)}bindCacheKey(e,t,n){return this._client.put(z`/v1/xcode_instances/${e}/cache`,{body:{key:t},...n})}followCache(e,t){let n=this._client.apiKey;if(!n)throw Error(`Following cache status needs an API key on the client`);return dt({baseURL:this._client.baseURL,apiKey:n,instanceId:e},t)}async createClient(e){let t,r;if(`instance`in e){if(!e.instance.status.apiUrl)throw Error(`Instance not ready: apiUrl is not available`);t=e.instance.status.apiUrl,r=H(e.instance)}else t=e.apiUrl,r=e.token;let i=_t(`[XcodeInstance]`,e.logLevel??`info`),a=this._client,o,s=()=>(o??=Ot(t,r),o),c=async e=>{let i,a;if(`status`in e){if(!e.status.apiUrl)throw Error(`Simulator instance not ready: apiUrl is not available`);i=e.status.apiUrl,a=H(e)}else i=e.apiUrl,a=e.token;return J(await n.fetch(`${t}/simulator`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r}`},body:JSON.stringify({apiUrl:i,token:a})}),`POST /simulator`)},l=async e=>{try{return await a.iosInstances.delete(e),!0}catch{return!1}};return{async sync(e,n){let{cacheKey:a,basisCacheDir:o}=ht(e,n?.basisCacheDir),c=n?.additionalFiles&&n.additionalFiles.length>0?await s():void 0,l=n?.additionalFiles?.map(e=>({localPath:e.localPath,remotePath:c&&e.remotePath.startsWith(`~/`)?`${c.homeDir}/${e.remotePath.slice(2)}`:e.remotePath})),u={apiUrl:t,token:r,udid:a,install:n?.install??!0,ignoreFn:await oe(e,{basisCacheDir:o,log:i,xcodeDefaults:!0,...n?.include?{include:n.include}:{},...n?.ignore?{additional:n.ignore}:{}}),basisCacheDir:o,watch:n?.watch??!0,launchMode:`ForegroundIfRunning`,log:i,syncSymlinks:!0,...l?{additionalFiles:l}:{},...n?.onSyncComplete?{onSyncComplete:n.onSyncComplete}:{}},d=await _(e,u),f={};return d.bytesSent!==void 0&&(f.bytesSent=d.bytesSent),d.stopWatching&&(f.stopWatching=d.stopWatching),f},xcodebuild(e,n){if(n?.reactNative?.devServerURL&&e?.configuration===`Release`)throw Error(`reactNative.devServerURL is only supported for Debug builds`);if(e?.onlyTesting?.length&&e?.skipTesting?.length)throw Error(`onlyTesting and skipTesting are mutually exclusive; pass one`);if((e?.onlyTesting?.length||e?.skipTesting?.length)&&e?.action!==`build-for-testing`)throw Error(`onlyTesting/skipTesting require action: 'build-for-testing'`);if(e?.runTests===!1&&e?.action!==`build-for-testing`)throw Error(`runTests: false requires action: 'build-for-testing'`);if(e?.action===`build-for-testing`&&e.sdk!==void 0&&e.sdk!==`iphonesimulator`)throw Error(`action: 'build-for-testing' requires the iphonesimulator sdk`);n?.buildSettings&&St(n.buildSettings);let o={command:`xcodebuild`,...e&&{xcodebuild:e},...n?.xcodegen&&{xcodegen:n.xcodegen},...n?.reactNative&&{reactNative:n.reactNative},...n?.signing&&{signing:n.signing},...n?.cloudSigning&&{cloudSigning:n.cloudSigning},...n?.appstore&&{testflight:n.appstore},...n?.buildSettings&&{buildSettings:n.buildSettings},...n?.env?.length&&{env:n.env},...n?.gitInit!==void 0&&{gitInit:n.gitInit},...n?.logProcessor&&{logProcessor:n.logProcessor},...n?.webhook&&{webhook:n.webhook}},s={apiUrl:t,token:r,log:i,...n?.onXctestEvent&&{onXctestEvent:n.onXctestEvent}};if(n?.upload&&`assetName`in n.upload){let e=K(a.assets,n.upload.assetName,n.upload.ttl,n.upload.uploadOptions).then(e=>(o.signedUploadUrl=e.signedUploadUrl,o.assetId=e.id,o.additionalMetadata={signedDownloadUrl:e.signedDownloadUrl},o));return h(e,s)}return n?.upload&&`signedUploadUrl`in n.upload&&(o.signedUploadUrl=n.upload.signedUploadUrl),h(o,s)},run:vt({apiUrl:t,token:r,log:i}),observeBuildLogs(e,n){return y(e,{apiUrl:t,token:r,log:i,...n})},async getSimulator(){return J(await n.fetch(`${t}/simulator`,{method:`GET`,headers:{Authorization:`Bearer ${r}`}}),`GET /simulator`)},attachSimulator:c,attachNewSimulator:async()=>{let e=await a.iosInstances.create({wait:!0});try{await c(e)}catch(t){throw await l(e.metadata.id),t}return{iosInstanceId:e.metadata.id,simulator:e}},deleteSimulator:l,async getXcode(){return Mt(await n.fetch(`${t}/xcode`,{method:`GET`,headers:{Authorization:`Bearer ${r}`}}),`GET /xcode`)},async setXcode(e){return Mt(await n.fetch(`${t}/xcode`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r}`},body:JSON.stringify({version:e})}),`POST /xcode`)},getInfo:()=>Ot(t,r),async startRbe(e){return q(await n.fetch(`${t}/rbe`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r}`},body:JSON.stringify(e??{})}),`POST /rbe`)},async getRbe(){return q(await n.fetch(`${t}/rbe`,{method:`GET`,headers:{Authorization:`Bearer ${r}`}}),`GET /rbe`)},async stopRbe(){return q(await n.fetch(`${t}/rbe`,{method:`DELETE`,headers:{Authorization:`Bearer ${r}`}}),`DELETE /rbe`)},async startRbeTunnel(n){return te(kt(t),r,n?.host??`127.0.0.1`,n?.port??8980,{mode:`multiplexed`,logLevel:n?.logLevel??e.logLevel??`info`})},async uploadLatestRbeBuild(e){let i,o;if(e.assetName!==void 0){if(!e.assetName)throw Error(`assetName must not be empty`);let t=await K(a.assets,e.assetName,e.ttl);i=t.signedUploadUrl,o=t.signedDownloadUrl}else i=e.signedUploadUrl;return{...await Et(async()=>{let e=await n.fetchLongRequest(`${t}/rbe/upload`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r}`},body:JSON.stringify({signedUploadUrl:i})});if(e.status===404)throw await e.text().catch(()=>void 0),Error(`POST /rbe/upload returned 404: the instance may no longer exist, or its limbuild predates RBE upload support. Recreate the instance and retry.`);return J(e,`POST /rbe/upload`)},{retryOn:e=>Tt(e)||g(e,400)&&/no successful RBE app build/i.test(e.body)}),...o&&{signedDownloadUrl:o}}},async getActiveRbeBuilds(){return q(await n.fetch(`${t}/rbe/builds/active`,{method:`GET`,headers:{Authorization:`Bearer ${r}`}}),`GET /rbe/builds/active`)},async getRecentRbeBuilds(){return q(await n.fetch(`${t}/rbe/builds/recent`,{method:`GET`,headers:{Authorization:`Bearer ${r}`}}),`GET /rbe/builds/recent`)},waitForRbeBuildEnd(e,i){return new Promise((a,o)=>{if(i?.signal?.aborted){o(Error(`waiting for build ${e} was aborted`));return}let s=!1,c=()=>{f.close(),i?.signal?.removeEventListener(`abort`,d)},l=e=>{s||(s=!0,c(),a(e))},u=e=>{s||(s=!0,c(),o(e))},d=()=>u(Error(`waiting for build ${e} was aborted`)),f=p({url:`${t}/exec/${e}/events`,fetch:re(n.fetch,t=>u(Error(`build event stream for ${e} is unreachable: ${t instanceof Error?t.message:t}`))),headers:{Authorization:`Bearer ${r}`},onMessage:t=>{if(t.event!==`end`)return;let n;try{n=JSON.parse(t.data)}catch(t){u(Error(`invalid build end event for ${e}: ${t}`));return}l(n)},onDisconnect:()=>{u(Error(`build event stream for ${e} ended without a terminal event (the build may have finished and its live stream been removed)`))}});i?.signal?.addEventListener(`abort`,d,{once:!0})})}}}};function Ft(e){let t=e.endsWith(`/`)?e.slice(0,-1):e,n=t.split(`/`);return n[n.length-1]===`local.properties`||n.length===1&&(t===`.gradle`||t===`.kotlin`||t===`build`)}var It=class extends B{listBuildLogs(e,t){return this._client.get(z`/v1/gradle_instances/${e}/build_logs`,t)}async createClient(e){let t,n;if(`instance`in e){if(!e.instance.status.apiUrl)throw Error(`Instance not ready: apiUrl is not available`);t=e.instance.status.apiUrl,n=H(e.instance)}else t=e.apiUrl,n=e.token;let r=_t(`[GradleInstance]`,e.logLevel??`info`),i=this._client;return{async sync(e,i){let{cacheKey:a,basisCacheDir:o}=ht(e,i?.basisCacheDir),s=i?.ignore,c={apiUrl:t,token:n,udid:a,install:!1,ignoreFn:await oe(e,{basisCacheDir:o,log:r,xcodeDefaults:!1,nestedGitignore:!0,additional:s?e=>Ft(e)||s(e):Ft,...i?.include?{include:i.include}:{}}),basisCacheDir:o,watch:i?.watch??!1,launchMode:`ForegroundIfRunning`,log:r,syncSymlinks:!0,...i?.additionalFiles&&{additionalFiles:i.additionalFiles},...i?.onSyncComplete&&{onSyncComplete:i.onSyncComplete}},l=await _(e,c),u={};return l.bytesSent!==void 0&&(u.bytesSent=l.bytesSent),l.stopWatching&&(u.stopWatching=l.stopWatching),u},run:vt({apiUrl:t,token:n,log:r}),gradlebuild(e){let a={command:`gradlebuild`,...e?.env?.length&&{env:e.env},...e?.tasks?.length&&{tasks:e.tasks},...e?.projectPath&&{projectPath:e.projectPath},...e?.reactNative&&{reactNative:e.reactNative},...e?.signing&&{signing:e.signing},...e?.webhook&&{webhook:e.webhook},...e?.playstore&&{playstore:e.playstore}};if(e?.upload&&`assetName`in e.upload){let o=K(i.assets,e.upload.assetName,e.upload.ttl).then(e=>(a.signedUploadUrl=e.signedUploadUrl,a.additionalMetadata={signedDownloadUrl:e.signedDownloadUrl},a));return h(o,{apiUrl:t,token:n,log:r})}return e?.upload&&`signedUploadUrl`in e.upload&&(a.signedUploadUrl=e.upload.signedUploadUrl),h(a,{apiUrl:t,token:n,log:r})},observeBuildLogs(e,i){return y(e,{apiUrl:t,token:n,log:r,...i})}}}};B.prototype.listBuildLogs=It.prototype.listBuildLogs,B.prototype.createClient=It.prototype.createClient;const Y=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var X,Z,Q,Lt,$=class{constructor({baseURL:e=Y(`LIMRUN_BASE_URL`),apiKey:t=Y(`LIM_API_KEY`)??null,...n}={}){X.add(this),Q.set(this,void 0),this.androidInstances=new at(this),this.assets=new tt(this),this.iosInstances=new rt(this),this.xcodeInstances=new Pt(this),this.gradleInstances=new B(this),this.analytics=new qe(this),this.scopedTokens=new V(this);let r={apiKey:t,...n,baseURL:e||`https://api.limrun.com`};this.baseURL=r.baseURL,this.timeout=r.timeout??Z.DEFAULT_TIMEOUT,this.logger=r.logger??console;let i=`warn`;this.logLevel=i,this.logLevel=E(r.logLevel,`ClientOptions.logLevel`,this)??E(Y(`LIMRUN_LOG`),`process.env['LIMRUN_LOG']`,this)??i,this.fetchOptions=r.fetchOptions,this.maxRetries=r.maxRetries??2,this.fetch=r.fetch??Oe(),x(this,Q,Me,`f`);let a=Y(`LIMRUN_CUSTOM_HEADERS`);if(a){let e={};for(let t of a.split(`
3
- `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}r.defaultHeaders={...e,...r.defaultHeaders}}this._options=r,this.apiKey=t}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted`)}async authHeaders(e){if(this.apiKey!=null)return R([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ne(e)}getUserAgent(){return`${this.constructor.name}/JS ${w}`}defaultIdempotencyKey(){return`stainless-node-retry-${fe()}`}makeStatusError(e,t,n,r){return i.generate(e,t,n,r)}buildURL(e,t,n){let r=!S(this,X,`m`,Lt).call(this)&&n||this.baseURL,i=me(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!_e(a)||!_e(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let i=await e,a=i.maxRetries??this.maxRetries;t??=a,await this.prepareOptions(i);let{req:o,url:c,timeout:l}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(o,{url:c,options:i});let u=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),d=n===void 0?``:`, retryOf: ${n}`,p=Date.now();if(A(this).debug(`[${u}] sending request`,j({retryOfRequestLogID:n,method:i.method,url:c,options:i,headers:o.headers})),i.signal?.aborted)throw new r;let h=new AbortController,g=await this.fetchWithTimeout(c,o,l,h).catch(s),_=Date.now();if(g instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new r;let a=f(g)||/timed? ?out/i.test(String(g)+(`cause`in g?String(g.cause):``));if(t)return A(this).info(`[${u}] connection ${a?`timed out`:`failed`} - ${e}`),A(this).debug(`[${u}] connection ${a?`timed out`:`failed`} (${e})`,j({retryOfRequestLogID:n,url:c,durationMs:_-p,message:g.message})),this.retryRequest(i,t,n??u);throw A(this).info(`[${u}] connection ${a?`timed out`:`failed`} - error; no more retries left`),A(this).debug(`[${u}] connection ${a?`timed out`:`failed`} (error; no more retries left)`,j({retryOfRequestLogID:n,url:c,durationMs:_-p,message:g.message})),a?new m:new ne({cause:g})}let v=`[${u}${d}] ${o.method} ${c} ${g.ok?`succeeded`:`failed`} with status ${g.status} in ${_-p}ms`;if(!g.ok){let e=await this.shouldRetry(g);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await je(g.body),A(this).info(`${v} - ${e}`),A(this).debug(`[${u}] response error (${e})`,j({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),this.retryRequest(i,t,n??u,g.headers)}let r=e?`error; no more retries left`:`error; not retryable`;A(this).info(`${v} - ${r}`);let a=await g.text().catch(e=>s(e).message),o=be(a),c=o?void 0:a;throw A(this).debug(`[${u}] response error (${r})`,j({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:c,durationMs:Date.now()-p})),this.makeStatusError(g.status,o,c,g.headers)}return A(this).info(v),A(this).debug(`[${u}] response start`,j({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),{response:g,options:i,controller:h,requestLogID:u,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Re(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ae(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ye(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=R([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...De()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&`body`in e?S(this,Q,`f`).call(this,{body:t,headers:R([n])}):{bodyHeaders:void 0,body:void 0};let r=R([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:Ae(t)}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t)}:S(this,Q,`f`).call(this,{body:t,headers:r})}};Z=$,Q=new WeakMap,X=new WeakSet,Lt=function(){return this.baseURL!==`https://api.limrun.com`},$.Limrun=Z,$.DEFAULT_TIMEOUT=3e5,$.LimrunError=c,$.APIError=i,$.APIConnectionError=ne,$.APIConnectionTimeoutError=m,$.APIUserAbortError=r,$.NotFoundError=l,$.ConflictError=t,$.RateLimitError=a,$.BadRequestError=ee,$.AuthenticationError=u,$.InternalServerError=v,$.PermissionDeniedError=d,$.UnprocessableEntityError=o,$.toFile=Ge,$.AndroidInstances=at,$.Assets=tt,$.IosInstances=rt,$.XcodeInstances=Pt,$.GradleInstances=B,$.Analytics=qe,$.ScopedTokens=V,process.platform;const Rt=`agent-device-cli`;function zt(e){return{apiKey:e.apiKey,defaultHeaders:{"x-agent-device-client":Rt,"x-agent-device-version":e.clientVersion}}}function Bt(t,n,r=`This daemon drives an existing Limrun instance with its own token. Set LIMRUN_API_KEY, or ask the instance owner to do this.`){if(t)return t;throw new e(`UNSUPPORTED_OPERATION`,`${n} requires a Limrun API key.`,{hint:r})}export{$ as i,zt as n,Bt as r,Rt as t};
@@ -1 +0,0 @@
1
- const e={control:{retryMaxRetries:3},command:{retryTapMaxAttempts:2,targetLookupTimeoutMs:17e3,optionalTargetLookupTimeoutMs:7e3,scrollUntilVisibleTimeoutMs:2e4,waitForAnimationToEndTimeoutMs:15e3,waitForAnimationToEndDifferencePercent:.005,longPressDurationMs:3e3,swipeDurationMs:400,repeatDelayMs:100,scrollUntilVisibleSpeed:40,scrollUntilVisiblePercentage:100,eraseTextMaxCharacters:50},observation:{pollIntervalMs:200,defaultSettleAttempts:10},targetSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9},screenSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9,centerFraction:.5,downStartFraction:.2,upStartFraction:{android:.5,ios:.9}},scrollUntilVisibleSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9}};function t(e){return Math.trunc(1e3*(100-e)/100)+1}const n={assertVisibleTimeoutMs:e.command.targetLookupTimeoutMs,assertNotVisibleTimeoutMs:e.command.targetLookupTimeoutMs,extendedWaitUntilTimeoutMs:e.command.targetLookupTimeoutMs,runFlowConditionTimeoutMs:e.command.optionalTargetLookupTimeoutMs},r=e.observation.pollIntervalMs*e.observation.defaultSettleAttempts;export{t as i,e as n,r,n as t};
@@ -1 +0,0 @@
1
- import{P as e}from"./sdk-contracts.js";import{l as t}from"./exec.js";import{r as n,t as r}from"./output-path.js";import{l as i}from"./daemon-http.js";import"./command.js";import{i as a,n as o}from"./transport.js";import{createHash as s,randomUUID as c}from"node:crypto";import l from"node:fs";import u from"node:os";import d from"node:path";import{Transform as f,Writable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";async function ee(e,t){let n=l.statSync(e),r=d.basename(e),i=n.isDirectory(),a=re(t)??ne(e,n),o=[];try{let t=i?await te(e,o):e,n=l.statSync(t);return{payloadPath:t,fileName:r,artifactType:i?`app-bundle`:`file`,platform:a,contentType:i?`application/gzip`:`application/octet-stream`,sha256:await ie(t),sizeBytes:n.size,cleanup:()=>h(o)}}catch(e){throw h(o),e}}async function te(e,n){let r=l.mkdtempSync(d.join(u.tmpdir(),`agent-device-upload-${c()}-`));n.push(r);let i=d.join(r,`${d.basename(e)}.tar.gz`);return await t(`tar`,[`czf`,i,`-C`,d.dirname(e),d.basename(e)],{env:{...process.env,COPYFILE_DISABLE:`1`}}),i}function ne(e,t){let n=e.toLowerCase();if(t.isDirectory()&&n.endsWith(`.app`)||n.endsWith(`.ipa`))return`ios`;if(n.endsWith(`.apk`)||n.endsWith(`.aab`))return`android`}function re(e){return e===`ios`||e===`android`?e:void 0}function h(e){for(let t of e)l.rmSync(t,{recursive:!0,force:!0})}async function ie(t){let n=s(`sha256`),r=new p({write(e,t,r){n.update(e),r()}});return await m(l.createReadStream(t),r).catch(t=>{throw new e(`COMMAND_FAILED`,`Failed to read local artifact`,{},t instanceof Error?t:void 0)}),n.digest(`hex`)}function g(e){let{stage:t,fileName:n,startOffset:r,totalBytes:i,onProgress:a}=e,o=r,s=y(i),c=Math.min(i,r+s);return new f({transform(e,r,l){o=Math.min(i,o+e.byteLength),o>=c&&(a?.({type:`progress`,stage:t,fileName:n,transferredBytes:o,totalBytes:i}),c=Math.min(i,o+s)),l(null,e)}})}function _(){if(!(process.stderr.isTTY!==!0||process.env.CI))return e=>{process.stderr.write(`${v(e)}\n`)}}function v(e){switch(e.type){case`start`:return`Uploading ${e.fileName} (${x(e.totalBytes)}) via ${b(e.stage)} upload`;case`resume`:return`Resuming ${e.fileName} at ${x(e.transferredBytes)} of ${x(e.totalBytes)}`;case`progress`:return`Uploaded ${x(e.transferredBytes)} of ${x(e.totalBytes)} (${ae(e.transferredBytes,e.totalBytes)})`;case`fallback`:return`Direct upload did not complete; retrying ${e.fileName} with ${b(e.to)} upload`}}function y(e){return Math.max(8388608,Math.ceil(e*.05))}function b(e){return e===`direct`?`direct`:`legacy`}function ae(e,t){return t<=0?`100%`:`${Math.min(100,Math.floor(e/t*100))}%`}function x(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KiB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MiB`:`${(n/1024).toFixed(1)} GiB`}const S=3e5,C=`uploadStreamRetryable`;async function w(e){return await E({...e,url:e.url,redirectCount:0,startOffset:0})}function T(t){return t instanceof e&&t.details?.[C]===!0}async function E(t){let n=await o(t.url.protocol),r=l.statSync(t.payloadPath).size,i=se(t.headers,t.startOffset,r);return oe(t.progress,t.startOffset,r),await new Promise((o,s)=>{let c=!1,u=n.request({protocol:t.url.protocol,host:t.url.hostname,port:t.url.port,method:t.method,path:t.url.pathname+t.url.search,headers:i,...t.signal?{signal:t.signal}:{}},n=>{c=!0,a(n).then(i=>{clearTimeout(f);let a=n.statusCode??500,c=n.headers.location;if(c&&ce(a)){if(t.redirectCount>=5){s(new e(`COMMAND_FAILED`,`Artifact upload exceeded redirect limit`,{maxRedirects:5,url:t.url.toString()}));return}let n=new URL(c,t.url);E({...t,url:n,redirectCount:t.redirectCount+1}).then(o,s);return}let l=le(a)?O(n.headers,r):void 0;if(l!==void 0){if(l>=r){o({statusCode:200,statusMessage:`Upload already complete`,body:``});return}if(l<=t.startOffset){s(new e(`COMMAND_FAILED`,`Artifact upload resume did not advance`,{offset:l,previousOffset:t.startOffset,url:t.url.toString()}));return}E({...t,startOffset:l}).then(o,s);return}o({statusCode:a,statusMessage:n.statusMessage,body:i})}).catch(s)}),f=setTimeout(()=>{u.destroy(),s(new e(`COMMAND_FAILED`,t.timeoutMessage,{timeoutMs:S,...t.timeoutHint?{hint:t.timeoutHint}:{},...D(t)}))},S);u.on(`error`,n=>{if(!c){if(clearTimeout(f),t.signal?.aborted){s(t.signal.reason);return}s(new e(`COMMAND_FAILED`,t.errorMessage,{...t.errorHint?{hint:t.errorHint}:{},...D(t)},n))}}),u.on(`close`,()=>clearTimeout(f)),m(l.createReadStream(t.payloadPath,{start:t.startOffset}),g({stage:t.progress?.stage??`legacy`,fileName:t.progress?.fileName??d.basename(t.payloadPath),startOffset:t.startOffset,totalBytes:r,onProgress:t.progress?.onProgress}),u).catch(t=>{if(c)return;u.destroy();let n=t instanceof Error?t:Error(String(t));s(new e(`COMMAND_FAILED`,`Failed to read local artifact`,{},n))})})}function D(e){return e.retryable===!0?{[C]:!0}:{}}function oe(e,t,n){e?.onProgress?.({type:t>0?`resume`:`start`,stage:e.stage,fileName:e.fileName,transferredBytes:t,totalBytes:n})}function se(e,t,n){return t<=0?e:{...e,"content-length":Math.max(n-t,0),"content-range":`bytes ${t}-${n-1}/${n}`}}function ce(e){return[301,302,303,307,308].includes(e)}function le(e){return e===308}function O(e,t){let n=k(e[`x-upload-offset`]??e[`upload-offset`]);if(n!==void 0)return Math.min(n,t);let r=A(e.range)?.match(/^bytes=0-(\d+)$/);if(!r)return;let i=Number(r[1]);if(!(!Number.isSafeInteger(i)||i<0))return Math.min(i+1,t)}function k(e){let t=A(e);if(t===void 0)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function A(e){return Array.isArray(e)?e[0]:e}const j=3e4;async function M(e){let t=await ee(e.localPath,e.platform),n=e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`,r=c();try{let i=await L({normalizedBase:n,token:e.token,artifact:t,uploadAttemptId:r,signal:e.signal});return i?.kind===`cache-hit`?i.uploadId:i?.kind===`direct-upload`?await N({normalizedBase:n,token:e.token,artifact:t,preflight:i,uploadAttemptId:r,onProgress:e.onProgress,signal:e.signal})||(e.onProgress?.({type:`fallback`,from:`direct`,to:`legacy`,fileName:t.fileName}),await I({normalizedBase:n,token:e.token,artifact:t,onProgress:e.onProgress,signal:e.signal})):await I({normalizedBase:n,token:e.token,artifact:t,onProgress:e.onProgress,signal:e.signal})}finally{t.cleanup()}}async function N(e){let t=async t=>(await V(e.artifact,t,e.onProgress,e.signal),await H({normalizedBase:e.normalizedBase,token:e.token,uploadId:t.uploadId,signal:e.signal}));try{return await t(e.preflight)}catch(n){if(e.signal?.aborted)throw n;return F(n)?await P(e,t):void 0}}async function P(e,t){let n=await L({normalizedBase:e.normalizedBase,token:e.token,artifact:e.artifact,uploadAttemptId:e.uploadAttemptId,signal:e.signal});if(n?.kind===`cache-hit`)return n.uploadId;if(n?.kind===`direct-upload`)try{return await t(n)}catch{return}}function F(t){return t instanceof e?T(t):!0}async function I(t){let{normalizedBase:n,token:r,artifact:a}=t,o=new URL(`upload`,n),s={"content-type":a.contentType,"x-artifact-type":a.artifactType,"x-artifact-filename":a.fileName,"x-artifact-hash":a.sha256,"x-artifact-hash-algorithm":`sha256`,"transfer-encoding":`chunked`};Object.assign(s,i(r));let c=await w({url:o,method:`POST`,headers:s,payloadPath:a.payloadPath,timeoutMessage:`Artifact upload timed out`,timeoutHint:`The upload to the remote daemon exceeded the 5-minute timeout.`,errorMessage:`Failed to upload artifact to remote daemon`,errorHint:`Verify the remote daemon is reachable and supports artifact uploads.`,signal:t.signal,progress:{stage:`legacy`,fileName:a.fileName,onProgress:t.onProgress}});try{let t=JSON.parse(c.body);if(!t.ok||!t.uploadId)throw new e(`COMMAND_FAILED`,`Upload failed: ${c.body}`);return t.uploadId}catch(t){throw t instanceof e?t:new e(`COMMAND_FAILED`,`Invalid upload response: ${c.body}`)}}async function L(e){let t=new URL(`upload/preflight`,e.normalizedBase),n={"content-type":`application/json`};Object.assign(n,i(e.token));let r=await fetch(t,{method:`POST`,headers:n,signal:R(e.signal,j),body:JSON.stringify({uploadAttemptId:e.uploadAttemptId,sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(t=>{if(e.signal?.aborted)throw t});if(r?.ok)return z(await r.json().catch(()=>void 0))}function R(e,t){let n=AbortSignal.timeout(t);return e?AbortSignal.any([e,n]):n}function z(e){if(!e||typeof e!=`object`)return;let t=e;if(t.ok!==!0||typeof t.uploadId!=`string`)return;if(t.cacheHit===!0)return{kind:`cache-hit`,uploadId:t.uploadId};let n=t.upload;if(!n||typeof n.url!=`string`)return;let r=n.headers??{};if(B(r))return{kind:`direct-upload`,uploadId:t.uploadId,url:n.url,headers:r}}function B(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}async function V(t,n,r,i){let a=await w({url:new URL(n.url),method:`PUT`,headers:n.headers,payloadPath:t.payloadPath,timeoutMessage:`Direct artifact upload timed out`,timeoutHint:`The direct upload ticket did not accept the artifact within the timeout.`,errorMessage:`Failed to upload artifact with direct upload ticket`,retryable:!0,signal:i,progress:{stage:`direct`,fileName:t.fileName,onProgress:r}});if(a.statusCode<200||a.statusCode>=300)throw new e(`COMMAND_FAILED`,`Direct artifact upload failed`,{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function H(t){let n=new URL(`upload/finalize`,t.normalizedBase),r={"content-type":`application/json`};Object.assign(r,i(t.token));let a=await fetch(n,{method:`POST`,headers:r,signal:R(t.signal,j),body:JSON.stringify({uploadId:t.uploadId})}).catch(n=>{throw t.signal?.aborted?n:new e(`COMMAND_FAILED`,`Failed to finalize direct artifact upload`,{},n)});if(!a.ok)throw new e(`COMMAND_FAILED`,`Direct artifact upload finalize failed`,{status:a.status,statusText:a.statusText});let o=await a.json().catch(()=>void 0);if(!o?.ok||!o.uploadId)throw new e(`COMMAND_FAILED`,`Invalid upload finalize response`);return o.uploadId}async function U(e,t,n){let r=[...e.positionals??[]],i=e.flags?{...e.flags}:void 0,a=e.meta?.installSource,o={},s,c=_();if(!we(t))return K({positionals:r,flags:i,installSource:a,uploadedArtifactId:s,clientArtifactPaths:o});W(e),i=G(e,r,i,o);let l=await pe(e,t,c,n);return l&&(a=l.installSource,s=l.uploadedArtifactId??s),e.command!==`install`&&e.command!==`reinstall`||(s=await ue(e,t,r,c,n)??s),K({positionals:r,flags:i,installSource:a,uploadedArtifactId:s,clientArtifactPaths:o})}function W(t){if(t.flags?.saveScript!==void 0)throw new e(`INVALID_ARGS`,`--save-script is not supported against a remote daemon: the healed script would be written on the daemon host, not on this machine.`,{hint:`Run the script against a local daemon to capture a healed .ad, or re-run without --save-script.`,command:t.command})}async function ue(e,t,n,r,i){let a=n.length===1?0:1,o=n[a];if(o===void 0)return;if(o.startsWith(`remote:`)){n[a]=o.slice(7);return}let s=fe(o,e.meta?.cwd);if(s)return await M({localPath:s,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform,onProgress:r,signal:i})}function G(e,t,n,r){let i=me(e,t);if(!i)return n;i.positionalIndex!==void 0&&i.positionalPath!==void 0&&(t[i.positionalIndex]=i.positionalPath);let a=de(n,i.flagKey??`out`,i.flagPath);return r[i.field]=i.localPath,a}function de(e,t,n){return n===void 0?e:{...e??{},[t]:n}}function fe(e,t){let n=d.isAbsolute(e)?e:d.resolve(t??process.cwd(),e);return l.existsSync(n)?n:void 0}function K(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function pe(e,t,n,r){let i=e.meta?.installSource;if(e.command!==`install_source`||!i||i.kind!==`path`)return null;let a=i.path.trim();if(!a)return{installSource:i};if(a.startsWith(`remote:`))return{installSource:{...i,path:a.slice(7)}};let o=d.isAbsolute(a)?a:d.resolve(e.meta?.cwd??process.cwd(),a);if(!l.existsSync(o))return{installSource:{...i,path:o}};let s=await M({localPath:o,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform,onProgress:n,signal:r});return{installSource:{...i,path:o},uploadedArtifactId:s}}function me(e,t){if(e.command===`screenshot`){let n=J(e,`path`,`.png`);return t[0]?{field:`path`,localPath:n,positionalIndex:0,positionalPath:Q(`screenshot`,`.png`)}:{field:`path`,localPath:n,positionalIndex:0,flagPath:Q(`screenshot`,`.png`)}}if(e.command===`record`&&(t[0]??``).toLowerCase()===`start`){if(!ge(e)&&e.flags?.platform===void 0)return null;let t=q(e),n=_e(J(e,`outPath`,t,1),e);return{field:`outPath`,localPath:n,positionalIndex:1,positionalPath:Q(`recording`,d.extname(n)||t)}}return e.command===`test`?{field:`artifactsDir`,localPath:he(e),flagKey:`artifactsDir`,flagPath:ve(`test-artifacts`)}:null}function he(e){let t=e.flags?.artifactsDir;return Y(X(t)?t:`.agent-device/test-artifacts`,e.meta?.cwd)}function q(e){return n(e.flags?.platform)}function ge(e){return X(e.positionals?.[1])||X(e.flags?.out)}function _e(e,t){return t.flags?.platform===`web`?r(e,q(t)):e}function J(e,t,n,r=0){let i=e.positionals?.[r]??e.flags?.out,a=`${t===`path`?`screenshot`:`recording`}-${Date.now()}${n}`;return Y(X(i)?i:a,e.meta?.cwd)}function Y(e,t){return d.isAbsolute(e)?e:d.resolve(t??process.cwd(),e)}function X(e){return typeof e==`string`&&e.trim().length>0}const Z=`/tmp`;function Q(e,t){let n=t.startsWith(`.`)?t:`.${t}`;return d.posix.join(Z,`${$(e)}${n}`)}function ve(e){return d.posix.join(Z,$(e))}function ye(e,t,n){let r=d.posix.basename(e,n);return e===d.posix.join(Z,`${r}${n}`)&&r.startsWith(`agent-device-${t}-`)&&/^\d+-[a-z0-9]+$/.test(r.slice(`agent-device-${t}-`.length))}function $(e){return`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}async function be(e,t,n){let r=Array.isArray(n.data?.artifacts)?n.data.artifacts:[];if(r.length===0||!e.baseUrl)return n;let i=n.data?{...n.data}:{},a=[];for(let n of r){if(!n||typeof n!=`object`||typeof n.artifactId!=`string`){a.push(n);continue}let r=xe(n,t),o=await Se({baseUrl:e.baseUrl,token:e.token,artifactId:n.artifactId,destinationPath:r,requestScope:t.meta,isDirectory:n.artifactType===`test-artifacts`});i[n.field]=o,a.push({...n,localPath:o})}return i.artifacts=a,{ok:!0,data:i}}function xe(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let n=t.meta?.clientArtifactPaths?.[e.field];if(n&&n.trim().length>0)return n;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return d.resolve(t.meta?.cwd??process.cwd(),r)}async function Se(e){let{downloadRemoteArtifactFromUrl:t}=await import(`./artifact-download.js`);return await t({artifactUrl:new URL(Ce(e.baseUrl,e.artifactId)),token:e.token,artifactId:e.artifactId,destinationPath:e.destinationPath,requestScope:e.requestScope,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.isDirectory===void 0?{}:{isDirectory:e.isDirectory}})}function Ce(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(`artifacts/${encodeURIComponent(t)}`,n).toString()}function we(e){return typeof e.baseUrl==`string`&&e.baseUrl.length>0}export{be as n,U as r,ye as t};
@@ -1 +0,0 @@
1
- import{I as e,P as t,Y as n,at as r,rt as i}from"./sdk-contracts.js";import{n as a,r as o}from"./diagnostics.js";import"./diagnostics2.js";import{d as s,m as c,o as l}from"./lease-scope.js";import{T as u}from"./sdk-batch.js";import{n as d}from"./catalog.js";import{r as f}from"./owner-identity.js";import{d as p,f as m,l as h,n as g,s as _}from"./daemon-http.js";import{n as v}from"./daemon-artifacts.js";import{i as ee,n as y,t as b}from"./transport.js";import{n as x,o as te,t as ne}from"./request-progress-protocol.js";import{t as re}from"./session-artifact-paths.js";import"./process.js";import{a as ie}from"./version.js";import{t as ae}from"./daemon-resolution.js";import S from"node:fs";import oe from"node:path";import C from"node:net";function w(e,n,r){return new t(`COMMAND_FAILED`,`Invalid daemon response`,{requestId:e.meta?.requestId,line:n},r instanceof Error?r:void 0)}function T(e){let t=t=>(e.onError(t),!0);return{handleLine(n){let r;try{r=JSON.parse(n)}catch(r){return t(w(e.req,n,r))}if(ne(r))try{return e.onProgress?.(r.event),!1}catch(e){return t(e)}return x(r)?(e.onResponse(r.response),!0):e.responseFormat===`socket-legacy`?(e.onResponse(r),!0):t(w(e.req,n,Error(`Missing daemon progress response envelope`)))}}}function se(e,t){return te(e)&&String(Array.isArray(t)?t.join(`,`):t??``).includes(`application/x-ndjson`)}function ce(e,t){let{req:n,isSettled:r,resolve:i,reject:a,clearTimeout:o}=t,s=``,c=T({req:n,onProgress:t.onProgress,responseFormat:`socket-legacy`,onResponse(t){o(),i(t),e.end()},onError(e){o(),a(e)}});e.setEncoding(`utf8`),e.on(`data`,e=>{if(r())return;let t=b(s,e);s=t.buffer;for(let e of t.lines)if(c.handleLine(e))return}),e.on(`end`,()=>{if(r())return;let e=s.trim();e&&c.handleLine(e)||(o(),a(w(n,e)))})}function le(e,n){let{req:r,handleResponseBody:i,reject:a,clearTimeout:o}=n,s=``,c=!1,l=T({req:r,onProgress:n.onProgress,responseFormat:`ndjson-envelope`,onResponse(e){c=!0,o(),i(JSON.stringify(e))},onError(e){c=!0,o(),a(e)}});e.setEncoding(`utf8`),e.on(`data`,e=>{if(c)return;let t=b(s,e);s=t.buffer;for(let e of t.lines)if(e&&l.handleLine(e))return}),e.on(`end`,()=>{if(c)return;let e=s.trim();e&&l.handleLine(e)||(c=!0,o(),a(w(r,e)))}),e.on(`error`,e=>{c||(c=!0,o(),a(new t(`COMMAND_FAILED`,`Failed to read daemon response`,{requestId:r.meta?.requestId},e instanceof Error?e:void 0)))})}const E=1e4,D=8388608;function ue(e,t){return m(e,`sessions/${encodeURIComponent(t.session)}/requests/${encodeURIComponent(t.requestId)}/diagnostics`)}function de(e){let{logPath:t,...n}=e;return n}async function fe(e,t){let n=de(e),r=e.diagnosticsRecord,i=r?.requestId??t.requestId;if(!r)return O(n,t.endpoint,i,`the daemon named no diagnostics record`);try{let e=re(t.stateDir,r),a=await pe({endpoint:t.endpoint,ref:r,destinationPath:e});return a?O(n,t.endpoint,i,a):{...n,logPath:e}}catch(e){return O(n,t.endpoint,i,e instanceof Error?e.message:String(e))}}function O(e,t,n,r){return{...e,logPathUnavailable:`remote daemon ${t.baseUrl}, request ${n??`unknown`}: ${r}`}}async function pe(e){let{endpoint:t,ref:n,destinationPath:r}=e,i;try{i=new URL(ue(t.baseUrl,n))}catch{return`daemon base URL is not a valid URL`}try{let e=await y(i.protocol);return await S.promises.mkdir(oe.dirname(r),{recursive:!0}),await new Promise(n=>{let a=!1,o=e=>{if(!a){if(a=!0,clearTimeout(c),e===void 0){n(void 0);return}S.promises.rm(r,{force:!0}).finally(()=>{n(e)})}},s=e.request({protocol:i.protocol,host:i.hostname,port:i.port,method:`GET`,path:i.pathname+i.search,headers:{...h(t.token),...p(t.tenantId)}},e=>{let t=e.statusCode??500;if(t!==200){e.resume(),o(`HTTP ${t}`);return}let n=S.createWriteStream(r),i=0;e.on(`data`,e=>{i+=e.length,i>D&&(s.destroy(),n.destroy(),o(`record exceeds ${D} bytes`))}),e.on(`error`,e=>{n.destroy(),o(e.message)}),n.on(`error`,e=>{o(e.message)}),n.on(`finish`,()=>{o(void 0)}),e.pipe(n)}),c=setTimeout(()=>{o(`fetch timed out after ${E}ms`),s.destroy()},E);s.on(`error`,e=>{o(e.message)}),s.end()})}catch(e){return e instanceof Error?e.message:String(e)}}function k(e,n){let{info:r,req:i,stateDir:a,resolve:o,reject:s}=n;try{let n=me(e);if(n.error){he(n.error,{info:r,req:i,stateDir:a,reject:s});return}if(!n.result||typeof n.result!=`object`){s(new t(`COMMAND_FAILED`,`Invalid daemon RPC response`,{requestId:i.meta?.requestId}));return}ve(r,i,n.result,o,s)}catch(n){s(new t(`COMMAND_FAILED`,`Invalid daemon response`,{requestId:i.meta?.requestId,line:e},n instanceof Error?n:void 0))}}function me(e){return JSON.parse(e)}async function he(e,t){let{info:n,req:r,stateDir:i,reject:a}=t,o=r.meta?.requestId,s=ge(e);if(!n.baseUrl){a(A(s,o));return}a(A(await fe(s,{endpoint:{baseUrl:n.baseUrl,token:n.token,tenantId:r.meta?.tenantId},stateDir:i,requestId:o}),o))}function ge(e){let t=e.data??{},r=_e(t.cause);return{code:i(t.code==null?void 0:String(t.code),`COMMAND_FAILED`),message:String(t.message??e.message??`Daemon RPC request failed`),cause:r,details:typeof t.details==`object`&&t.details?t.details:void 0,hint:typeof t.hint==`string`?t.hint:void 0,diagnosticId:typeof t.diagnosticId==`string`?t.diagnosticId:void 0,logPath:typeof t.logPath==`string`?t.logPath:void 0,diagnosticsRecord:n(t.diagnosticsRecord),retriable:typeof t.retriable==`boolean`?t.retriable:void 0,supportedOn:typeof t.supportedOn==`string`?t.supportedOn:void 0}}function _e(e){return r(e)}function A(e,n){return new t(i(e.code,`COMMAND_FAILED`),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath,logPathUnavailable:e.logPathUnavailable,diagnosticsRecord:e.diagnosticsRecord,retriable:e.retriable,supportedOn:e.supportedOn,requestId:n},e.cause)}async function ve(e,t,n,r,i){try{r(e.baseUrl&&n.ok?await v(e,t,n):n)}catch(e){i(e)}}function ye(e,t){let n=e.meta?.requestId??a();return be(e.command)?{jsonrpc:`2.0`,id:n,method:xe(e.command),params:{...Se(e,e.command,t),...e.command===`lease_allocate`?c(e.flags):{},...e.command===`lease_allocate`&&e.meta?.providerCredentialFingerprint?{providerCredentialFingerprint:e.meta.providerCredentialFingerprint}:{}}}:{jsonrpc:`2.0`,id:n,method:`agent_device.command`,params:e}}function be(e){return e===`lease_allocate`||e===`lease_heartbeat`||e===`lease_release`}function xe(e){switch(e){case`lease_allocate`:return`agent_device.lease.allocate`;case`lease_heartbeat`:return`agent_device.lease.heartbeat`;case`lease_release`:return`agent_device.lease.release`}}function Se(e,t,n){return s(l(e),t,{includeTokenParam:n.includeTokenParam,token:e.token,session:e.session})}async function Ce(e){let{info:n,statePaths:r,remote:i,timeoutMs:a,requestId:s,command:c,platform:l,session:u,action:d}=e,f=!i&&we(c)?await(await import(`./daemon-client-liveness-probe.js`)).probeDaemonResponsive(n,{session:u}):void 0,p=f===!1,m;if(p){let{stopAndRetireDaemon:e}=await import(`./daemon-registration-owner.js`).then(e=>e.r);m=await e({paths:r,observed:{pid:n.pid,startTime:n.processStartTime??null},mode:`force`})}let h=m?.status===`retired`,g=m?.status===`retained`&&m.termination?.status!==`exited`;return o({level:`error`,phase:`daemon_request_timeout`,data:{timeoutMs:a,requestId:s,command:c,daemonPidReset:h?n.pid:void 0,daemonPidForceKilled:h?Oe(m):void 0,daemonRetirement:m,daemonPreservedAfterTimeout:g||!i&&!p,daemonLivenessProbeAnswered:f,daemonBaseUrl:n.baseUrl}}),new t(`COMMAND_FAILED`,`Daemon request timed out`,{timeoutMs:a,requestId:s,reason:`daemon_transport_timeout`,...m?{retirement:m,stateDir:r.baseDir}:{},hint:m?.status===`retained`?`The daemon could not be safely retired. State was retained at ${r.baseDir}. ${m.error?.hint??`Retry with --debug and inspect daemon diagnostics before retrying.`}`:De({remote:i,resetDaemon:h,command:c,applePlatformDeclared:Ee(l),session:u,action:d})})}function we(e){return u(e).onTimeout===`reset-daemon`}const Te=new Set([`apple`,`ios`,`macos`]);function Ee(e){return e!==void 0&&Te.has(e)}function De(e){let{remote:t,resetDaemon:n,command:r,applePlatformDeclared:i,session:a,action:o}=e;if(!n&&r===d.record&&o===`stop`)return`The ${t?`remote `:``}daemon may still be exporting the recording. Run agent-device record stop${a?` --session ${a}`:``} again to wait for that export and receive the completed recording.`;if(t)return`Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.`;if(n)return`Retry with --debug and check daemon diagnostics logs. The daemon did not answer the liveness probe and was reset after the timeout.`;let s=i&&r===d.snapshot?` If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.`:``;return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??`request`} request was canceled; the daemon was kept alive so the session can still be closed or inspected.${s}`}function Oe(e){if(!e||e.status===`absent`)return!1;let t=e.termination;return t?.status===`exited`&&t.mode===`forced`}function ke(e){let t=Ie(e);if(!t||typeof t!=`object`)return null;let n=t,r=Ae(n);if(!r)return null;let i=je(n);return i?{token:r,...i,transport:Ne(n.transport),pid:f(n.pid)?n.pid:0,version:j(n.version),codeOrigin:Me(n.codeOrigin),codeSignature:j(n.codeSignature),processStartTime:j(n.processStartTime),policyDigest:j(n.policyDigest)}:null}function Ae(e){return typeof e.token==`string`&&e.token.length>0?e.token:null}function je(e){let t=M(e.port),n=M(e.httpPort);return t===void 0&&n===void 0?null:{port:t,httpPort:n}}function Me(e){return e===`installed`||e===`checkout`?e:void 0}function Ne(e){return e===`socket`||e===`http`||e===`dual`?e:void 0}function j(e){return typeof e==`string`?e:void 0}function M(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function Pe(e){return{hasInfo:S.existsSync(e.infoPath),hasLock:S.existsSync(e.lockPath)}}function N(e){return typeof e.baseUrl==`string`&&e.baseUrl.length>0}function Fe(e,t=ae(process.env.AGENT_DEVICE_STATE_DIR)){let n=[e.hasInfo?t.infoPath:null,e.hasLock?t.lockPath:null].filter(Boolean).join(` and `);return`Daemon startup did not establish a reachable owner. ${n?`State was retained at ${n}. `:``}Retry with --debug and inspect daemon diagnostics. Before upgrading, stop all older clients and daemons with their original CLI and prevent them from returning to this state directory. Unverified lock state requires confirming every user stopped before manual recovery; deleting metadata alone is not a safe reset.`}function Ie(e){if(!S.existsSync(e))return null;try{return JSON.parse(S.readFileSync(e,`utf8`))}catch{return null}}function P(t,n,r){return e({requestId:r,dispatched:n},t.reason)}function F(e,t){if(e?.aborted)throw P(e,`no`,t)}const Le={refuseIfAborted:()=>{},guard:async e=>await e()};function Re(e){let{signal:t,requestId:n}=e;return t?{refuseIfAborted(){if(t.aborted)throw P(t,`no`,n)},guard:async e=>{if(t.aborted)throw P(t,`no`,n);return await new Promise((r,i)=>{let a=()=>i(P(t,`unknown`,n));t.addEventListener(`abort`,a,{once:!0}),e().then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})})}}:Le}const I=3e3,L=`daemon_endpoint_unavailable`;function ze(e){return e instanceof t&&e.code===`COMMAND_FAILED`&&e.details?.reason===L}function R(e){return new t(`COMMAND_FAILED`,e===`http`?`Daemon HTTP endpoint is unavailable`:`Daemon socket endpoint is unavailable`,{reason:L,transport:e})}async function Be(e,t,n){let r=Date.now()+(n??1/0),i=q(e,t),a=Y(e,t,i);return await z(e,i,(r-Date.now())/(a?2:1))?Date.now()<r:a?await z(e,a,r-Date.now())&&Date.now()<r:!1}async function z(e,t,n){return t===`http`?await He(e,n):await Ve(e.port,n)}function Ve(e,t=500){return!e||t<=0?Promise.resolve(!1):new Promise(n=>{let r=!1,i=C.createConnection({host:`127.0.0.1`,port:e},()=>{a(!0)}),a=e=>{r||(r=!0,i.destroy(),n(e))};i.setTimeout(Math.min(500,Math.ceil(t))),i.on(`timeout`,()=>{a(!1)}),i.on(`error`,()=>{a(!1)})})}function He(e,t){return V(e,t).then(e=>e.reachable)}async function B(e,n,r){let i=await V(e,n,r);if(!e.baseUrl||!i.reachable)return i;let a=[i,i.upstream].find(e=>typeof e?.rpcProtocolVersion==`number`&&e.rpcProtocolVersion!==2);if(a)throw new t(`COMMAND_FAILED`,`Remote daemon RPC protocol is incompatible`,{daemonBaseUrl:e.baseUrl,clientVersion:ie(),remoteVersion:a.version,remoteService:a.service,supportedRpcProtocolVersion:2,remoteRpcProtocolVersion:a.rpcProtocolVersion,hint:`Upgrade agent-device on the client or remote host so both support the same daemon RPC protocol.`});return i}function Ue(e){return e.baseUrl?m(e.baseUrl,`health`):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null}async function V(e,t,n){let r=Ue(e);if(!r)return{reachable:!1};let i=new URL(r),a=Math.min(e.baseUrl?I:500,t??1/0);if(a<=0)return{reachable:!1,timedOut:!0};let o=performance.now()+a,s=AbortSignal.timeout(Math.ceil(a)),c=n?AbortSignal.any([s,n]):s,l=await Promise.race([y(i.protocol),new Promise(e=>{c.addEventListener(`abort`,()=>e(null),{once:!0})})]),u=()=>We(s,o);return!l||H(c,o)?u():await new Promise(t=>{let n=e.baseUrl?h(e.token):{},r=l.request({protocol:i.protocol,host:i.hostname,port:i.port,path:i.pathname+i.search,method:`GET`,timeout:a,signal:c,headers:n},e=>{let n=``;e.setEncoding(`utf8`),e.on(`data`,e=>{n+=e}),e.on(`end`,()=>{let r=e.statusCode??500;t(H(s,o)?{reachable:!1,timedOut:!0}:{reachable:r<500,statusCode:r,...Ge(n)})}),e.on(`error`,()=>t(u())),e.on(`aborted`,()=>t(u()))});r.on(`timeout`,()=>{r.destroy(),t({reachable:!1,timedOut:!0})}),r.on(`error`,()=>{t(u())}),r.end()})}function We(e,t){return H(e,t)?{reachable:!1,timedOut:!0}:{reachable:!1}}function H(e,t){return e.aborted||performance.now()>=t}function Ge(e){try{let t=JSON.parse(e),n=t.upstream&&typeof t.upstream==`object`?U(t.upstream):void 0;return{...U(t),...n?{upstream:n}:{}}}catch{return{}}}function U(e){return{service:typeof e.service==`string`?e.service:void 0,version:typeof e.version==`string`?e.version:void 0,rpcProtocolVersion:typeof e.rpcProtocolVersion==`number`?e.rpcProtocolVersion:void 0,...typeof e.instanceId==`string`?{instanceId:e.instanceId}:{},...typeof e.hostArch==`string`?{hostArch:e.hostArch}:{}}}async function Ke(e,n,r,i,a,o={}){try{return await qe(e,n,r,i,a,o)}catch(r){if(!(r instanceof t)||r.details?.reason!==`daemon_transport_timeout`)throw r;let a=r.details.timeoutMs;throw typeof a==`number`?await Ce({info:e,statePaths:i,...$e(n,N(e),a)}):r}}async function qe(e,t,n,r,i,a={}){let o=q(e,n),s=typeof i==`number`?performance.now()+i:void 0;F(a.signal,t.meta?.requestId);try{return await K(e,t,r,i,o,a)}catch(c){if(e.baseUrl&&Ye(c))return await Je(e,t,r,i,s,o,a);G(c)&&$(e);let l=Y(e,n,o);if(!l||!Xe(c,o))throw c;return await K(e,t,r,i,l,a)}}async function Je(e,n,r,i,a,o,s){$(e);let c=W(n,i,a),l=await B(e,c,s.signal);F(s.signal,n.meta?.requestId);let u=W(n,i,a,l.timedOut?c:void 0);if(!l.reachable)throw new t(`COMMAND_FAILED`,`Remote daemon is unavailable`,{daemonBaseUrl:e.baseUrl});e.remoteInstanceId=l.instanceId,e.remoteUpstreamInstanceId=l.upstream?.instanceId,it(e,l);try{return await K(e,n,r,u,o,s)}catch(t){throw G(t)&&$(e),t}}function W(e,t,n,r){if(n===void 0||t===void 0)return;let i=n-performance.now();if(i>0&&(r===void 0||r>I))return i;throw Z(t,e.meta?.requestId)}function Ye(e){return e instanceof t&&e.details?.reason===`remote_instance_mismatch`}function G(e){return e instanceof t&&(e.details?.reason===`daemon_transport_failure`||e.details?.reason===`daemon_transport_timeout`||e.details?.reason===`daemon_response_read_failure`)}async function K(e,t,n,r,i,a){return i===`http`?await nt(e,t,n,r,a):await Qe(e,t,r,a)}function q(e,n){if(e.baseUrl){if(n===`socket`)throw new t(`COMMAND_FAILED`,`Remote daemon endpoint only supports HTTP transport`,{daemonBaseUrl:e.baseUrl});return`http`}if(n===`http`||n===`socket`)return Ze(e,n);let r=(e.transport===`socket`||e.transport===`dual`?[`socket`,`http`]:[`http`,`socket`]).find(t=>J(e,t));if(r)return r;throw new t(`COMMAND_FAILED`,`Daemon metadata has no reachable transport`)}function J(e,t){return t===`http`?!!e.httpPort:!!e.port}function Y(e,t,n){if(t!==`auto`||e.baseUrl)return null;let r=n===`socket`?`http`:`socket`;return J(e,r)?r:null}function Xe(e,n){return n===`socket`&&e instanceof t&&e.code===`COMMAND_FAILED`&&e.message===`Failed to communicate with daemon`&&e.details?.daemonSocketRequestWritten===!1}function Ze(e,t){if(J(e,t))return t;throw R(t)}function X(e,n,r,i={}){return o({level:`error`,phase:`daemon_request_socket_error`,data:{requestId:n,message:e instanceof Error?e.message:String(e)}}),new t(`COMMAND_FAILED`,`Failed to communicate with daemon`,{...i,reason:`daemon_transport_failure`,requestId:n,hint:r?`Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.`:`Retry command. If this persists, clean stale daemon metadata and start a fresh session.`},e instanceof Error?e:void 0)}async function Qe(e,t,n,r){let i=e.port;if(!i)throw R(`socket`);let a=r.signal;return F(a,t.meta?.requestId),new Promise((e,o)=>{let s=!1,c=!1,l=C.createConnection({host:`127.0.0.1`,port:i},()=>{if(a?.aborted){c=!0,d(a);return}s=!0,l.write(`${JSON.stringify(t)}\n`)}),u=typeof n==`number`?setTimeout(()=>{c||(c=!0,p(),o(Z(n,t.meta?.requestId)),l.destroy())},n):void 0,d=e=>{p(),u&&clearTimeout(u),l.destroy(),o(P(e,s?`unknown`:`no`,t.meta?.requestId))},f=()=>{c||(c=!0,d(a))},p=()=>{a&&a.removeEventListener(`abort`,f)};a&&a.addEventListener(`abort`,f,{once:!0}),ce(l,{req:t,onProgress:r.onProgress,isSettled:()=>c,clearTimeout:()=>{u&&clearTimeout(u)},resolve:t=>{c=!0,p(),e(t)},reject:e=>{c=!0,p(),o(e)}}),l.on(`error`,e=>{c||(c=!0,u&&clearTimeout(u),p(),o(X(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}function Z(e,n){return new t(`COMMAND_FAILED`,`Daemon request timed out`,{reason:`daemon_transport_timeout`,timeoutMs:e,requestId:n})}function $e(e,t,n){return{remote:t,timeoutMs:n,requestId:e.meta?.requestId,command:e.command,platform:e.flags?.platform,session:e.session,action:e.positionals?.[0]}}function et(e){return{...e.remoteInstanceId?{[g]:e.remoteInstanceId}:{},...e.remoteUpstreamInstanceId?{[_]:e.remoteUpstreamInstanceId}:{}}}function tt(e,t){return e===409&&t[`x-agent-device-instance-mismatch`]===`true`}async function nt(e,n,r,i,a){let o=e.baseUrl?new URL(m(e.baseUrl,`rpc`)):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!o)throw R(`http`);let s=JSON.stringify(ye(n,{includeTokenParam:!e.baseUrl})),c={"content-type":`application/json`,"content-length":Buffer.byteLength(s)};e.baseUrl&&(Object.assign(c,h(e.token)),Object.assign(c,et(e)));let l=await y(o.protocol),u=a.signal;return F(u,n.meta?.requestId),await new Promise((d,f)=>{let p=!1,m=!1,h=()=>{u&&u.removeEventListener(`abort`,x)},g=e=>{p||(p=!0,h(),d(e))},_=e=>{p||(p=!0,h(),f(e))},v=l.request({protocol:o.protocol,host:o.hostname,port:o.port,method:`POST`,path:o.pathname+o.search,headers:c},i=>{if(tt(i.statusCode,i.headers??{})){i.resume(),b&&clearTimeout(b),_(new t(`COMMAND_FAILED`,`Remote daemon instance changed`,{reason:`remote_instance_mismatch`,daemonBaseUrl:e.baseUrl}));return}if(se(n,i.headers?.[`content-type`])){le(i,{req:n,onProgress:a.onProgress,reject:_,clearTimeout:()=>{b&&clearTimeout(b)},handleResponseBody:t=>{k(t,{info:e,req:n,stateDir:r.baseDir,resolve:g,reject:_})}});return}ee(i).catch(e=>{throw new t(`COMMAND_FAILED`,`Failed to read daemon response`,{requestId:n.meta?.requestId,reason:`daemon_response_read_failure`},e instanceof Error?e:void 0)}).then(t=>{b&&clearTimeout(b),k(t,{info:e,req:n,stateDir:r.baseDir,resolve:g,reject:_})}).catch(e=>{b&&clearTimeout(b),_(e)})}),y=N(e),b=typeof i==`number`?setTimeout(()=>{_(Z(i,n.meta?.requestId)),v.destroy()},i):void 0,x=()=>{p||(b&&clearTimeout(b),_(P(u,m?`unknown`:`no`,n.meta?.requestId)),v.destroy())};u&&u.addEventListener(`abort`,x,{once:!0}),v.on(`error`,e=>{b&&clearTimeout(b),!p&&_(X(e,n.meta?.requestId,y))}),v.write(s),v.end(),m=!0})}let Q;function rt(e,t){return e.baseUrl===t.baseUrl&&e.token===t.token&&e.pid===t.pid}function it(e,t){!t.instanceId||t.upstream&&!t.upstream.instanceId||(Q={baseUrl:e.baseUrl??``,token:e.token,pid:e.pid,health:Promise.resolve(t)})}function $(e){Q&&rt(Q,e)&&(Q=void 0)}async function at(e){if(Q&&rt(Q,e))return await Q.health;let t={baseUrl:e.baseUrl??``,token:e.token,pid:e.pid,health:B(e)};Q=t;try{let e=await t.health;return(!e.reachable||!e.instanceId||e.upstream&&!e.upstream.instanceId)&&Q===t&&(Q=void 0),e}catch(e){throw Q===t&&(Q=void 0),e}}export{Ke as a,ke as c,ze as i,Fe as l,Be as n,Pe as o,Re as r,N as s,at as t};
@@ -1 +0,0 @@
1
- const e=`/agent-device`,t=`x-agent-device-tenant`,n=`x-agent-device-network-access`,r=`public-only`;function i(t){return a(t,e)}function a(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function o(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function s(e){let n=e?.trim();return n?{[t]:n}:{}}const c=`x-agent-device-instance`,l=`x-agent-device-upstream-instance`,u=`x-agent-device-instance-mismatch`;function d(e,t,n){return{jsonrpc:`2.0`,id:e,error:{code:-32001,message:t,data:n}}}function f(e,t,n={}){return{ok:!0,service:e,version:t,rpcProtocolVersion:2,...n.instanceId===void 0?{}:{instanceId:n.instanceId},...n.hostArch===void 0?{}:{hostArch:n.hostArch},...n.leaseBackends===void 0?{}:{leaseBackends:n.leaseBackends},...n.upstream===void 0?{}:{upstream:n.upstream}}}export{r as a,f as c,s as d,a as f,n as i,o as l,c as n,t as o,d as p,u as r,l as s,e as t,i as u};
@@ -1 +0,0 @@
1
- import{F as e,I as t,P as n,l as r,s as i}from"./sdk-contracts.js";import"./capture.js";import{i as a,m as o}from"./sdk-batch-runner.js";import{p as s}from"./android-input-ownership.js";import{r as c}from"./diagnostics.js";import"./diagnostics2.js";import{d as l,l as u,m as d,p as f,w as p}from"./sdk-device.js";import{f as m,n as h,u as ee}from"./lease-scope.js";import{Ar as te,Dr as ne,Lr as re,Yr as g,Yt as ie,en as _,o as ae,or as oe,tn as se}from"./sdk-batch.js";import{a as ce}from"./script.js";import"./dispatch-resolve.js";import{i as le}from"./back-mode.js";import{a as ue}from"./session.js";import{b as de,m as fe}from"./owner-identity.js";import{l as pe}from"./exec.js";import{t as me}from"./timeouts.js";import"./command.js";import{t as he}from"./daemon-artifacts.js";import"./process.js";import{n as ge}from"./retry.js";import{n as v}from"./runtime-transport-hints.js";import{s as _e}from"./device-shell.js";import{_ as y,a as ve,c as ye,d as be,h as xe,i as Se,n as b,o as Ce,p as we,r as Te,s as x,t as Ee,u as S,v as De,y as Oe}from"./lease-registry-scope.js";import{c as ke}from"./request-cancel.js";import{t as Ae}from"./request.js";import{n as je,t as Me,u as Ne}from"./provider-session-ownership.js";import{a as Pe,i as Fe,n as C,r as Ie}from"./human-control-contract.js";import{_ as Le,d as Re,f as ze,u as Be}from"./screenshot-runtime.js";import{r as Ve}from"./daemon-policy-file.js";import{r as He}from"./application-lifecycle-runtime.js";import{a as Ue,c as w,l as We,n as Ge,o as Ke,r as qe,t as Je}from"./device-claim-inspection.js";import{c as Ye,f as Xe,i as Ze,p as T}from"./perf-runtime-plan.js";import{n as Qe,r as E,t as $e}from"./lease-context.js";import{n as et}from"./screen-recording-admission-ledger.js";import{a as tt,c as nt,d as D,l as rt,n as it,o as at,r as ot,u as O}from"./src8.js";import{n as st,t as ct}from"./compatibility-policy.js";import{i as lt,o as ut,s as dt}from"./durable-capture-resource.js";import{o as ft}from"./screen-recording-resource-recovery.js";import pt,{createHash as mt}from"node:crypto";import"node:fs";import k from"node:os";import A from"node:path";import j from"node:fs/promises";function ht(e,t){return gt(e,t)?t:`${e}:${t}`}function gt(e,t){return t.startsWith(`${e}:`)}function _t(e,t){return!e.partitioned||gt(e.tenant,t)}const vt=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/,yt=/^[1-9][0-9]{0,9}$/;function M(e){let t=e?.trim()??``,r=t.lastIndexOf(`@`),i=r<0?t:t.slice(0,r),a=r<0?void 0:t.slice(r+1);if(!vt.test(i)||a!==void 0&&!yt.test(a))throw new n(`INVALID_ARGS`,`A macos-app lease device key must be <bundleId> or <bundleId>@<pid>.`,{deviceKey:t});return a===void 0?{bundleId:i}:{bundleId:i,pid:Number(a)}}const bt=new Set([`open`,`batch`,`lease_heartbeat`,`lease_release`]),xt=[`out`,`saveScript`,`sessionSaveScript`,`baseline`,`launchConsole`,`launchArgs`,`launchUrl`,`bundleUrl`,`artifactsDir`,`stepsFile`,`searchPath`,`retainPaths`,`installSource`,`metroProjectRoot`,`metroRuntimeFile`,`iosXctestrunFile`,`iosXctestDerivedDataPath`,`iosXctestEnvDir`],St=[`device`,`udid`,`serial`,`target`,`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function N(e,t,r={}){return new n(`UNAUTHORIZED`,t,{...r,reason:`MACOS_APP_LEASE_DENIED`,rule:e,retriable:!1,hint:`This lease is limited to one macOS app; retrying will not help. Use an allowed command on the leased app.`})}function Ct(e,t,n){if(e.backend!==`macos-app`)return;let r=M(e.deviceKey);if(Tt(r,t.command,t.positionals??[],wt(t.runtime,{...t.input,...t.flags})),(t.command===`open`||t.command===`batch`)&&t.flags?.platform!==`macos`)throw N(`device`,`A macos-app lease needs platform macos on ${t.command}.`);if(t.command===`batch`)for(let e of t.flags?.batchSteps??[]){let t=Array.isArray(e.positionals)?e.positionals.map(String):[];Tt(r,ae(e.command),t,wt(e.runtime,{...e.input,...e.flags}))}if(n)Mt(r,n);else if(!bt.has(t.command))throw N(`session`,`A macos-app lease runs ${t.command} only in a session of ${r.bundleId}; open it first.`,{command:t.command,bundleId:r.bundleId})}function wt(e,t){return{...t,...e?.launchUrl?{launchUrl:e.launchUrl}:{},...e?.bundleUrl?{bundleUrl:e.bundleUrl}:{}}}function Tt(e,t,n,r){if(!Be(t))throw N(`command`,`A macos-app lease does not allow ${t}.`,{command:t});if(kt(r),Ot(r),t===`screenshot`?Et(n,r):Dt(r),t===`open`&&At(e,n),t===`close`&&n.length>0&&n[0]!==e.bundleId)throw N(`app`,`A macos-app lease only closes ${e.bundleId}.`,{bundleId:e.bundleId})}function Et(e,t){if(t.screenshotFullscreen===!0)throw N(`capture`,`A macos-app lease captures only the app window.`);let{out:n,...r}=t;Dt(r);for(let t of[e[0],n])if(!(t===void 0||typeof t==`string`&&he(t,`screenshot`,`.png`)))throw N(`host-path`,`A macos-app lease does not write files on the host.`)}function Dt(e){let t=xt.find(t=>e[t]!==void 0&&e[t]!==!1);if(t)throw N(`host-path`,`A macos-app lease does not accept ${t}, which names a host path or launch.`,{field:t})}function Ot(e){let t=St.find(t=>e[t]!==void 0&&e[t]!==``);if(t)throw N(`device`,`A macos-app lease does not accept the ${t} device selector.`,{field:t})}function kt(e){if(e.surface!==void 0&&e.surface!==`app`)throw N(`surface`,`A macos-app lease is limited to the app surface, not ${String(e.surface)}.`,{surface:e.surface});if(e.platform!==void 0&&e.platform!==`macos`)throw N(`app`,`A macos-app lease only drives a macOS app.`,{platform:e.platform})}function At(e,t){if(t.length!==1||t[0]!==e.bundleId)throw N(`app`,`A macos-app lease only opens ${e.bundleId}.`,{bundleId:e.bundleId});jt()}function jt(){if(ue(de)!==`native`)throw N(`backend`,`A macos-app lease needs the native macOS app backend (AGENT_DEVICE_MACOS_APP_BACKEND=native).`)}function Mt(e,t){if(!d(t.device)||(t.surface??`app`)!==`app`||t.appBundleId!==e.bundleId)throw N(`app`,`This session is not the leased app ${e.bundleId}.`,{bundleId:e.bundleId})}const Nt=/bundleID="([^"]+)"/,Pt=async e=>{if(!fe(e))return;let t=await pe(`/usr/bin/lsappinfo`,[`info`,`-only`,`bundleid`,String(e)],{allowFailure:!0,timeoutMs:5e3});return Nt.exec(t.stdout)?.[1]};async function Ft(e,t=Pt){if(e.backend!==`macos-app`)return;let n=M(e.deviceKey);if(n.pid!==void 0&&await t(n.pid)!==n.bundleId)throw N(`process`,`The leased app process ${n.bundleId}@${n.pid} is no longer running.`,{bundleId:n.bundleId,pid:n.pid})}const It=[`sessionStateDir`,`runnerLogPath`,`requestLogPath`,`eventLogPath`,`device`,`id`,`kind`,`serial`,`device_udid`,`ios_simulator_device_set`],Lt=/(?<![\p{L}\p{N}_./])\/(?:Users|home|private|var|tmp|Volumes|Library|Applications|opt|System|usr|etc|Network|cores)(?:\/[\p{L}\p{N}_.@%+~-]+)*\/?/gu;function Rt(){return{hostName:k.hostname(),homeDirectory:k.homedir()}}function zt(e,t,n=Rt()){return t.ok?{ok:!0,data:Bt(e,t.data,n)}:{ok:!1,error:Vt(t.error,n)}}function Bt(e,t,n){if(!t)return t;let{fallbackScreenshotPath:r,...i}=t;if(e!==`open`)return i;for(let e of It)delete i[e];let{snapshot:a,initialSnapshotError:o,warnings:s,...c}=i;return{...c,...a===void 0?{}:{snapshot:Bt(`snapshot`,a,n)},...o===void 0?{}:{initialSnapshotError:Vt(o,n)},...s===void 0?{}:{warnings:P(s,n)}}}function Vt(e,t){let{logPath:n,diagnosticsRecord:r,...i}=e;return P(i,t)}function P(e,t){return typeof e==`string`?Ht(e,t):Array.isArray(e)?e.map(e=>P(e,t)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,P(n,t)]))}function Ht(e,t){let n=e;if(t.homeDirectory.length>1){let e=t.homeDirectory.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);n=n.replaceAll(RegExp(`${e}[\\w.@%+~/-]*`,`g`),`<host-path>`)}for(let e of new Set([t.hostName,t.hostName.split(`.`)[0]]))e.length>=4&&(n=n.replaceAll(e,`<host>`));return n.replace(Lt,`<host-path>`)}function Ut(e,t){if(!(t===void 0||!e.hasHeldMacOsAppLease(t)))throw N(`diagnostics`,`A macos-app lease does not serve request diagnostics.`)}function Wt(e,t){if(Gt(e,t.command,t.flags??{}),t.command===`batch`)for(let n of t.flags?.batchSteps??[])Gt(e,ae(n.command),{...n.input,...n.flags})}function Gt(e,t,n){if(Zt(e,t),t===`close`&&n.shutdown===!0&&Jt(e,`device-shutdown`),e.deviceIds)for(let t of[n.udid,n.serial]){let n=typeof t==`string`?t.trim():``;if(!(!n||e.deviceIds.has(n)))throw F(e,`device`,`Device ${n} is outside this daemon's policy.`,{deviceId:n})}}function Kt(e,t){return!e.deviceIds||e.deviceIds.has(t.id)}function qt(e,t){if(!Kt(e,t))throw F(e,`device`,`Device ${t.id} is outside this daemon's policy.`,{deviceId:t.id})}function Jt(e,t){if(e.deniedCapabilities.has(t))throw F(e,`capability`,`This daemon's policy denies ${t}.`,{capability:t})}function Yt(e,t){let n=e.requiredLeaseBackend;if(!(!n||t?.backend===n))throw F(e,`lease`,`This daemon's policy requires a ${n} lease.`,{leaseBackend:n})}function Xt(e,t){if(!t.deviceIds)return e;let n=e=>e.filter(e=>Kt(t,e)),r=Object.freeze({discover:async(t,r)=>n(await e.localOnly.discover(t,r))}),i=async(t,i)=>{let a=await e.providerFirst.discoverWithSource(t,i),o=n(a.devices);return o.length>0||a.source===`local`?{...a,devices:o}:{devices:await r.discover(t,i),source:`local`}},a=Object.freeze({discover:async(e,t)=>(await i(e,t)).devices,discoverWithSource:i});return Object.freeze({...e,localOnly:r,providerFirst:a})}function Zt(e,t){let n=e.commands;if(!n)return;let r=Ve(t);if(r===void 0)return;let i=n.names.has(r);if(!(n.mode===`allow`?i:!i))throw F(e,`command`,`This daemon's policy denies the ${r} command.`,{command:r})}function F(e,t,r,i){return new n(`UNAUTHORIZED`,r,{...i,reason:`DAEMON_POLICY_DENIED`,rule:t,policyDigest:e.digest,retriable:!1,hint:`The daemon operator's policy denies this request; retrying will not help. Use an allowed command and device, or ask the operator to change the policy.`})}var Qt=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)}}},$t=class{entriesByLeaseId=new Map;retain(e,t){let n={wanted:t,released:!1},r=this.entriesByLeaseId.get(e)??new Set;return r.add(n),this.entriesByLeaseId.set(e,r),{leaseId:e,release:()=>this.releasePass(e,r,n)}}forget(e){let t=this.entriesByLeaseId.get(e);if(t){for(let e of t)e.released=!0;this.entriesByLeaseId.delete(e)}}isDeferred(e){let t=this.entriesByLeaseId.get(e);if(!t)return!1;for(let e of t)e.wanted()||t.delete(e);return t.size>0||(this.entriesByLeaseId.delete(e),!1)}releasePass(e,t,n){return!n.released&&(n.released=!0,t.delete(n),t.size===0&&this.entriesByLeaseId.delete(e),n.wanted())}},en=class{holdsByDevice=new Map;mutations=new Qt;inFlightWork=new $t;leases=new Map;runBindings=new Map;deviceBindings=new Map;hostTtlMsByLeaseId=new Map;macOsAppTenantIds=new Set;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=Se(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new Me({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=be(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=Te(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}putHostLease(e,t){let r=y(e),i=be(t);this.cleanupExpiredLeases();let a=this.resolveLeaseTtlMs(i.ttlMs),o=this.leases.get(r);if(o){if(!Ce(o,i))throw new n(`INVALID_ARGS`,`Lease id already names a lease with another scope.`,{reason:`LEASE_SCOPE_MISMATCH`});return this.hostTtlMsByLeaseId.set(r,a),this.refreshLease(o,a)}if(this.assertHumanControlAdmission(i),this.assertDeviceAvailable(i),i.backend===`macos-app`&&this.macOsAppTenantIds.add(i.tenantId),this.runBindings.has(S(i)))throw new n(`DEVICE_IN_USE`,`This tenant run already holds a lease for the device.`,{reason:`DEVICE_LEASE_BUSY`});this.enforceCapacity(i.backend);let s={...Te(i,a,this.now()),leaseId:r};return this.leases.set(s.leaseId,s),this.hostTtlMsByLeaseId.set(r,a),this.bindLease(s),{...s}}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(e.retainOnClose?{...i,retainOnClose:!0}:i,t);if(i.deviceKey)throw ve(i);return b(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=y(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);Ee(n,e),b(n,e);let r=e.ttlMs===void 0?ye(n):this.resolveLeaseTtlMs(e.ttlMs),i=this.hostTtlMsByLeaseId.get(t);return this.refreshLease(n,i===void 0?r:Math.min(r,i))}retainLeaseWork(e,t){let n=this.inFlightWork.retain(e.leaseId,t);return{leaseId:n.leaseId,release:()=>{let t=n.release();return t&&this.refreshProtectedLease(e.leaseId,this.now()),t}}}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),this.inFlightWork.forget(t.leaseId),{released:!0,lease:t}):{released:!1}}getLease(e){let t=y(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return Ee(n,e),b(n,e),{...n}}assertLeaseAdmission(e){let t=we(e);this.cleanupExpiredLeases(),b(this.getActiveLease(t.leaseId),t)}hasHeldMacOsAppLease(e){return this.macOsAppTenantIds.has(e)}findActiveLeaseBackend(e){let t=xe(e);if(t)return this.cleanupExpiredLeases(),this.leases.get(t)?.backend}hasRetainedLeases(){let e=this.now();return this.listActiveLeases().some(t=>t.retainOnClose===!0&&t.expiresAt>e)}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,r,i){i?.throwIfAborted();let a=Fe(t),o=Pe(r);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 n(`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,r,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 n(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return t.hold={...t.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(e,s),C(t.hold)}catch(n){throw a.get(o)===t&&this.deleteHumanControlHold(e,o),n}}removeHumanControlHold(e,t){let n=Fe(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 Ie(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 n(`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 n(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return t.scope}if(t.scope)throw new n(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(e.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(e,t){if(e.kind===`host`)return;let r=this.requireHumanControlLease(e.leaseId);if(t.ownerLeaseId!==r.leaseId||x(r)!==x(t.hold.scope))throw new n(`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)}isLeaseProtected(e,t){return e.expiresAt>t||this.hasHumanControl(e)||this.inFlightWork.isDeferred(e.leaseId)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){this.refreshProtectedLease(this.deviceBindings.get(e),t)}refreshProtectedLease(e,t){let n=e?this.leases.get(e):void 0;n&&this.refreshLease(n,ye(n),Math.max(t,n.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(this.isLeaseProtected(n,e))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=xe(e);if(!t)return;let n=this.leases.get(t);if(!n||this.isLeaseProtected(n,this.now()))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(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 n(`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 n(`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.hostTtlMsByLeaseId.delete(e.leaseId),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 ve(r)}};function tn(e){let t=Oe(e.meta?.sessionIsolation??e.flags?.sessionIsolation),r=e.meta?.tenantId??e.flags?.tenant,i=De(r);if(r&&!i)throw new n(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(t!==`tenant`)return e;if(!i)throw new n(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=e.session||`default`;return gt(i,a)?{...e,meta:{...e.meta,tenantId:i,sessionIsolation:t}}:{...e,session:ht(i,a),meta:{...e.meta,tenantId:i,sessionIsolation:t}}}function nn(e,t,r,i={}){if(an(e,t,r,i.daemonPolicy))return;let a=Qe(e);ln(e,a);let o=r?.lease;if(i.daemonPolicy?.requiredLeaseBackend){let n=E(e,r).leaseId?rn(e,t,r):void 0;return Yt(i.daemonPolicy,n),n}if(!(r===void 0&&!a.leaseId&&sn(e,i.providerAppCatalog))){if(e.command===`human_control`&&!o&&!a.leaseId)throw new n(`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 rn(e,t,r)}}function rn(e,t,n){un(Qe(e),n?.lease);let r=E(e,n);t.assertLeaseAdmission(ee(r));let i=t.heartbeatLease(ee(r));return Ct(i,e,n),Re(e)&&t.assertHumanControlAdmission(i),i}function an(e,t,n,r){return ze(e.command)?Be(e.command)?!0:!on(e,t,n,r):!1}function on(e,t,n,r){if(r?.requiredLeaseBackend)return!0;let i=E(e,n);return i.leaseBackend===`macos-app`||i.leaseId!==void 0&&t.findActiveLeaseBackend(i.leaseId)===`macos-app`}function sn(e,t){let n=Le(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function cn(e){ze(e.command)||ln(e,Qe(e))}function ln(e,t){if(e.command!==`open`)return;let r=h(t);if(r.length!==0)throw new n(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function un(e,t){t&&(I(`leaseId`,e.leaseId,t.leaseId),I(`tenantId`,e.tenantId,t.tenantId),I(`runId`,e.runId,t.runId),I(`leaseProvider`,e.leaseProvider,t.leaseProvider),I(`clientId`,e.clientId,t.clientId),I(`deviceKey`,e.deviceKey,t.deviceKey))}function I(e,t,r){if(!(!t||!r||t===r))throw new n(`UNAUTHORIZED`,`Lease does not match session owner (${e})`,{reason:`LEASE_SESSION_MISMATCH`,field:e})}async function dn(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),c({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return c({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 fn(e){cn(e)}async function pn(e){let t=e.sessionStore.lookup(e.sessionName),n=t?.session,r=n?.lease;return!t||!n||!r||!e.leaseRegistry.consumeExpiredLease(r.leaseId)?!1:(c({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:r.leaseId,session:n.name,deviceKey:r.deviceKey}}),await e.teardownSession(t).catch(e=>{c({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:r.leaseId,session:n.name,error:e instanceof Error?e.message:String(e)}})}),await Xe(n.deviceClaim).catch(e=>{c({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:n.name,deviceKey:n.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.retire(t),!0)}function mn(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.lookup(t),a=i?.session,o=nn(e.req,r,a,{providerAppCatalog:e.providerAppCatalog,daemonPolicy:e.daemonPolicy});if(!o)return e.req;let s={...e.req,internal:{...e.req.internal,admittedLease:o}};return i&&a?.lease&&n.update(i,e=>({lease:{...e.lease,leaseBackend:o.backend,expiresAt:o.expiresAt}})),s}function hn(e){return $e(e.req,e.req.internal?.admittedLease)??e.existingLease}async function gn(e){let t=e.session.lease;if(!t)return;let n=m({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);if(r?.retainOnClose){c({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:!1,retained:!0}});return}let i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=je(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return c({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const _n=[`platform`,`target`],vn=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function yn(e){return u({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function bn(e){return yn(e)||Cn(e,_n)}function xn(e){return bn(e)||Cn(e,vn)}function Sn(e){return typeof e==`string`&&e.trim().length>0}function Cn(e,t){return e?t.some(t=>Sn(e[t])):!1}function wn(e){return{appleSimulatorAppTarget:Tn(e)}}function Tn(e){return e&&!a(e)?e:void 0}function En(){return et({displayName:`audio probe`})}function Dn(){return et({displayName:`perf capture`})}function On(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return mt(`sha256`).update(oe(t),`utf8`).digest(`hex`)}function kn(e,t){try{return new Rn(jn(An(e)),t).parse()}catch(e){if(e instanceof n&&e.code===`INVALID_ARGS`)return;throw e}}function An(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function jn(e){let t=[],r=0;for(;r<e.length;){let i=e.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Mn(i);if(!o)throw new n(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);t.push(o.value),r+=o.length}return t}function Mn(e){return Nn(e)??Pn(e)??Fn(e)??In(e)??Ln(e)}function Nn(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Pn(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Fn(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function In(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Ln(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Rn=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new n(`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 n(`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 n(`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 n(`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 n(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new n(`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]}};const zn=new Set([``,`false`,`0`,`null`,`undefined`]);function L(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!zn.has(e)}function Bn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?L(e):typeof e==`bigint`?e!==0n:e!=null}function Vn(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Hn(e,t){return{...B(e,t),source:e.source}}function R(e,t,r){if(e===void 0)return;let i=r??tt[t]??{},a=at(i),o;if(typeof e==`number`)o=e;else{let r=e.trim();if(r===``)throw new n(`INVALID_ARGS`,`Maestro ${t} 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 n(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function Un(e,t,n,r){return R(e===void 0?t:n.resolve(String(e)),r)}function z(e){if(e?.aborted)throw t()}async function Wn(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new n(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return z(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 Gn(e,t){if(e.include.kind===`file`)return A.resolve(t?A.dirname(t):process.cwd(),e.include.path)}function Kn(e){return e===void 0?void 0:A.resolve(e)}function qn(e,t){let r=Gn(e,e.source.path);if(r&&t.has(r))throw new n(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Jn(e,t,r,i){let a=e.include.kind===`file`?Kn(t.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 n(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Yn(e,t){if(e.trustedScripts===!1)throw new n(`UNAUTHORIZED`,`Maestro ${t} is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`)}async function Xn(e,t,n,r){if(e===void 0)return!0;if(typeof e==`boolean`)return e;let i=Zn(e,n);if(i!==void 0){let e=kn(i,r.platform);if(e!==void 0)return e;if(!i.includes("${"))return L(i)}Yn(r,t);let{evaluateMaestroConditionScript:a}=await import(`./engine-eval-script.js`),o=await a(e,n.values,r.platform,t);return n.replaceOutput(o.outputEnv),Bn(o.value)}function Zn(e,t){try{return t.resolve(e)}catch(e){if(e instanceof n&&e.code===`INVALID_ARGS`)return;throw e}}function Qn(e,t){return[...e.visible?[{kind:`visible`,selector:B(e.visible,t)}]:[],...e.notVisible?[{kind:`notVisible`,selector:B(e.notVisible,t)}]:[]]}function B(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>B(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,B(n,t)])):e}async function $n(e,t){z(t.signal);let n=Kn(e.source.path),r={options:t,context:nt(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await er(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function er(e,t,n,r,i){z(i.options.signal);let a=ur(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 nr(s,a,o,e.source.path??r,i));return n}finally{s()}}async function tr(e,t,n,r,i){let a=[];for(let o of e)a.push(...await nr(o,t,n,r,i));return a}async function nr(e,t,n,r,i){z(i.options.signal);let a=dr(e,r);switch(a.kind){case`runFlow`:{let e=ir(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await rr(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[V(a,t,n,o)]}case`repeat`:return[V(a,t,n,await tr(a.commands,t,n,r,i))];case`retry`:return[V(a,t,n,await tr(a.commands,t,n,r,i))];default:return[cr(a,t,n)]}}async function rr(e,t,n,r,i){let a=or(e,i.context),o=qn(a,i.activeIncludePaths),s=await Wn(a,i.options);z(i.options.signal);let c=Jn(a,s,o,i.activeIncludePaths),l=ur(t,e.env),u=i.context.enter(e.env);try{return await er(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function ir(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:ar(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function ar(e,t){if(e===!1)return`omit`;if(typeof e!=`string`)return;let n=t.context.resolveDeferred(e);if(sr(n))return`opaque`;let r=kn(n,t.options.platform);return r===void 0?`opaque`:r?void 0:`omit`}function or(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function sr(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function cr(e,t,n){return D({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function V(e,t,n,r){return D({kind:`opaque`,command:lr(e),source:e.source,scopes:t,body:r,appId:n})}function lr(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 D({kind:e.kind,source:e.source,times:e.times,while:e.while});case`retry`:return D({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function ur(e,t){return t===void 0?e:[...e,t]}function dr(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function fr(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await $n(e,t),a=pr(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=On(o);return mr({...o,digest:s})}function pr(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 mr(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))mr(t);return Object.freeze(e)}function hr(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function gr(e,t={}){let r=hr(e,t);if(!r.allowed)throw new n(`INVALID_ARGS`,r.reason);return r.startIndex}function _r(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new n(`INVALID_ARGS`,`Maestro replay startIndex ${t} is out of range for a ${e.total}-step plan.`);return t}const vr=`maestro-test-failure`;function H(e,t={}){return new n(`COMMAND_FAILED`,e,{...t,reason:vr})}function yr(e){return e instanceof n&&e.code===`COMMAND_FAILED`&&e.details?.reason===vr}async function br(e,t){z(t.options.signal);try{return await Pr(e,t.context,async()=>await xr(e,t))}catch(t){throw G(t,e)}}async function xr(e,t){if(e.kind===`command`)return await Sr(e.command,e.appId,t);await Or(e,t)}async function Sr(e,t,n){if(e.kind===`evalScript`)return await Tr(e,n);let r=Hn(e,n.context);try{return await Er(r,t,n)}catch(e){if(z(n.options.signal),wr(r)&&yr(e)){n.warnings.push(Cr(r,e)),n.skipped+=1;return}throw Fr(e,r)}}function Cr(e,t){let r=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,i=t instanceof n?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${r}: ${i}`}function wr(e){return`optional`in e&&e.optional===!0}async function Tr(e,t){let{evaluateMaestroEvalScript:n}=await import(`./engine-eval-script.js`);Yn(t.options,`evalScript`);let r=await n(e.script,t.context.values);t.context.replaceOutput(r),t.executed+=1}async function Er(e,t,n){switch(e.kind){case`assertVisible`:await W({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await W({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!L(e.condition))throw H(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await W(Nr(e),R(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await Dr(e,t,n)}}async function Dr(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 z(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 Or(e,t){let n=e.command;switch(n.kind){case`runFlow`:if(n.when&&!await jr(n.when,`runFlow.when`,t)){t.skipped+=1;return}t.executed+=1,await U(e.body,t);return;case`repeat`:t.executed+=1,await kr(e.body,n.times,n.while,t);return;case`retry`:{let r=Math.min(Un(n.maxRetries,1,t.context,`retry.maxRetries`),st.control.retryMaxRetries);t.executed+=1,await Ar(e.body,r,t);return}}}async function U(e,t){for(let n of e)await br(n,t)}async function kr(e,t,n,r){let i=t===void 0&&n?1/0:Un(t,0,r.context,`repeat.times`);for(let t=0;t<i;t+=1){if(await new Promise(e=>setImmediate(e)),z(r.options.signal),n&&!await jr(n,`repeat.while`,r))return;await U(e,r)}}async function Ar(e,t,r){let i;for(let n=0;n<=t;n+=1){z(r.options.signal);try{await U(e,r);return}catch(t){if(z(r.options.signal),!yr(Lr(t)))throw t;i=G(t,e[0])}}throw i||new n(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function jr(e,t,n){if(e.platform&&e.platform!==n.options.platform||!await Xn(e.true,`${t}.true`,n.context,n.options))return!1;for(let t of Qn(e,n.context))if(z(n.options.signal),!(await Mr(t,n.timing.runFlowConditionTimeoutMs,n)).matched)return!1;return!0}async function W(e,t,n){if(!(await Mr(e,t,n)).matched)throw H(`Maestro ${e.kind} condition did not match.`)}async function Mr(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 z(n.options.signal),n.context.recordObservation(i),i}function Nr(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new n(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Pr(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 G(e,t){if(Ir(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Rr(e,t?.command),source:n,...t?{command:t.command}:{}}}function Fr(e,t){return{kind:`maestroPlanStepFailure`,error:Rr(e,t),source:t.source,command:t}}function Ir(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Lr(e){return Ir(e)?e.error:e}function Rr(e,t){if(!(e instanceof n)||!t||/\bline \d+\b/.test(e.message))return e;let r=t.source.path?`${t.source.path}:`:``;return new n(e.code,`${e.message} (${r}line ${t.source.line})`,e.details)}async function zr(e,t,r={}){z(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>e.total)throw new n(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:r,context:nt(r.defaults,r.env?{...r.env}:{}),timing:ct,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=i;t<e.steps.length;t+=1)try{await Br(e.steps[t],t,a)}catch(e){throw Lr(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Br(e,t,n){z(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};K(()=>n.options.observer?.commandStarted?.(s));try{let t=await br(e,n);z(n.options.signal),K(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Vr(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=G(t,e);throw K(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Vr(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Vr(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 K(e){try{e?.()}catch{}}async function Hr(e,t,n={}){let r=Ur(e,n);return await zr(e,t,{...n,startIndex:r})}function Ur(e,t){return t.from!==void 0||t.planDigest!==void 0?gr(e,{from:t.from,planDigest:t.planDigest}):_r(e,t.startIndex??0)}function Wr(e){return Vn(e)?{command:e.kind,...e.kind===`runFlow`?J(e.label??e.includePath):{}}:{command:e.kind,...Gr(e)}}function Gr(e){return`label`in e&&e.label?J(e.label):Kr(e)?J($r(e.target)):qr(e)?Jr(e):e.kind===`inputText`?J(`<text>`):Yr(e)}function Kr(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function qr(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Jr(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return J(q(e.target));case`extendedWaitUntil`:return J(q(e.visible??e.notVisible));case`scrollUntilVisible`:return J(q(e.element))}}function Yr(e){return Xr(e)?Zr(e):e.kind===`swipe`?Qr(e):e.kind===`runFlow`?J(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?J(String(e.condition)):{}}function Xr(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Zr(e){switch(e.kind){case`openLink`:return J(e.link);case`takeScreenshot`:return J(e.path);case`runScript`:return J(e.file);case`pressKey`:return J(e.key)}}function Qr(e){return J(e.gesture.kind===`coordinates`?`${ei(e.gesture.start)} to ${ei(e.gesture.end)}`:e.gesture.direction)}function $r(e){return e.space===`target`?q(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function q(e){return e?.id??e?.text}function ei(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function J(e){return e?{value:e}:{}}const ti=new Set(String.raw`^$\.*+?()[]{}|`);function ni(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function ri(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(ti.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!ti.has(i))return;t+=i,n+=1}return t}function ii(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(g(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>te(e,n)?e:null);return r?g(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function ai(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function oi(e,t){let n=[t.id===void 0?void 0:ci(e.identifier,t.id),t.text===void 0?void 0:li(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 si(e){return e.matches.filter(t=>ii(t,e.visibility,e.platform))}function ci(e,t){let n=e??``;return O(n)===O(t)||ni(n,t)}function li(e,t){return[e.label,rt(e),e.identifier].filter(e=>!!e).some(e=>ci(e,t))}function ui(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 di(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function fi(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=mi(a.rect,e.rect);n===void 0||!pi(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 pi(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 mi(e,t){if(!(!hi(e)||!hi(t)))return Math.fround(Math.hypot(Y(e.x,e.width)-Y(t.x,t.width),Y(e.y,e.height)-Y(t.y,t.height)))}function hi(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function Y(e,t){return e+Math.trunc(t/2)}function gi(e,t={},r={}){let i=ne(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=fi(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 n(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),t.onSelectorComputed?.(i);try{let t=_i(e,i,l,u,m,p),n={matches:t,indexed:xi(t,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function _i(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=di(m)?e.nodes.filter(e=>oi(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>yi(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=>vi(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of bi(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function vi(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function yi(e,t){for(let n of e)if(t.has(n))return!0;return!1}function bi(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function xi(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Ci(e)[wi(t)];return r?[r]:[]}function Si(e,t){return t===void 0?e[0]:Ci(e)[wi(t)]}function Ci(e){return[...e].sort((e,t)=>{let n=X(e.rect?.y),r=X(t.rect?.y);return n===r?X(e.rect?.x)-X(t.rect?.x):n-r})}function X(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function wi(e){let t=typeof e==`number`?e:Number(e.trim());if(!Number.isSafeInteger(t)||t<0)throw new n(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return t}const Ti={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Ei(e,t){let n=Ti[t];if(n.kind===`divergence`)return n;let r=s(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 Z(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Di(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Di(e){return e===!0?2:+(e===!1)}function Oi(e,t,n,r={}){let i=Ei(e,n),a=Ai(e,i,r),o=ki(t,a),s=si({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:ji(s,t,n,a.visibility,i)}}function ki(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Ai(e,t,n={}){return gi(e,n,t?{orderUnindexed:e=>Z(e,t)}:{})}function ji(e,t,n,r,i){let a=n!==`ios`||!Fi(t)?e:e.filter(n=>{if(zi(n))return!0;let i=e.filter(e=>e!==n&&Ii(n,e,t));return!i.some(e=>zi(e)&&ai(n,e,r))&&!i.some(e=>ai(e,n,r))});return t.index===void 0&&i?Z(a,i):a}function Mi(e,t){let n=t===void 0?e.find(Q):Ni(e,t);return!n||!Q(n)?null:{node:n,rect:n.rect}}function Ni(e,t){return Si(e,t)}function Pi(e){return Q(e)?e.rect:void 0}function Q(e){return g(e.rect)}function Fi(e){return e.id!==void 0||e.text!==void 0}function Ii(e,t,n){if(n.id!==void 0&&Ri(e.identifier)!==Ri(t.identifier))return!1;if(n.text!==void 0){let n=Li(e),r=new Set(Li(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Li(e){return[e.label,e.value,e.identifier].map(Ri).filter(e=>e!==void 0)}function Ri(e){if(e)return O(e)||void 0}function zi(e){let t=re(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Bi=Symbol(`maestroFlowProgram`),Vi=Symbol(`maestroFailureCommand`),Hi=Symbol(`maestroFailurePlan`);function Ui(e,t){let n=ot(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Ji(n),[Bi]:n}}async function Wi(e,t,n){let r;try{let i=it(A.dirname(e.sourcePath),n.readSource),a=await fr(e[Bi],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=gr(a,{from:n.from,planDigest:n.planDigest}),s=await Hr(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,trustedScripts:n.trustedScripts,observer:Ki(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 Gi(e,t){let n=Xi(e[Vi]),r=e[Hi].platform;return!n||r!==`android`&&r!==`ios`?[]:Oi(t,n.selector,r).ranked.map(e=>({node:e,basis:Zi(n.selector,e)}))}function Ki(e,t,n){return{commandStarted:e=>t?.actionStarted?.(qi(e)),commandCompleted:e=>t?.actionCompleted?.({...qi(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=hr(e,{from:r.stepIndex,planDigest:e.digest}),a={...qi(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:Vn(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},[Vi]:r.command,[Hi]:e};n(a),t?.actionFailed?.(a)}}}function qi(e){let t=Wr(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Ji(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(Yi)}function Yi(e){return!!(e?.trim()&&!e.includes(`$`)&&!a(e))}function Xi(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 Zi(e,t){return e.id!==void 0||e.text!==void 0&&oi({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const Qi=`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 $i(e,t){let r=e.files[t];if(r===void 0)throw new n(`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 r}function ea(e){let t=ce(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ra(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function ta(e,t){return t===`ios`?ia(e)??{}:{}}function na(e,t){let n=ea(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ra(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!a(e))}function ia(e){let t=Tn(e);return t?{appleSimulatorAppTarget:t}:void 0}function aa(e){let t=e.flags??{};if(t.waitMs===void 0)return;let[r]=le(`waitMs`);if(!r)throw new n(`INTERNAL_ERROR`,`The waitMs option has no flag declaration whose bounds the daemon can enforce.`);return o(t,`waitMs`,{min:r.min,max:r.max})}function oa(e){let t=e.internal?.openDeviceWait?.waitedMs;return t===void 0?{}:{waitedMs:t}}function sa(e){return{...oa(e),offersDeviceWait:e.command===`open`&&typeof e.flags?.waitMs!=`number`}}function ca(e){let{req:t,budgetMs:n,sessionName:r,sessionStore:i,deviceId:a}=e;if(t.command===`open`&&n!==void 0&&!(a===void 0||i.get(r)))return ua({req:t,sessionName:r,sessionStore:i,deviceId:a,budgetMs:n})}function la(e,t,n){let r=e.findByDevice(t);if(!(!r||r.address===n))return r}function ua(e){let{req:t,sessionName:n,sessionStore:r,deviceId:i,budgetMs:a}=e,o=ge.fromTimeoutMs(a),s=()=>la(r,i,n),c=async()=>{for(;;){let e=s();if(!e||o.isExpired())return;Ae({type:`command`,status:`progress`,message:`Waiting for ${e.session.device.name}: held by session "${e.address}" (${Math.round(o.elapsedMs())}ms of the ${Math.round(a)}ms wait budget used)`}),await me(Math.min(250,o.remainingMs())),ke(t.meta?.requestId)}};return{waitForDeviceOutsideLocks:c,runWhenDeviceIsUnheld:async e=>{let{acquireLocks:n,task:r}=e;for(;;){let e=await n(async()=>{if(s()){if(!o.isExpired())return{ran:!1};da(t,o.elapsedMs())}return{ran:!0,outcome:await r()}});if(e.ran)return e.outcome;await c()}}}}function da(e,t){if(t<=0)return;let n=e.internal??={};n.openDeviceWait={waitedMs:t}}const fa={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.`},$=new Map;async function pa(e){let t=await j.mkdtemp(A.join(k.tmpdir(),`agent-device-materialized-`));try{let n=await va(e.installablePath,A.join(t,`installable`)),r=e.archivePath?await va(e.archivePath,A.join(t,`archive`)):void 0,i=pt.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{ga(i)},a);return $.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 ma(e,t){await _a(e,Ne($,e,t,fa))}async function ha(e){let t=Array.from($.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await _a(e,t)}))}async function ga(e){let t=$.get(e);if(t)try{await _a(e,t)}catch{}}async function _a(e,t){clearTimeout(t.timer),$.delete(e),await j.rm(t.rootPath,{recursive:!0,force:!0})}async function va(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 ya(e){return e.device.platform===`web`}function ba(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function xa(e){let t=e.sessionStore.refresh(e.ref);if(!t.session.appLog)return;let{forceCleanupSessionAppLog:n}=await import(`./app-log-session-resource.js`).then(e=>e.r);await n({...e,ref:t})}async function Sa(e){let t=ut(e.sessionStore,e.ref);t.read()&&await Ze({binding:t,intent:`disposal`})}async function Ca(e,t){await t.stopSnapshotHelper(e.device)}async function wa(e){let{ref:t,sessionStore:n,platformCleanup:r}=e,i=n.resolveCurrent(t)??t.session,a=t.address;await r.closeManagedBrowser({device:i.device,sessionName:a,stateDir:n.resolveDaemonStateDir(),openSessionNames:()=>ba(n)})}async function Ta(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 Ea(e){if(e.failures.length===0)return;let t=e.failures.map(({step:e})=>e),r=e.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return c({level:`error`,phase:e.phase,data:{session:e.sessionName,failedSteps:t,errors:r}}),new n(`COMMAND_FAILED`,`Session cleanup left ${e.failures.length} resource(s) unreleased: ${r.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 Da(e){let{ref:t,sessionStore:r}=e,i=r.resolveCurrent(t)??t.session,a=t.address;if(!e.platformCleanup)throw new n(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let o=e.platformCleanup,s=[{step:`recording`,run:()=>Oa({ref:t,sessionStore:r})},...e.appLog===`run`?[{step:`app_log`,run:()=>xa({ref:t,sessionStore:r})}]:[],{step:`audio_probe`,run:()=>ka({ref:t,sessionStore:r})},{step:`perf_capture`,run:()=>Sa({ref:t,sessionStore:r})},{step:`platform_snapshot_helper`,run:()=>Ca(i,o)},{step:`web_browser`,run:()=>wa({ref:t,sessionStore:r,platformCleanup:o})}];s.push({step:`materialized_paths`,run:()=>ha(a)});let c=Ea({sessionName:a,phase:`session_teardown_cleanup_failed`,failures:await Ta(s)});if(c)throw c}async function Oa(e){let t=dt(e.sessionStore,e.ref);t.read()&&await ft({binding:t,intent:`disposal`})}async function ka(e){let t=lt(e.sessionStore,e.ref);t.read()&&await Ye({binding:t,intent:`disposal`})}function Aa(e){return f(e)&&e.kind===`simulator`}function ja(e){return e.platform===`android`&&e.kind===`emulator`}const Ma=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Na(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Pa(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 Fa(e){return He(Pa(e))}function Ia(e,t){if(e!==void 0){if(typeof e!=`string`)throw new n(`INVALID_ARGS`,`Invalid open runtime ${t}: expected string.`);return v(e)}}function La(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new n(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function Ra(e){if(e!==void 0){if(typeof e!=`number`)throw new n(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return La(e)}}function za(e,t,i){if(e===void 0)return i;if(!r(e))throw new n(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios", "android", or "harmonyos".`);if(i&&e!==i)throw new n(`INVALID_ARGS`,`open runtime targets ${e}, but session "${t}" is bound to ${i}.`);return e}function Ba(e){if(r(e))return e}function Va(e,t){return{platform:t,metroHost:v(e?.metroHost),metroPort:La(e?.metroPort),bundleUrl:v(e?.bundleUrl),launchUrl:v(e?.launchUrl)}}function Ha(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 Ua(e){if(ja(e))return`10.0.2.2`;if(Aa(e))return`127.0.0.1`}function Wa(e,t){if(!e||v(e.metroHost)||v(e.bundleUrl)||e.metroPort===void 0)return e;let n=Ua(t);return n?{...e,metroHost:n}:e}function Ga(e){let{runtime:t,sessionName:r,platform:i}=e;if(t===void 0)return;if(!t||typeof t!=`object`||Array.isArray(t))throw new n(`INVALID_ARGS`,`open runtime must be an object.`);let a=t,o=Object.keys(a).find(e=>!Ma.includes(e));if(o)throw new n(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ma.join(`, `)}.`);return{platform:za(a.platform,r,i),metroHost:Ia(a.metroHost,`metroHost`),metroPort:Ra(a.metroPort),bundleUrl:Ia(a.bundleUrl,`bundleUrl`),launchUrl:Ia(a.launchUrl,`launchUrl`)}}function Ka(e,t,n){if(n){if(Na(n)===0){e.setRuntimeHints(t,void 0);return}return e.setRuntimeHints(t,n),n}}function qa(e,t,r,i){let a=e.getRuntimeHints(t);if(!a)return;let o=r?p(r):void 0,s=Ba(o)??i;if(a.platform&&r&&!s)throw new n(`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 n(`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 Ja(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Ba(p(i)):e.platform,o=n.getRuntimeHints(r),s=Ga({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=qa(n,r,i,a);return{runtime:i?Wa(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&Na(s)>0?s:void 0;return{runtime:i?Wa(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ya(e){return Ja(e).runtime}function Xa(t){try{return{ok:!0,data:Ja(t)}}catch(t){let n=e(t);return i(n.code,n.message,n.details)}}async function Za(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!Qa(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Pa(t)})}function Qa(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Fa(e.previousRuntime)&&!Fa(e.runtime)}function $a(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&se(i.owner,n)?ie(i.fence):null;if(!a)return{status:`binding-invalid`};let o=w(T(t)),s=qe(We(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!to(c.stateDir,r)||!se(Ke(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function eo(e){let t=w(T(e));return Ue(We(t))}function to(e,t){return A.resolve(e)===A.resolve(t)}function no(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=p(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=l(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${_e(i)}`,`${a} ${_e(e.id)}`,...n===`release`||Ge(t.classification)?[`--stale`]:[]].join(` `)}function ro(e,t){if(t.classification===`allocator-held`)return ao(e,t);let r=t.claim,i=no(e,t,Je(t.classification)?`release`:`status`),a=p(r?{platform:r.device.family,appleOs:r.device.appleOs}:e);return new n(`DEVICE_IN_USE`,r?`${a} device ${e.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${e.name} has an ownership claim that could not be verified.`,{reason:po(t.classification),classification:t.classification,deviceKey:t.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:Je(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 io(e,t){return fo(ro(e,t))}function ao(e,t){let r=t.allocatorClaim,i=p({platform:r.device.family,appleOs:r.device.appleOs}),a=no(e,t);return new n(`DEVICE_IN_USE`,`${i} device ${e.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:t.classification,deviceKey:t.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 oo(e,t){return new n(`COMMAND_FAILED`,`${p(e)} device ${e.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:_(t),deviceKey:w(T(e)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function so(e,t,r){return new n(`COMMAND_FAILED`,`${p(e)} device ${e.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:_(t),deviceKey:w(T(e)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function co(e,t){return new n(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:_(t),deviceKey:w(T(e)),retriable:!1})}function lo(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:co(e,t)};case`missing`:return{admitted:!1,error:oo(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:so(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:ro(e,n.conflict)}}}function uo(e,t,n){let r=lo(e,t,n);return r.admitted?void 0:fo(r.error)}function fo(e){let{hint:t,retriable:n,...r}=e.details??{};return i(e.code,e.message,r,{hint:t,retriable:n})}function po(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 mo(e,t){if(t?.backend===`macos-app`)return`none`;switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{ui as $,pa as A,Gi as B,Sa as C,Jt as Ct,ba as D,M as Dt,ya as E,Ut as Et,ta as F,Oi as G,Ui as H,na as I,Ni as J,ji as K,ea as L,sa as M,aa as N,ma as O,zt as Ot,ia as P,gi as Q,Qi as R,xa as S,Wt as St,Da as T,Ft as Tt,Ai as U,Wi as V,ki as W,Z as X,Pi as Y,Ei as Z,Ba as _,hn as _t,ro as a,Dn as at,Oa as b,en as bt,Va as c,bn as ct,Za as d,Sn as dt,si as et,Ha as f,mn as ft,Qa as g,gn as gt,Ka as h,dn as ht,lo as i,R as it,ca as j,ha as k,_t as kt,Na as l,yn as lt,Pa as m,pn as mt,uo as n,ri as nt,eo as o,En as ot,Ya as p,fn as pt,Mi as q,io as r,H as rt,$a as s,wn as st,mo as t,ii as tt,Fa as u,xn as ut,Xa as v,on as vt,Ca as w,Xt as wt,Ea as x,qt as xt,ka as y,tn as yt,$i as z};
@@ -1 +0,0 @@
1
- import{P as e}from"./sdk-contracts.js";const t=`native-panel`,n=[`portrait`,`portrait-upside-down`,`landscape-left`,`landscape-right`],r={portrait:0,"landscape-left":1,"portrait-upside-down":2,"landscape-right":3};function i(e){return n.find(t=>r[t]===e)}function a(e){return typeof e==`string`&&n.includes(e)}function o(e){return r[e]*90}function s(e){return r[e]%2==0?`PORTRAIT`:`LANDSCAPE`}function c(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.`)}}const l=[`closed`,`half-open`,`open`],u=`closed|half-open|open`;function d(e){if(Number.isFinite(e))return e<=f?`closed`:e>=p?`open`:`half-open`}const f=1,p=179;function m(t){if(t===void 0)throw new e(`INVALID_ARGS`,`fold requires a pose argument. Use ${u}.`);switch(t.trim().toLowerCase()){case`closed`:case`close`:case`fold`:case`folded`:return`closed`;case`half-open`:case`half`:case`half-unfolded`:case`partially-open`:case`book`:return`half-open`;case`open`:case`unfold`:case`unfolded`:case`fully-open`:case`flat`:return`open`;default:throw new e(`INVALID_ARGS`,`Invalid fold pose: ${t}. Use ${u}.`)}}const h=6e4;function g(t){if(t.keyframes===void 0){if(t.pose===void 0)throw new e(`INVALID_ARGS`,`fold requires a pose or keyframes`);if(typeof t.pose!=`string`)throw new e(`INVALID_ARGS`,`fold pose must be a string`);return{pose:m(t.pose)}}if(t.pose!==void 0)throw new e(`INVALID_ARGS`,`fold accepts either pose or keyframes`);return{keyframes:_(t.keyframes)}}function _(t){if(!Array.isArray(t)||t.length<2||t.length>64)throw new e(`INVALID_ARGS`,`fold requires 2–64 keyframes`);let n=t.map(y);if(n[0].atMs!==0||n.some((e,t)=>t>0&&e.atMs<=n[t-1].atMs))throw new e(`INVALID_ARGS`,`Fold keyframes must start at 0ms and increase strictly`);return n}function v(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=t}function y(t){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`Each fold keyframe requires atMs and angle`);let{atMs:n,angle:r}=t;if(Object.keys(t).some(e=>e!==`atMs`&&e!==`angle`))throw new e(`INVALID_ARGS`,`Fold keyframes only accept atMs and angle`);if(!v(n,6e4)||!Number.isSafeInteger(n))throw new e(`INVALID_ARGS`,`Fold keyframe times must be integers from 0 to ${h}ms`);if(!v(r,180))throw new e(`INVALID_ARGS`,`Fold keyframe angles must be finite numbers from 0 to 180`);return{atMs:n,angle:r}}function b(t){let n;try{n=JSON.parse(t)}catch{throw new e(`INVALID_ARGS`,`--keyframes requires a JSON array of {atMs, angle} objects`)}return _(n)}export{t as a,s as c,a as d,c as f,m as h,u as i,o as l,b as m,r as n,h as o,g as p,l as r,i as s,n as t,d as u};
@@ -1,3 +0,0 @@
1
- import{B as e,P as t}from"./sdk-contracts.js";import{i as n}from"./sdk-batch-runner.js";import{n as r}from"./app-inventory.js";import"./device.js";import{t as i}from"./ios-client.js";import{t as a}from"./instance-client.js";import{t as o}from"./request-cancellation.js";import{i as s}from"./snapshot.js";import c from"node:fs";import l from"node:os";import u from"node:path";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await a({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,ownership:e.ownership,device:e.device,client:n,token:e.token,dependencies:t},i={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return i.reverse=await t.android.createPortReverse(i.exec,{noRebind:e.ownership===`attached`}),Object.assign(r,{adbProvider:i})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,r,i,a){i?.throwIfAborted();let s=f(r?.packageNameHint);r?.relaunch&&s&&await t.dependencies.android.forceStopApp(async(e,n)=>await y(t,e,n),s,i);let c=await o(a,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:i}),i);await o(a,t.client.sendAsset(c.signedDownloadUrl),i),i?.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(e.dependencies.android.hostAdbInvocation([`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=[],a=e.ownership===`attached`;for(let e of n)e.ownerId?r.add(e.ownerId):a||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{invocation: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=await S(e),i=e.dependencies.android.deviceAdbInvocation(r,t);return{invocation:i,result:await e.dependencies.host.runAdb(i,{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,e);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(e){if(!Number.isInteger(e)||e<1||e>65535)throw new t(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${e}`);return`tcp:${e}`}function T(e,t){let n=u.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await i({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,ownership:e.ownership,device:e.device,client:n,token:e.token,dependencies:t}}async function D(e,t,n,r,i,a){i?.throwIfAborted();let s=await j(n,t.dependencies);try{i?.throwIfAborted();let n=await o(a,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:i}),i),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:r?.relaunch,appIdentifierHint:r?.appIdentifierHint},i,a)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(e,n,r,i,a){i?.throwIfAborted();let s=await o(a,e.client.listApps(),i).catch(e=>{if(i?.aborted)throw e}),c=f((await o(a,e.client.installApp(n,{md5:r?.md5,launchMode:r?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),i)).bundleId),l=f(r?.appIdentifierHint),u=[];for(let t of N){t>0&&await d(t,void 0,{signal:i}),u=await o(a,e.client.listApps(),i);let n=I({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new t(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(R).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,t){if(t?.url){await this.launch(e,t.launchArgs),await this.session.client.openUrl(t.url);return}if(n(e)){await this.session.client.openUrl(e);return}await this.launch(e,t?.launchArgs)}async launch(e,n=[]){let r=await this.session.dependencies.ios.resolveAppAlias(e);if(n.length===0){await this.session.client.launchApp(r);return}let i=await this.session.client.simctl([`launch`,`--terminate-running-process`,`booted`,r,...n]).wait();if(i.code!==0)throw new t(`COMMAND_FAILED`,`Limrun iOS could not launch ${r} with arguments.`,{bundleId:r,exitCode:i.code,stderr:i.stderr.trim()})}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(s(e))}async doubleTap(e,t){await this.session.client.performActions([{type:`tap`,x:e,y:t},{type:`wait`,durationMs:F},{type:`tap`,x:e,y:t}])}async longPress(e,t,n=P){await this.session.client.performActions([{type:`touchDown`,x:e,y:t},{type:`wait`,durationMs:n},{type:`touchUp`,x:e,y:t}])}async focus(e,t){await this.tap(e,t)}async type(e,t){await this.enterText(e,t)}async fill(e,t,n,r){let{awaitLimrunTextEntryFocus:i,readLimrunUnambiguousTapTargets:a,readLimrunTextEntryFocus:o}=await import(`./text-entry-focus.js`),s=a(await this.session.client.elementTree(),e,t);await this.tap(e,t);let c=await i({targetsAtPoint:s,readFocus:async()=>o(await this.session.client.elementTree()),sleep:e=>d(e),x:e,y:t});return await this.session.client.pressKey(`a`,[`command`]),n.length===0?(await this.session.client.pressKey(`delete`),{textEntryReadiness:c}):(await this.enterText(n,r),{textEntryReadiness:c})}async enterText(t,n){if(n&&n>0){let r=0;try{for(let e of Array.from(t))await this.session.client.typeText(e,!1,{requireFocus:!1}),r+=1,await d(n)}catch(t){throw e(t,r)}return}await this.session.client.typeText(t,!1,{requireFocus:!1})}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let{transcodeScreenshotToPngAsync:t}=await import(`./png-worker-client.js`).then(e=>e.s),n=await this.session.client.screenshot(),r=await t(Buffer.from(n.base64,`base64`),`Limrun iOS screenshot`);c.mkdirSync(u.dirname(e),{recursive:!0}),await c.promises.writeFile(e,r)}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(){await this.session.client.performActions([{type:`buttonDown`,button:`home`},{type:`buttonUp`,button:`home`}])}async readClipboard(){return(await this.pasteboard([`pbpaste`,`booted`])).stdout.replaceAll(`\r
2
- `,`
3
- `).replace(/\n$/,``)}async writeClipboard(e){await this.pasteboard([`pbcopy`,`booted`],e)}async pasteboard(e,n){let r=await this.session.client.simctl(e,n===void 0?void 0:{stdin:n}).wait();if(r.code!==0)throw new t(`COMMAND_FAILED`,`Limrun iOS could not access the clipboard.`,{command:e[0],exitCode:r.code,stderr:r.stderr.trim()});return r}async setOrientation(e){if(e===`portrait-upside-down`)throw z(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async setSetting(e,t,n,r){let{setLimrunIosSetting:i}=await import(`./ios-settings.js`);return await i(this.session,e,t,n,r)}};async function j(e,t){if(!(await c.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:u.basename(e),appName:M(e),cleanup:async()=>{}};let n=await c.promises.mkdtemp(u.join(l.tmpdir(),`agent-device-limrun-ios-app-`)),r=u.join(n,`${u.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:u.dirname(e),entryName:u.basename(e),archivePath:r})}catch(e){throw await c.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:u.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await c.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return u.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250],P=800,F=80;function I(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)??L(e.beforeInstallApps,e.afterInstallApps)}function L(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>R(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function R(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}function z(e,n){throw new t(`UNSUPPORTED_OPERATION`,n,{command:e})}function B(e){return e.platform===`android`?V(e):H(e)}function V(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async n=>await e.dependencies.android.listApps(t,r(n)),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),...U(e.client,e.token,e.dependencies.host),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function H(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=>r(t)===`all`||R(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),...U(e.client,e.token,e.dependencies.host),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function U(e,t,n){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async()=>({downloadUrl:await e.stopRecording({})}),downloadRecording:async e=>{await n.downloadFile({url:e.downloadUrl,headers:{Authorization:`Bearer ${t}`},destinationPath:e.outPath,timeoutMs:6e4})}}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,B as t};
@@ -1 +0,0 @@
1
- import{createHash as e}from"node:crypto";const t=`limrun`,n={provider:t,label:`Limrun`,fields:{providerApp:`consumed`,providerOsVersion:`refused`,providerProject:`refused`,providerBuild:`refused`,providerSessionName:`refused`,providerDeviceOrientation:`refused`,providerGeoLocation:`refused`,providerTimezone:`refused`,providerAppiumVersion:`refused`,providerLanguage:`refused`,providerLocale:`refused`,providerNetworkProfile:`refused`,providerCustomNetwork:`refused`,providerNoResignApp:`refused`,awsProjectArn:`refused`,awsDeviceArn:`refused`,awsAppArn:`refused`,awsRegion:`refused`,awsInteractionMode:`refused`}},r=t;function i(e){if(e===`ios-instance`)return`ios`;if(e===`android-instance`)return`android`}function a(e,t,n){return{platform:e===`ios`?`apple`:`android`,...e===`ios`?{appleOs:`ios`}:{},id:c(e,t.leaseId),name:`Limrun ${e} ${n.slice(0,8)}`,kind:e===`ios`?`simulator`:`emulator`,target:`mobile`,booted:!0}}function o(t){return`attached-${e(`sha256`).update(t).digest(`hex`).slice(0,12)}`}function s(e){let[t,n,i]=e.split(`:`);if(t===r&&(n===`ios`||n===`android`)&&i)return{platform:n,leaseId:i}}function c(e,t){return`${r}:${e}:${t}`}function l(e){let t=s(e.id);return!t||e.target!==`mobile`?!1:t.platform===`ios`?u(e):d(e)}function u(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&e.iosPhysicalDeviceBackend===void 0}function d(e){return e.platform===`android`&&e.appleOs===void 0&&e.kind===`emulator`&&e.iosPhysicalDeviceBackend===void 0}export{l as a,a as i,t as n,s as o,o as r,i as s,n as t};
@@ -1,3 +0,0 @@
1
- import{P as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{s as n}from"./device-shell.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
- `)}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
- `)}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,4 +0,0 @@
1
- import{P as e,it as t}from"./sdk-contracts.js";import{v as n}from"./sdk-batch-runner.js";import{a as r,c as i,r as a}from"./diagnostics.js";import"./diagnostics2.js";import{E as o,a as s,d as c,i as l,l as ee,n as te,w as ne}from"./sdk-device.js";import{$n as re,S as ie,er as ae,ln as u,m as oe,sn as se}from"./sdk-batch.js";import{t as ce}from"./recording-scope.js";import{a as le}from"./scroll-gesture.js";import{_ as d,c as ue,d as de,g as fe,h as pe,i as me,l as he,m as ge,o as _e,p as f,s as ve,u as p,y as ye}from"./script.js";import{C as be,D as xe,E as Se,F as Ce,M as we,O as Te,P as Ee,S as De,T as Oe,a as ke,b as Ae,d as je,i as Me,j as Ne,k as Pe,l as Fe,o as Ie,r as Le,s as Re,v as m,w as h,x as ze,y as Be}from"./provider-device-admission.js";import{n as g,t as _}from"./catalog.js";import{o as Ve,t as v}from"./back-mode.js";import{t as He}from"./session.js";import{r as Ue}from"./success-text.js";import{t as We}from"./click-button.js";import"./device.js";import{r as Ge,t as Ke}from"./device-rotation.js";import{j as qe}from"./owner-identity.js";import"./file.js";import{t as Je}from"./tv-remote.js";import{n as Ye,r as Xe,t as Ze}from"./session-paths.js";import{i as Qe,n as $e,r as et}from"./session-artifact-paths.js";import{i as tt,r as nt,t as rt}from"./session-repair-tombstone.js";import{t as it}from"./keyboard-actions.js";import{n as at,r as ot}from"./device-isolation.js";import{a as st,i as ct,r as lt}from"./device-inventory-context.js";import{AsyncLocalStorage as ut}from"node:async_hooks";import{createHash as dt}from"node:crypto";import y from"node:fs";import b from"node:path";import{StringDecoder as ft}from"node:string_decoder";function pt(e,t={}){let n=[e.command];return e.command===`snapshot`?de(n,e):e.command===`open`?me(n,e):e.command===`runtime`?ue(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?ve(n,e):e.command===`screenshot`?he(n,e):_e(n,e),n.join(` `)}function mt(e){return e.targetEvidences?[re(e.targetEvidences)]:e.targetEvidence?[ae(e.targetEvidence)]:[]}function x(e){return e?.scriptPublication??m}function ht(e,t){let n=x(e),r=typeof t.saveScript==`string`?Ze(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Ae(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function gt(e){e.scriptPublication=De(x(e))}function _t(e){e.scriptPublication=Se(x(e))}function vt(e,t){e.scriptPublication=xe(x(e),t)}function yt(e){e.scriptPublication=Be(x(e))}function bt(e,t){let n=x(e);return n.kind===`repair`&&n.closeReceipt===t}function xt(e){return x(e).kind===`repair`}function St(e){return Oe(x(e))}function S(e){return Te(x(e))}function Ct(e){return Pe(x(e))}function wt(e,t){if(t.flags?.noRecord||Pt(e,t))return;t.flags&&Fe(e,t.flags);let n=Et(t),r=kt(e,Dt(t,n));n&&Ot(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:It(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),a({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function Tt(e,t,n,r,i,a){!t||!e.resolveCurrent(t)||e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function Et(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=Ce(e.flags.recordAs),n=Ee(t);return{literal:we({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function Dt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:jt(e.positionals,r),result:Le(e.result,n,r),targetEvidence:Me(e.targetEvidence,n,r)}}function Ot(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function kt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=ke(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?At(t.targetEvidence,n):C(t.targetEvidence,n),a=t.targetEvidences?{source:C(t.targetEvidences.source,n),destination:C(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function At(e,t){return e&&(Re(e,t)?void 0:e)}function C(e,t){return!e||!Re(e,t)?e:{...Ie(e,t),verification:`unverifiable`}}function jt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const Mt=new Set([`snapshot`,`get`,`is`,`find`]);function Nt(e){return e.internal?.replayPlanStep!==!0&&Mt.has(e.command)}function Pt(e,t){return!t.interactiveObservation||S(e)===void 0?!1:t.flags?.record!==!0}const Ft=Ve();function It(e){if(!e)return{};let t={};for(let n of Ft){let r=e[n];r!==void 0&&(t[n]=r)}return t}function w(e){return b.join(e,`idle-expiry.json`)}function Lt(e){let t;try{t=y.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||!Number.isFinite(n.expiresAt))&&!(n.expiresAt<=Date.now())&&typeof n.owner==`string`&&!(!Rt(n.expiredAtMs)||!Rt(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function Rt(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function zt(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())ie({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Gt))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Bt(t){for(let n of t){if(Vt(n)){Ht(n);continue}let t=Kt(n),r=t??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&ie(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=t;if(!(!i||!u(i)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function Vt(e){return Ut(e)!==void 0}function Ht(t){let n=Ut(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!u(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Ut(e){return e.command===`gesture`?ye(e.positionals):void 0}function Wt(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Gt(e){if(e.command!==`wait`)return!1;let t=se(e.positionals);return t?.kind!==`selector`||!u(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Kt(e){if(e.command===`get`)return e.positionals[1];if(fe(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&qt(t)&&qt(n)?void 0:t}}function qt(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Jt(e){let t=e.scriptPublication??m;return t.kind===`repair`?t.status===`committed`||!h(t):!1}function Yt(e){return!be(e.scriptPublication??m)||Jt(e)}var Xt=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=xt(e),r=t?.publication===`active`,i;try{if(Yt(e))return{written:!1};let a=Zt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=b.dirname(i);return y.existsSync(o)||y.mkdirSync(o,{recursive:!0}),en({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=ze(e.scriptPublication??m)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Qt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Ne(e.scriptPublication??m);if(t)return Ze(t);let n=Xe(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return b.join(this.sessionsDir,`${n}-${r}.ad`)}};function Zt(e,t){let n=tn(e,{strictPortableRefs:t.activePublication});return t.activePublication&&zt(n),{script:fn(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Qt(t){let{session:n,error:r,scriptPath:i,repairArmed:o,activePublication:s}=t;if(a({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),o)return{written:!1,error:$t(r,i)};if(s)return{written:!1,error:Wt(r,i)};if(r instanceof e)throw r;return{written:!1}}function $t(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function en(t){let{scriptPath:n,script:r,force:i}=t;try{qe({destination:n,contents:r,publish:i?`replace`:`link-exclusive`})}catch(t){throw t.code===`EEXIST`?new e(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):t}}function tn(e,t={}){let n=S(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=an(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&nn(n);let o=dn(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Bt(a),a}function nn(t){let n=t.command===`gesture`?ye(t.positionals??[]):void 0;if(n){rn(n);return}if(!T(t.command))return;let r=t.command===`get`?t.positionals?.[1]:t.positionals?.[0];if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot write recorded step "${t.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function rn(t){let n=[t.source,t.destination].find(e=>e.startsWith(`@`));if(n)throw new e(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function an(e){let t=on(e);if(!(!t||!T(e.command)))return pe(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?cn(e,t):e.command===`fill`?sn(e,t):ln(e,t)}function on(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function T(e){return fe(e)||e===`fill`||e===`get`}function sn(e,t){let n=we(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function cn(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):un(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function ln(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function un(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function dn(e,t){if(!T(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function fn(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${ne(e.device)} device=${ge(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...mt(e)),r.push(pn(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
- `)}\n`}function pn(e){return mn([e.command],e)||pt(e)}function mn(e,t){if(pe(t.command))return hn(e,t);if(t.command===`fill`)return gn(e,t);if(t.command===`get`)return _n(e,t)}function hn(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(f(d(n))),E(e,t),p(e,t),e.join(` `);if(t.positionals.length===1)return e.push(f(n)),p(e,t),e.join(` `)}}function gn(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(f(d(n))),E(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(f(r)),p(e,t),e.join(` `)}function _n(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(f(n)),e.push(f(d(r))),r.startsWith(`@`)&&E(e,t),e.join(` `)}function E(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(f(n))}const vn=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],yn={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function bn(e,t){let n=t??{};switch(e.command){case g.devices:return xn(n.devices);case g.apps:return Sn(n.apps,e.flags?.appsFilter);case g.boot:return Cn(`Booted`,n,!0);case g.shutdown:return Cn(`Shut down`,n,!1);case g.install:return wn(`Installed`,n);case g.reinstall:return wn(`Reinstalled`,n);case g.screenshot:return Tn(e,n);default:return{}}}function xn(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Dn(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:In(`Found ${t.length} ${Ln(`device`,t.length)}`,i.map(e=>Pn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Sn(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=k(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:In(`Found ${n.length} ${Ln(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function Cn(e,t,n){let r=On(t);if(!r)return{};let i={device:r,...Nn(t),booted:n};return{summary:`${e} ${Pn(i,!1)}`,details:i}}function wn(e,t){let n=k(t.appName),r=k(t.bundleId),i=D(t,[`packageName`,`package`]),a=k(t.platform),o=k(t.launchTarget),s=D(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Fn(n,s);if(!c)return{};let l={};return O(l,`appName`,n),O(l,`bundleId`,r),O(l,`packageName`,i),O(l,`platform`,a),o!==s&&O(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Tn(e,t){let n=En(e,t);return n?{details:{requestedFileName:n}}:{}}function En(e,t){let n=F(e.meta?.clientArtifactPaths?.path)??F(t.path);if(n)return P(n)}function Dn(e){if(!n(e))return;let t=On(e);if(t)return{name:t,...Nn(e)}}function On(e){let t=D(e,[`name`,`deviceName`,`device`]);return!t||!kn(e,t)?t:jn(e)}function kn(e,t){let n=An(t);return vn.some(t=>{let r=k(e[t]);return r!==void 0&&An(r)===n})}function An(e){return e.toLowerCase()}function jn(e){let t=k(e.appleOs),n=k(e.platform),r=k(e.kind),i=Mn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Mn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(yn,n)))return yn[n]}function Nn(e){let t=k(e.platform),n=k(e.appleOs),r=k(e.kind),i=k(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Pn(e,t){let n=k(e.name)??k(e.device)??`device`,r=k(e.platform),i=k(e.appleOs),a=[r,i===r?void 0:i,k(e.kind),k(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Fn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function D(e,t){for(let n of t){let t=k(e[n]);if(t)return t}}function O(e,t,n){n&&(e[t]=n)}function In(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Ln(e,t){return t===1?e:`${e}s`}function k(e){let t=F(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function A(e){return k(e)}function j(e){return typeof e==`boolean`?e:void 0}function M(e,t){let n=A(e);return n&&t.includes(n)?n:void 0}function N(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function P(e){let t=F(e);return t?k(t.split(/[\\/]/).at(-1)):void 0}function F(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function I(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Rn=[`up`,`down`,`left`,`right`],zn=[`top`,`bottom`];function Bn(e){return`${e.command===g.reinstall?`Reinstalled`:`Installed`} ${Wn(e.result??{})??`app`}`}function Vn(e){let t=e.result??{};switch(e.command){case g.scroll:return Kn(t);case g.screenshot:return Yn(t);case g.home:return`Went home`;case g.back:return Zn(t);case g.appSwitcher:return`Opened app switcher`;case g.actionButton:return`Pressed Action Button`;case g.orientation:return $n(t);case g.fold:return Qn(t);case g.viewport:return er(t);case g.clipboard:return tr(t);case g.keyboard:return nr(t);case g.tvRemote:return ar(t);case g.gesture:return or(t);case g.swipe:return sr(t);case g.trace:return lr(`trace`,e);case g.record:return lr(`recording`,e);default:return}}function Hn(e){let t=e.result??{};switch(e.command){case g.scroll:return N({direction:M(t.direction,Rn),edge:M(t.edge,zn),passes:I(t.passes),amount:I(t.amount),pixels:I(t.pixels),durationMs:I(t.durationMs),x1:I(t.x1),y1:I(t.y1),x2:I(t.x2),y2:I(t.y2)});case g.screenshot:return N({requestedFileName:Xn(t)});case g.back:return N({mode:M(t.mode,v)});case g.orientation:return N({orientation:M(t.orientation,Ke)});case g.fold:return N({pose:M(t.pose,Ge)});case g.viewport:return N({width:I(t.width),height:I(t.height)});case g.clipboard:return N({action:M(t.action,[`read`,`write`])});case g.keyboard:return ir(t);case g.tvRemote:return N({button:M(t.button,Je),durationMs:I(t.durationMs)});case g.gesture:case g.swipe:return cr(t);case g.trace:case g.record:return N({action:M(t.action,[`start`,`stop`]),fileName:dr(e),showTouches:j(t.showTouches)});default:return{}}}function Un(e,t){if(e.command!==g.screenshot)return t;let n=En(e,t);return n?{...t,requestedFileName:n}:t}function Wn(e){let t=A(e.appName),n=fr(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Gn(e)}function Gn(e){let t=A(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Kn(e){let t=M(e.direction,Rn),n=M(e.edge,zn),r=I(e.passes);return n?qn(n,r):t?Jn(t,e):`Scrolled`}function qn(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Jn(e,t){let n=I(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=I(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Yn(e){let t=Xn(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function Xn(e){return P(e.requestedFileName)??P(e.path)}function Zn(e){return M(e.mode,v)===`system`?`Went back using system navigation`:`Went back`}function Qn(e){let t=M(e.pose,Ge);return t?`Folded to ${t}`:`Changed fold pose`}function $n(e){let t=M(e.orientation,Ke);return t?j(e.confirmed)===!1?`Requested ${t} (unconfirmed)`:`Rotated to ${t}`:`Changed orientation`}function er(e){let t=I(e.width),n=I(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function tr(e){let t=M(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function nr(e){let t=F(e.action);if(!t||!it(t))return`Used keyboard`;if(t===`dismiss`)return rr(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=j(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function rr(e){return j(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function ir(e){let t=F(e.action);return N({action:t&&it(t)?t:void 0,platform:M(e.platform,[`ios`,`android`]),visible:j(e.visible),wasVisible:j(e.wasVisible),dismissed:j(e.dismissed),attempts:I(e.attempts),mechanism:M(e.mechanism,[`dismissKey`])})}function ar(e){let t=M(e.button,Je);return t?`Pressed TV remote ${t}`:`Used TV remote`}function or(e){let t=M(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function sr(e){let t=I(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function cr(e){return N({kind:M(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:I(e.durationMs),pointerCount:I(e.pointerCount),x1:I(e.x1),y1:I(e.y1),x2:I(e.x2),y2:I(e.y2),count:I(e.count),pauseMs:I(e.pauseMs),pattern:M(e.pattern,[`one-way`,`ping-pong`]),scale:I(e.scale)})}function lr(e,t){let n=ur(e,M(t.result?.action,[`start`,`stop`])),r=dr(t);return r?`${n} ${r}`:n}function ur(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function dr(e){let t=e.result??{};return P(t.requestedFileName)??P(t.outPath)??P(t.path)??P(e.positionals[1])}function fr(e,t){for(let n of t){let t=A(e[n]);if(t)return t}}function pr(e){switch(e.command){case g.open:return`Opened ${L(e)??`session`}`;case g.close:return`Closed ${A(e.result?.session)??`session`}`;case g.click:case g.press:return`Tapped ${L(e)??`target`}`;case g.longPress:return`Long pressed ${L(e)??`target`}`;case g.hover:return`Hovered ${L(e)??`target`}`;case g.fill:return`Filled ${L(e)??`target`}`;case g.type:return`Typed text`;case g.install:case g.reinstall:case _.installSource:return Bn(e);default:return Vn(e)??`Ran ${e.command}`}}function mr(e){return N({command:e.command,positionals:Cr(e),flags:Fr(e),...hr(e),...gr(e),..._r(e),...Hn(e)})}function hr(e){if(!vr(e.command))return{};let t=e.result??{};return N({ref:H(t),targetLabel:L(e),selectorChainLength:jr(t.selectorChain)?.length,x:I(t.x),y:I(t.y),x2:I(t.x2),y2:I(t.y2),durationMs:I(t.durationMs)})}function gr(e){if(!yr(e.command))return{};let t=e.result??{};return N({platform:M(t.platform,s),target:M(t.target,te),appName:A(t.appName),appBundleId:A(t.appBundleId),bundleId:A(t.bundleId),packageName:A(t.packageName),launchTarget:A(t.launchTarget)})}function _r(e){let t=e.result??{};return e.command===g.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==g.wait&&e.command!==g.find&&e.command!==g.get&&e.command!==g.is?{}:N({waitedMs:I(t.waitedMs),found:j(t.found)})}function vr(e){return e===g.click||e===g.press||e===g.longPress||e===g.hover||e===g.focus||e===g.fill}function yr(e){return e===g.open||e===g.install||e===g.reinstall||e===_.installSource}function L(e){let t=e.result??{};return br(t)??xr(t)??Sr(t)??kr(e.positionals[0])}function br(e){let t=H(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function xr(e){let t=I(e.x),n=I(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Sr(e){return A(e.appName)??A(e.appBundleId)??A(e.bundleId)??A(e.packageName)}function Cr(e){if(e.positionals.length!==0)return e.command===g.type?[z(`text`)]:e.command===g.fill?wr(e):e.command===g.find?Tr(e):e.command===g.clipboard?Er(e):e.command===g.push?Dr(e,`app`,`payload`):e.command===g.triggerAppEvent?Dr(e,`event`,`payload`):e.positionals.map(R)}function wr(e){let t=z(`text`),n=e.result??{},r=H(n);if(r)return[`@${r}`,t];if(A(n.selector))return[z(`target`),t];let i=I(n.x),a=I(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Tr(e){let t=+!!Ar(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],z(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,z(`text`)]:[...r,...e.positionals.slice(n).map(Or)]:r}function Er(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,z(`text`)]:e.positionals.map(R)}function Dr(e,t,n){let[r,i,...a]=e.positionals;return[...r?[z(t)]:[],...i?[z(n)]:[],...a.map(R)]}function Or(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:R(e)}function R(e){return kr(e)??z(`arg`)}function kr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function z(e){return`<${e}>`}function Ar(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function jr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Mr={enums:[{source:`platform`,values:l},{source:`target`,values:te}]},Nr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},Pr={[g.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:He}]},[g.click]:B(),[g.press]:B(),[g.longPress]:B(),[g.hover]:B(),[g.fill]:Lr(),[g.type]:Lr(),[g.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[g.gesture]:Rr(),[g.swipe]:Rr(),[g.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[g.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[g.back]:{enums:[{source:`backMode`,output:`mode`,values:v}]},[g.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:ce}]},[g.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[g.boot]:{booleans:[{source:`headless`}]},[g.close]:{booleans:[{source:`shutdown`}]}};function Fr(e){let t=e.flags??{},n={},r=Object.hasOwn(Pr,e.command)?Pr[e.command]:void 0;return V(n,t,Mr),V(n,t,r),V(n,t,Ir(e.command)),Object.keys(n).length>0?n:void 0}function Ir(e){return oe(e)?Nr:void 0}function B(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:We}]}}function Lr(){return{numbers:[{source:`delayMs`}]}}function Rr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:le}]}}function V(e,t,n){n&&(zr(e,t,n.booleans??[]),Br(e,t,n.numbers??[]),Vr(e,t,n.enums??[]))}function zr(e,t,n){for(let r of n)Hr(e,r.output??r.source,t[r.source])}function Br(e,t,n){for(let r of n)Ur(e,r.output??r.source,t[r.source])}function Vr(e,t,n){for(let r of n)Wr(e,r.output??r.source,t[r.source],r.values)}function H(e){let t=A(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Hr(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Ur(e,t,n){let r=I(n);r!==void 0&&(e[t]=r)}function Wr(e,t,n,r){let i=M(n,r);i!==void 0&&(e[t]=i)}const Gr=65536;function Kr(e){return dt(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function U(e,t){let n=Xr(e);if(n===void 0)return!1;try{let e=Jr(t),r=Buffer.allocUnsafe(Gr),i=0;do if(i=y.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{y.closeSync(n)}}async function qr(e){let t=await Zr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=Jr(e=>{n.lineCount===0&&(n.firstLineDigest=Kr(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Gr);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function W(e){let t;return U(e,e=>(t=Kr(e),!1)),t}function Jr(e){let t=new ft(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
3
- `);t!==-1;t=a.indexOf(`
4
- `,o)){if(Yr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||Yr(`${n}${t.end()}`,e)}}}function Yr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Xr(e){try{return y.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Zr(e){try{return await y.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Qr=5242880;function $r(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Qr;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Qr}function G(e){return`${e}.1`}function K(e){return`${e}.window.json`}function ei(e){let t;for(let n=0;n<3;n+=1){let n=J(e);try{let t=ti(e);if(J(e)===n)return t}catch(r){if(t=r,J(e)===n)throw r}}throw t??q(e,`the window did not settle while reading`)}function ti(e){let t=G(e),n=X(e);if(n===`unverifiable`)throw q(e,`window file is invalid`);if(n===void 0)return ni(e,t);let r=n.at(-1);if(!r)throw q(e,`window file records no generation`);let i=ui(e),a=ri(e,r),o=[],s=ii({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function ni(e,t){if(W(t)!==void 0)throw q(e,`a rotated event log exists with no window record`);return{files:ui(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function ri(e,t){let n=W(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function ii(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=W(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw q(t,`the rotated event log matches no window record`);let c=si(n);if(c!==s.lineCount)throw q(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw q(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function ai(e,t){let n=di(e);if(!n||n.size<t)return!1;let r=X(e);if(r===`unverifiable`)return await y.promises.rename(e,G(e)),!0;let i=await qr(e);if(i.firstLineDigest!==void 0){let t=r??[],n=t.at(-1),a=n&&n.firstLineDigest===i.firstLineDigest?n:{firstLineIndex:n?n.firstLineIndex+n.lineCount:0,lineCount:i.lineCount,firstLineDigest:i.firstLineDigest};await li(e,(a===n?t:[...t,a]).slice(-2))}return await y.promises.rename(e,G(e)),!0}function oi(t,n){if(!(t>=n))throw new e(`COMMAND_FAILED`,`events cursor ${t} precedes the retained event log window; events before cursor ${n} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:t,earliestCursor:n,hint:`Resume with cursor ${n}, the oldest retained event; earlier events are no longer available.`})}function q(t,n){return new e(`COMMAND_FAILED`,`Session event log window cannot be verified: ${n}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:t,hint:`Cursor positions for this session cannot be resolved. Delete ${t}, ${G(t)}, and ${K(t)} to restart the timeline, or read the files directly.`})}function si(e){let t=0;return U(e,()=>{t+=1}),t}function J(e){return[Y(K(e)),Y(e),Y(G(e))].join(`|`)}function Y(e){try{let t=y.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function X(e){let t;try{t=y.readFileSync(K(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!n(e)||e.version!==2)return`unverifiable`;let{generations:r}=e;if(!Array.isArray(r)||r.length===0)return`unverifiable`;let i=r.map(ci);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function ci(e){if(!n(e))return;let{firstLineIndex:t,lineCount:r,firstLineDigest:i}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(r)||r<0)&&typeof i==`string`&&i.length!==0)return{firstLineIndex:t,lineCount:r,firstLineDigest:i}}async function li(e,t){let n=K(e),r=`${n}.${process.pid}.tmp`;await y.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await y.promises.rename(r,n)}function ui(e){return di(e)!==void 0}function di(t){try{let n=y.lstatSync(t);if(n.isSymbolicLink())throw new e(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${t}`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}const Z=new Map,fi=new Set;function pi(e){return b.join(e,`events.ndjson`)}function mi(e){return e.command!==g.events}function hi(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});_i(e,`${JSON.stringify(i)}\n`)}async function gi(e){await(e?Z.get(e):Promise.all(Z.values()))}function _i(e,t){let n=(Z.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await vi(e),await ai(e,$r()),await y.promises.appendFile(e,t,`utf8`)}).catch(t=>{a({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{Z.get(e)===n&&Z.delete(e)});Z.set(e,n)}async function vi(e){let t=b.dirname(e);if(!fi.has(t))try{await y.promises.mkdir(t,{recursive:!0}),fi.add(t)}catch(t){throw a({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function yi(e,t,n){hi(e,t,{kind:`action.recorded`,requestId:r().requestId,command:n.command,summary:pr(n),details:mr(n)})}function bi(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??r().requestId,command:t.command,summary:`Started ${t.command}`}}function xi(e){let{req:t,response:n,durationMs:i}=e;if(n.ok){let e=bn(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??r().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:i,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??r().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:i,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function Si(e,t={}){let n=wi(t.cursor),r=Ti(t.limit),i=ei(e);oi(n,i.earliestCursor);let a=Ci(i.files,n,r),o=a.lines.flatMap(e=>{let t=Ei(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function Ci(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(U(a.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),i!==void 0)break}return{lines:r,...i===void 0?{}:{nextCursor:i}}}function wi(t){if(t===void 0||t.trim()===``)return 0;let n=Number(t);if(Number.isInteger(n)&&n>=0)return n;throw new e(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function Ti(t){if(t===void 0||typeof t==`string`&&t.trim()===``)return 100;let n=typeof t==`string`?Number(t):t;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new e(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function Ei(e){try{let t=Di(JSON.parse(e));return t?Oi(t):void 0}catch{return}}function Di(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&ki(e.kind))return e}function Oi(e){let t=n(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...Ai(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ki(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function Ai(e){return e===`ok`||e===`error`}const ji=36e5;var Mi=class{sessions=new Map;acceptingSessions=!0;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new Xt(e)}get(e){return this.sessions.get(e)?.current}closeAdmission(){this.acceptingSessions=!1}assertAdmissionOpen(t){if(!this.acceptingSessions)throw new e(`COMMAND_FAILED`,`Daemon is shutting down`,{reason:`daemon_shutting_down`,session:t})}assertPublishable(t){if(this.assertAdmissionOpen(t),this.sessions.has(t))throw new e(`COMMAND_FAILED`,`Session address is already occupied`,{reason:`session_address_occupied`,session:t})}publish(e,t){this.assertPublishable(e);let n={current:t};return this.sessions.set(e,n),this.clearIdleExpiryTombstone(e),this.captureRef(e,n)}resolveCurrent(e){let t=this.sessions.get(e.address);return t===e.lifetime?t.current:void 0}refresh(e){let t=this.sessions.get(e.address);return t===e.lifetime?this.captureRef(e.address,t):e}requireCurrent(t){let n=this.resolveCurrent(t);if(!n)throw new e(`COMMAND_FAILED`,`Session lifetime has ended`,{reason:`session_lifetime_ended`,session:t.address,hint:`Open a new session before retrying the command.`});return n}update(e,t){let n=this.requireCurrent(e),r=this.sessions.get(e.address),i=typeof t==`function`?t(n):t,a={...n,...i};return r.current=a,a}retire(e){return this.resolveCurrent(e)?(this.runtimeHints.delete(e.address),this.sessions.delete(e.address)):!1}captureRef(e,t){return Object.freeze({address:e,session:t.current,lifetime:t})}*values(){for(let e of this.sessions.values())yield e.current}toArray(){return Array.from(this.values())}lookup(e){let t=this.sessions.get(e);return t?this.captureRef(e,t):void 0}findByDevice(e){for(let[t,n]of this.sessions)if(n.current.device.id===e)return this.captureRef(t,n)}listRefs(){return Array.from(this.sessions,([e,t])=>this.captureRef(e,t))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){t?this.runtimeHints.set(e,t):this.runtimeHints.delete(e)}clearRuntimeHints(e){return this.requireCurrent(e),this.runtimeHints.delete(e.address)}recordAction(e,t){let n=wt(this.requireCurrent(e),t);n&&yi(this.resolveEventLogPath(e.address),e.address,n)}recordEvent(e,t){hi(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return Si(this.resolveEventLogPath(e),t)}async flushEvents(e){await gi(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.requireCurrent(e),r=this.scriptWriter.write(n,t);return r.written&&a({level:`info`,phase:`session_script_written`,data:{session:n.name,path:r.path}}),r}finalizeRepairTeardown(e){let t=this.resolveCurrent(e);if(!t)return;this.recordRepairFinalizeCloseIfCommitting(e);let n=this.writeSessionLog(e,{force:je(t,void 0)});St(t)&&(!n.written&&n.error?this.writeRepairTombstone(e,ji,{code:String(n.error.code),message:n.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=this.requireCurrent(e),n=t.scriptPublication??m;h(n)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:t.name,...Ue(`Closed: ${t.name}`)}})}writeRepairTombstone(e,t=ji,n){let r=this.resolveCurrent(e);if(r)try{let i=this.resolveSessionDir(e.address);y.mkdirSync(i,{recursive:!0});let a={owner:e.address,reapedAt:Date.now(),expiresAt:Date.now()+t,...Ct(r)?{sourcePath:Ct(r)}:{},...n?{commitFailure:n}:{}};y.writeFileSync(this.repairTombstonePath(e.address),`${JSON.stringify(a)}\n`)}catch(t){a({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.address,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return nt(this.repairTombstonePath(e),e)}clearRepairTombstone(e){rt(this.repairTombstonePath(e),e)}noteSessionActivity(e,t=Date.now()){let n=this.get(e);n&&(n.lastActivityAtMs=t)}writeIdleExpiryTombstone(e,t){try{y.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),y.writeFileSync(w(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){a({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Ye(e))return;let t=Lt(w(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{y.rmSync(w(this.resolveSessionDir(e)),{force:!0})}catch(t){a({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return tt(this.resolveSessionDir(e))}defaultTracePath(e){let t=Xe(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return b.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return Qe(this.sessionsDir,e)}resolveDaemonStateDir(){return b.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return y.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return $e(this.sessionsDir,e)}resolveAppLogPidPath(e){return et(this.sessionsDir,e)}resolveEventLogPath(e){return pi(this.resolveSessionDir(e))}};async function Q(e){let{resolveInventoryDeviceSelection:t}=await import(`./device-selection-resolver.js`).then(e=>e.t);return await t(e)}const $=new ut;function Ni(t,n){return!ee(n)&&t instanceof e&&t.code===`DEVICE_NOT_FOUND`}function Pi(e,t){return!ee(e)&&(!e.platform||e.platform===`apple`||e.platform===`ios`)&&e.target!==`desktop`&&(!t||t.kind===`device`)}async function Fi(e,t={}){return(await Ii(e,t)).device}async function Ii(e,t={}){let n={...zi(e),androidAvdSelection:t.androidAvdSelection??`running-only`},{iosSimulatorSetPath:r,...a}=n,o=Ui(n,t),s={platform:n.platform,target:e.target,cacheHit:!1};return await i(`resolve_target_device`,async()=>{let e=Vi(o);if(e)return s.cacheHit=!0,e;let i=await ct(n),l=[...i.devices];if(c(a.platform)&&i.source===`local`){let e=await Li(l,a,{simulatorSetPath:r,appleSimulatorAppTarget:t.appleSimulatorAppTarget});return Hi(o,e)}return Hi(o,await Q({devices:l,selector:a,source:i.source}))},s)}async function Li(t,n,r){let i;try{i=await Q({devices:t,selector:n,source:`local`,appleSimulatorAppTarget:r.appleSimulatorAppTarget})}catch(e){if(!Ni(e,n))throw e}let a=await Ri(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 Ri(e,t,n){if(Pi(e,n))try{return await Q({devices:await lt({platform:e.platform??`ios`,target:e.target,iosSimulatorSetPath:t.simulatorSetPath,kind:`simulator`}),selector:e,source:`local`})}catch(e){if(st(e))throw e;return}}function zi(t){let n=t.platform;if(t.target&&!n)throw new e(`INVALID_ARGS`,`Device target selector requires --platform. Use --platform ios|macos|android|vega|linux|apple with --target mobile|tv|desktop.`);let r=o({simulatorSetPath:ot(t.iosSimulatorDeviceSet),platform:n,target:t.target}),i=at(t.androidDeviceAllowlist);return{platform:n,target:t.target,deviceName:t.device,udid:t.udid,serial:t.serial,leaseId:t.leaseId,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId,iosSimulatorSetPath:r,androidSerialAllowlist:i?Array.from(i).sort():void 0}}async function Bi(e){return $.getStore()?await e():await $.run(new Map,e)}function Vi(e){let t=$.getStore()?.get(e);if(t)return{...t,device:{...t.device}}}function Hi(e,t){return $.getStore()?.set(e,{...t,device:{...t.device}}),t}function Ui(e,t){let{appleSimulatorAppTarget:n,...r}=t;return JSON.stringify({request:e,options:r})}export{St as _,Mi as a,S as b,mi as c,Nt as d,Tt as f,xt as g,bt as h,Bi as i,Cr as l,ht as m,Fi as n,xi as o,yt as p,Ii as r,bi as s,zi as t,Un as u,_t as v,gt as x,vt as y};
@@ -1 +0,0 @@
1
- import e from"node:path";function t(t){let n=e.extname(t).toLowerCase();return n===`.yaml`||n===`.yml`}function n(e,t){return`Maestro YAML requires explicit --maestro routing: ${e} ${t} --maestro`}function r(e,n){return n===`maestro`&&t(e)?`maestro`:`ad`}export{n,r,t};
@@ -1 +0,0 @@
1
- const e=1e4;export{e as t};
package/dist/src/host.js DELETED
@@ -1 +0,0 @@
1
- let e;function t(t){if(e&&e!==t)throw Error(`Apple runner host is already bound to a different implementation.`);e=t}function n(){if(!e)throw Error(`Apple runner host is not bound. Production binds it in core/runner-client.ts; package tests bind it through runner/test-host.ts.`);return e}function r(e){return((...t)=>n()[e](...t))}const i=r(`runCmdStreaming`),a=r(`runCmdSync`),o=r(`runCmdBackground`),s=r(`requireExecSuccess`),c=r(`isCommandTimeoutError`),l=r(`commandDeveloperDir`),u=r(`shellQuote`),d=r(`emitDiagnostic`),f=r(`withDiagnosticTimer`),p=r(`retryWithPolicy`),m=r(`isEnvTruthy`),h=r(`isProcessAlive`),g=r(`isProcessGroupAlive`),_=r(`readProcessStartTime`),v=r(`readProcessCommand`),y=r(`signalPidsBestEffort`),b=r(`signalProcessGroupBestEffort`),x=r(`classifyOwnerLiveness`),S=r(`readHostCpuArchSync`),C=r(`findProjectRoot`),w=r(`readVersion`),T=r(`acquireProcessLock`),E=r(`withProcessLock`),D=r(`publishFileSync`),O=r(`emitRequestProgress`),k=r(`getRequestSignal`),A=r(`isRequestCanceled`),j=r(`withKeyedLock`),M=r(`createTtlMemo`),N=r(`isRecord`),P=r(`parseBooleanLiteral`),F=r(`classifyBootFailure`),I=r(`bootFailureHint`),L=r(`runAppleToolCommand`),R=r(`runXcrun`),z=r(`readApplePlistJson`),B=r(`hasScopedAppleToolProvider`),V=r(`buildSimctlArgsForDevice`),H=r(`simulatorAddressFor`),U=r(`visitXmlPlistEntries`),W=r(`resolveIosPhysicalDeviceControl`),G=r(`leaseOwnerStateDir`),K=r(`hasDeviceClaimAuthority`),q={fromTimeoutMs:r(`deadlineFromTimeoutMs`)};export{s as A,b as B,P as C,v as D,S as E,i as F,E as G,U as H,a as I,R as L,p as M,L as N,_ as O,o as P,u as R,G as S,z as T,f as U,H as V,j as W,m as _,V as a,N as b,l as c,O as d,C as f,c as g,B as h,I as i,W as j,w as k,M as l,K as m,T as n,F as o,k as p,t as r,x as s,q as t,d as u,h as v,D as w,A as x,g as y,y as z};
@@ -1 +0,0 @@
1
- import{P as e}from"./sdk-contracts.js";import{f as t,g as n,m as r}from"./lease-registry-scope.js";const i=`/admin/human-control/holds`;function a(t){let n=s(t,`Human-control request body`),r=n.reason;if(r!==void 0&&(typeof r!=`string`||r.trim().length>512))throw new e(`INVALID_ARGS`,`Human-control reason must be at most 512 characters.`);let i=n.ttlMs;if(i!==void 0&&(typeof i!=`number`||!Number.isInteger(i)||i<1e3||i>864e5))throw new e(`INVALID_ARGS`,`Human-control ttlMs must be between 1000 and 86400000.`);return{...n.scope===void 0?{}:{scope:o(n.scope)},...typeof r==`string`&&r.trim()?{reason:r.trim()}:{},...typeof i==`number`?{ttlMs:i}:{}}}function o(i){let a=s(i,`Host human-control scope`);if(typeof a.backend!=`string`||!a.backend.trim()||typeof a.deviceKey!=`string`)throw new e(`INVALID_ARGS`,`Host human control requires scope.backend and scope.deviceKey.`);if(a.leaseProvider!==void 0&&typeof a.leaseProvider!=`string`)throw new e(`INVALID_ARGS`,`scope.leaseProvider must be a string.`);let o=n(a.leaseProvider);return{backend:r(a.backend),deviceKey:t(a.deviceKey),...o?{leaseProvider:o}:{}}}function s(t,n){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`${n} must be an object.`);return t}function c(t){let n=typeof t==`string`?t.trim():``;if(!/^[a-zA-Z0-9._-]{1,128}$/.test(n))throw new e(`INVALID_ARGS`,`Invalid human-control hold id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return n}function l(e){return{...e,scope:{...e.scope}}}function u(t){return new e(`DEVICE_IN_USE`,`A human is interacting with this simulator or device; agent interactions are temporarily disabled.`,{reason:`human_control_active`,blockedBy:`human_control`,holdId:t.id,deviceKey:t.scope.deviceKey,pausedAt:new Date(t.createdAt).toISOString(),...t.expiresAt===void 0?{}:{expiresAt:new Date(t.expiresAt).toISOString()},...t.reason?{humanReason:t.reason}:{},hint:`Wait until the human-control hold is released before retrying.`})}export{a,c as i,l as n,u as r,i as t};