agent-device 0.21.30 → 0.21.31

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 (304) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.30.apk → agent-device-android-ime-helper-0.21.31.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.31.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.30.manifest.json → agent-device-android-ime-helper-0.21.31.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.31.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.31.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.30.manifest.json → agent-device-android-snapshot-helper-0.21.31.manifest.json} +7 -7
  7. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift +20 -6
  8. package/apple/snapshot-bridge/README.md +16 -3
  9. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +33 -1
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +110 -8
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAppScreenCapture.swift +20 -0
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +4 -4
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +1 -1
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +30 -4
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +14 -4
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +81 -41
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +40 -6
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift +5 -0
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +74 -10
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +33 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +2 -2
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +23 -2
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +158 -6
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +165 -70
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +2 -3
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +49 -27
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +17 -9
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +30 -28
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +87 -87
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +4 -3
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.h +13 -0
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m +45 -0
  33. package/dist/src/absence-observation-errors.js +1 -1
  34. package/dist/src/adapter.js +1 -1
  35. package/dist/src/adb-executor.js +1 -1
  36. package/dist/src/adb-failure.js +2 -2
  37. package/dist/src/agent-browser-lifecycle.js +1 -1
  38. package/dist/src/agent-browser-process-record.js +1 -1
  39. package/dist/src/agent-browser-provider.js +1 -1
  40. package/dist/src/agent-browser-tool.js +1 -1
  41. package/dist/src/agent-device-client.js +1 -1
  42. package/dist/src/alert-tree-driver.js +1 -1
  43. package/dist/src/alert.js +1 -1
  44. package/dist/src/alert2.js +1 -1
  45. package/dist/src/android.js +1 -1
  46. package/dist/src/app-backend.js +1 -1
  47. package/dist/src/app-launch.js +1 -1
  48. package/dist/src/app-lifecycle.js +4 -4
  49. package/dist/src/app-log-runtime2.js +3 -3
  50. package/dist/src/app-log-session-resource.js +1 -1
  51. package/dist/src/app-resolution-facade.js +1 -1
  52. package/dist/src/app-resolution.js +2 -2
  53. package/dist/src/apple-runner-platform.js +1 -1
  54. package/dist/src/application-lifecycle-interaction.js +1 -1
  55. package/dist/src/artifact-tracking.js +1 -1
  56. package/dist/src/automation-helper-artifact.js +1 -1
  57. package/dist/src/automation-helper.js +1 -1
  58. package/dist/src/back-mode.js +1 -1
  59. package/dist/src/boot-diagnostics.js +1 -1
  60. package/dist/src/browser-launch.js +1 -1
  61. package/dist/src/cli-config.js +1 -1
  62. package/dist/src/cli-help.js +35 -29
  63. package/dist/src/cli-runner.js +1 -1
  64. package/dist/src/cli.js +3 -3
  65. package/dist/src/client-metro-companion.js +1 -1
  66. package/dist/src/client-metro.js +1 -1
  67. package/dist/src/client-types.d.ts +3 -3
  68. package/dist/src/cloud-artifacts.d.ts +5 -4
  69. package/dist/src/code-signature-cache.js +1 -1
  70. package/dist/src/command-metadata.js +10 -10
  71. package/dist/src/command-tools.js +2 -2
  72. package/dist/src/command.js +1 -1
  73. package/dist/src/composed-inventory-gateways.js +1 -1
  74. package/dist/src/connection-runtime.js +1 -1
  75. package/dist/src/connection.js +5 -5
  76. package/dist/src/contracts.js +1 -1
  77. package/dist/src/daemon-client-ensure.js +1 -1
  78. package/dist/src/daemon-client-lease-beat.js +1 -1
  79. package/dist/src/daemon-client-lifecycle.js +1 -1
  80. package/dist/src/daemon-client-liveness-probe.js +1 -1
  81. package/dist/src/daemon-client.js +1 -1
  82. package/dist/src/daemon-command-registry.js +1 -1
  83. package/dist/src/daemon-composition.js +1 -1
  84. package/dist/src/daemon-policy-file.js +1 -1
  85. package/dist/src/daemon-registration-owner.js +3 -3
  86. package/dist/src/daemon-resolution.js +1 -1
  87. package/dist/src/daemon-startup-diagnostics.js +1 -1
  88. package/dist/src/debug-symbols-facade.js +3 -3
  89. package/dist/src/device-claim-recovery.js +1 -1
  90. package/dist/src/device-claims.js +1 -1
  91. package/dist/src/device-inventory-context.js +1 -1
  92. package/dist/src/device-readiness-runtime.js +1 -1
  93. package/dist/src/device-selection-resolver.js +1 -1
  94. package/dist/src/device.js +1 -1
  95. package/dist/src/devicectl.js +1 -1
  96. package/dist/src/diagnostics.js +1 -1
  97. package/dist/src/display-inventory.js +1 -1
  98. package/dist/src/doctor-facade.js +1 -1
  99. package/dist/src/durable-capture-resource.js +1 -1
  100. package/dist/src/durable-resource.js +1 -1
  101. package/dist/src/engine-eval-script.js +1 -1
  102. package/dist/src/error.js +1 -1
  103. package/dist/src/explicit-session-resolution.js +1 -1
  104. package/dist/src/expo-dev-client-launch.js +1 -1
  105. package/dist/src/file.js +1 -1
  106. package/dist/src/find.js +1 -1
  107. package/dist/src/finders.js +1 -1
  108. package/dist/src/gesture-admission.js +1 -1
  109. package/dist/src/gesture-plan.js +1 -1
  110. package/dist/src/gesture-runtime.js +1 -1
  111. package/dist/src/hdc.js +1 -1
  112. package/dist/src/helper.js +2 -2
  113. package/dist/src/host.js +1 -1
  114. package/dist/src/host2.js +1 -1
  115. package/dist/src/host3.js +1 -1
  116. package/dist/src/host4.js +1 -1
  117. package/dist/src/host5.js +1 -0
  118. package/dist/src/human-control.js +1 -1
  119. package/dist/src/ime-rebind.js +1 -1
  120. package/dist/src/ime-state.js +1 -1
  121. package/dist/src/index.js +1 -1
  122. package/dist/src/input-actions.js +1 -1
  123. package/dist/src/input-actions2.js +1 -1
  124. package/dist/src/install-source-network-transport.js +1 -1
  125. package/dist/src/install-source2.js +1 -1
  126. package/dist/src/interaction-positionals.js +1 -1
  127. package/dist/src/interaction.js +1 -1
  128. package/dist/src/interaction2.js +1 -1
  129. package/dist/src/interactor-operation-catalog.js +1 -1
  130. package/dist/src/interactor.js +5 -5
  131. package/dist/src/interactor2.js +1 -1
  132. package/dist/src/interactor3.js +1 -1
  133. package/dist/src/interactor4.js +1 -1
  134. package/dist/src/interactor5.js +1 -1
  135. package/dist/src/interactors.js +1 -1
  136. package/dist/src/internal/bin.js +1 -1
  137. package/dist/src/internal/daemon.js +1 -1
  138. package/dist/src/internal/png-worker.js +1 -1
  139. package/dist/src/inventory.js +1 -1
  140. package/dist/src/inventory2.js +1 -1
  141. package/dist/src/inventory6.js +1 -1
  142. package/dist/src/ios-node-interpretation.js +1 -1
  143. package/dist/src/ios-settings.js +1 -1
  144. package/dist/src/ios-snapshot-acquisition.js +1 -1
  145. package/dist/src/ios-snapshot-engine.js +1 -1
  146. package/dist/src/ios-snapshot-runtime.js +1 -1
  147. package/dist/src/keyboard-occlusion.js +1 -1
  148. package/dist/src/keyed-lock.js +1 -1
  149. package/dist/src/launch-confirmation.js +1 -1
  150. package/dist/src/launch-services-registration.js +4 -4
  151. package/dist/src/lease.js +1 -1
  152. package/dist/src/legacy.js +1 -1
  153. package/dist/src/limrun-runtime-dependencies.js +1 -1
  154. package/dist/src/local-interactor-operation-set.js +1 -1
  155. package/dist/src/mechanics.js +12 -12
  156. package/dist/src/mobile-snapshot-semantics.js +1 -1
  157. package/dist/src/observability.js +1 -1
  158. package/dist/src/output-path.js +1 -1
  159. package/dist/src/parameterized-recorded-fill.js +1 -1
  160. package/dist/src/perf-facade.js +1 -1
  161. package/dist/src/perf-runtime-operation-builder.js +1 -1
  162. package/dist/src/perf-target.js +1 -1
  163. package/dist/src/physical-device-control.js +1 -1
  164. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  165. package/dist/src/platform-runtime-claim-recovery.js +1 -1
  166. package/dist/src/platform-runtime-daemon-services.js +1 -1
  167. package/dist/src/platform-runtime-host.js +1 -1
  168. package/dist/src/platform-runtime-open-target.js +1 -1
  169. package/dist/src/platform-runtime-operation-host.js +5 -5
  170. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  171. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  172. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  173. package/dist/src/platform-runtime-unavailable.js +1 -1
  174. package/dist/src/platform-runtime.js +1 -1
  175. package/dist/src/platform-runtime2.js +1 -1
  176. package/dist/src/png-resize.js +1 -1
  177. package/dist/src/png-worker-client.js +1 -1
  178. package/dist/src/process-exit.js +1 -1
  179. package/dist/src/provider-device-runtime.d.ts +28 -0
  180. package/dist/src/provider-plugin-catalog.js +2 -0
  181. package/dist/src/provider-plugin.d.ts +1 -1
  182. package/dist/src/provider-webdriver.js +1 -1
  183. package/dist/src/proxy.js +1 -1
  184. package/dist/src/react-native-overlay2.js +1 -1
  185. package/dist/src/react-native.js +1 -1
  186. package/dist/src/react-profile-command.js +1 -1
  187. package/dist/src/record-runtime.js +1 -1
  188. package/dist/src/record-trace.js +1 -1
  189. package/dist/src/recording-scope.js +1 -1
  190. package/dist/src/recording.js +1 -1
  191. package/dist/src/registry.js +1 -1
  192. package/dist/src/remote-config-core.js +1 -1
  193. package/dist/src/replay-backend-host.js +1 -1
  194. package/dist/src/replay-divergence.js +1 -1
  195. package/dist/src/replay-maestro-backend.js +3 -3
  196. package/dist/src/replay-script-selection.js +1 -1
  197. package/dist/src/replay2.js +1 -1
  198. package/dist/src/request-runtime-binding.js +1 -1
  199. package/dist/src/request.js +1 -1
  200. package/dist/src/result-serialization.js +1 -1
  201. package/dist/src/retry.js +1 -1
  202. package/dist/src/runner-cache-retention.js +1 -1
  203. package/dist/src/runner-client.js +1 -1
  204. package/dist/src/runner-dev-tools-security.js +1 -1
  205. package/dist/src/runner-device-readiness.js +1 -1
  206. package/dist/src/runner-device-set.js +1 -1
  207. package/dist/src/runner-error-classification.js +2 -2
  208. package/dist/src/runner-exchange.js +1 -1
  209. package/dist/src/runner-lease.js +1 -1
  210. package/dist/src/runner-operations-facade.js +1 -1
  211. package/dist/src/runner-retention.js +1 -1
  212. package/dist/src/runner-selector-query.js +1 -1
  213. package/dist/src/runner-start-budget.js +1 -1
  214. package/dist/src/runner-startup-transport.js +1 -1
  215. package/dist/src/runner-toolchain-probe.js +1 -1
  216. package/dist/src/runner.js +2 -2
  217. package/dist/src/runtime-admission.js +1 -1
  218. package/dist/src/runtime-deployment.js +1 -1
  219. package/dist/src/runtime-factory.js +1 -1
  220. package/dist/src/runtime-session.js +1 -1
  221. package/dist/src/runtime.js +4 -4
  222. package/dist/src/runtime10.js +2 -2
  223. package/dist/src/runtime2.js +1 -1
  224. package/dist/src/runtime3.js +5 -5
  225. package/dist/src/runtime4.js +1 -1
  226. package/dist/src/runtime5.js +1 -1
  227. package/dist/src/runtime6.js +1 -1
  228. package/dist/src/runtime7.js +1 -1
  229. package/dist/src/runtime8.js +1 -1
  230. package/dist/src/runtime9.js +2 -2
  231. package/dist/src/screen-recording-transport.js +1 -1
  232. package/dist/src/screenshot-density.js +1 -1
  233. package/dist/src/screenshot-runtime.js +1 -1
  234. package/dist/src/screenshot3.js +1 -1
  235. package/dist/src/sdk-batch-runner.js +2 -2
  236. package/dist/src/sdk-batch.js +2 -2
  237. package/dist/src/sdk-contracts.d.ts +9 -0
  238. package/dist/src/sdk-contracts.js +2 -2
  239. package/dist/src/sdk-device.js +1 -1
  240. package/dist/src/sdk-finders.js +1 -1
  241. package/dist/src/sdk-io.js +5 -5
  242. package/dist/src/sdk-remote-config.js +1 -1
  243. package/dist/src/sdk-selectors.js +1 -1
  244. package/dist/src/selection.js +0 -0
  245. package/dist/src/selector-pipeline-policy.js +1 -1
  246. package/dist/src/selector-runtime.js +1 -1
  247. package/dist/src/selectors.js +1 -1
  248. package/dist/src/server-startup.js +1 -1
  249. package/dist/src/session-paths.js +1 -1
  250. package/dist/src/session-replay-vars.js +1 -1
  251. package/dist/src/session-runtime.js +1 -1
  252. package/dist/src/session-store.js +3 -3
  253. package/dist/src/session.js +1 -1
  254. package/dist/src/session2.js +5 -5
  255. package/dist/src/settings-bluetooth.js +1 -1
  256. package/dist/src/settings.js +1 -1
  257. package/dist/src/settings2.js +1 -1
  258. package/dist/src/settle-observation-capture.js +1 -1
  259. package/dist/src/simctl-settings.js +1 -1
  260. package/dist/src/simctl.js +1 -1
  261. package/dist/src/simulator-boot.js +1 -1
  262. package/dist/src/simulator-state.js +1 -1
  263. package/dist/src/simulator.js +1 -1
  264. package/dist/src/snapshot-chrome.js +1 -1
  265. package/dist/src/snapshot-desktop-projection.js +1 -1
  266. package/dist/src/snapshot-helper-install.js +6 -6
  267. package/dist/src/snapshot-node-lookup.js +1 -1
  268. package/dist/src/snapshot-occlusion.js +1 -1
  269. package/dist/src/snapshot-runtime-binding.js +1 -1
  270. package/dist/src/snapshot-runtime-capture-input.js +1 -1
  271. package/dist/src/snapshot-runtime.js +1 -1
  272. package/dist/src/snapshot-state.js +1 -1
  273. package/dist/src/snapshot.js +1 -1
  274. package/dist/src/snapshot3.js +1 -1
  275. package/dist/src/src.js +1 -1
  276. package/dist/src/src3.js +1 -1
  277. package/dist/src/src4.js +1 -1
  278. package/dist/src/store.js +1 -1
  279. package/dist/src/tap-keyboard-occlusion.js +1 -1
  280. package/dist/src/target-evidence-tree.js +1 -1
  281. package/dist/src/target-evidence.js +1 -1
  282. package/dist/src/telephony-runtime.js +1 -1
  283. package/dist/src/text-entry-focus.js +1 -1
  284. package/dist/src/tool-provider.js +3 -3
  285. package/dist/src/tool-provider2.js +1 -1
  286. package/dist/src/tool-provider3.js +1 -1
  287. package/dist/src/toolchain-probe.js +1 -1
  288. package/dist/src/touch-reference-frame.js +1 -1
  289. package/dist/src/touch-runtime.js +1 -1
  290. package/dist/src/touch-runtime2.js +1 -1
  291. package/dist/src/tree.js +1 -1
  292. package/dist/src/tv-remote-runtime.js +1 -1
  293. package/dist/src/tv-remote.js +2 -2
  294. package/dist/src/type-text-runtime.js +1 -1
  295. package/dist/src/update-check.js +1 -1
  296. package/dist/src/vega-executable.js +1 -1
  297. package/dist/src/video.js +1 -1
  298. package/dist/src/webdriver-source.js +1 -1
  299. package/package.json +7 -6
  300. package/server.json +2 -2
  301. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +0 -1
  302. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
  303. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +0 -1
  304. package/dist/src/physical-device-apps.js +0 -1
@@ -1,5 +1,5 @@
1
- import{B as e,C as t,N as n,Q as r,R as i,S as a,V as o,Z as s,et as c,f as l,k as u,n as d,ot as f,p,s as m,w as h}from"./sdk-contracts.js";import{L as g,V as _,z as v}from"./tv-remote.js";import{i as y,j as b,n as x,t as S,v as C}from"./sdk-batch-runner.js";import{a as w,n as ee,t as T}from"./snapshot-diagnostics.js";import{$ as E,A as te,E as D,F as O,G as ne,I as re,M as k,N as ie,R as A,T as ae,Y as oe,at as se,et as ce,j as le,k as ue,m as de,tt as fe}from"./back-mode.js";import{V as pe,Z as me,_t as he,bt as ge,ht as j}from"./sdk-io.js";import"./diagnostics.js";import{E as _e,M as ve,O as M,S as ye,T as be,_ as N,p as P,v as F,y as xe}from"./sdk-device.js";import{A as Se,B as Ce,Cn as we,Ct as Te,F as Ee,G as De,I as Oe,It as ke,J as Ae,Jn as je,K as Me,Kn as Ne,Kt as Pe,L as Fe,N as Ie,P as Le,Q as Re,R as ze,Sn as Be,T as Ve,Tt as He,U as Ue,W as We,X as Ge,Y as Ke,Yn as qe,Z as Je,at as Ye,d as Xe,f as Ze,fn as Qe,fr as $e,it as et,j as tt,mr as nt,mt as rt,pr as it,pt as at,q as ot,st,tr as ct,un as lt,v as ut,wn as dt,wt as ft,z as pt}from"./sdk-batch.js";import{c as mt,d as ht,f as gt,h as _t,l as vt,m as yt,o as I,p as bt,s as xt,u as St}from"./session-store.js";import{a as Ct,i as wt,n as Tt,o as Et,t as Dt}from"./target-evidence.js";import{a as Ot,i as kt,n as At,o as jt,r as Mt,s as Nt,t as Pt}from"./vars.js";import{A as Ft,N as It,_ as Lt,d as Rt,g as zt,h as Bt,j as Vt,k as Ht,l as Ut,m as Wt,p as Gt,s as Kt,u as qt}from"./parameterized-recorded-fill.js";import{n as Jt,r as Yt,t as Xt}from"./target-evidence-tree.js";import{A as Zt,D as Qt,E as $t,O as en,_ as tn,b as nn,d as rn,f as an,g as on,h as sn,k as cn,m as ln,o as un,p as dn,s as fn,v as pn,x as mn,y as hn}from"./src.js";import{g as gn,i as _n}from"./observability.js";import{i as L,n as vn,r as R}from"./success-text.js";import{t as yn}from"./app-inventory.js";import{n as bn,r as xn}from"./output-path.js";import"./command.js";import{t as z}from"./session-paths.js";import{c as Sn,s as Cn}from"./session-artifact-paths.js";import{a as wn}from"./version.js";import{t as Tn}from"./keyed-lock.js";import"./retry.js";import{i as En,n as Dn}from"./replay-divergence.js";import{n as On,t as kn}from"./deploy-result-target.js";import{d as An,f as jn,g as Mn,h as Nn,l as Pn,m as Fn,p as In,u as Ln,v as Rn,y as zn}from"./device-claim-recovery.js";import{t as Bn}from"./keyboard-actions.js";import{a as Vn,c as Hn,d as Un,h as Wn,o as Gn,r as Kn,s as qn,u as Jn}from"./replay-script-selection.js";import{a as Yn,n as Xn}from"./artifact-tracking.js";import{n as Zn}from"./provider-device-admission.js";import{_ as Qn,d as $n,g as er,n as tr,o as B,r as nr,u as rr}from"./snapshot-runtime-capture-input.js";import{a as ir,f as ar,i as or,l as sr,n as cr,p as lr,t as ur,u as dr}from"./device-claims.js";import{i as fr,n as pr}from"./lease-context.js";import{C as mr,S as hr,_ as gr,a as _r,c as vr,d as yr,f as br,g as xr,h as Sr,i as Cr,l as wr,m as Tr,n as Er,o as Dr,p as Or,r as kr,s as Ar,t as jr,u as Mr,x as Nr,y as Pr}from"./session-runtime.js";import{d as Fr}from"./daemon-command-registry.js";import{n as V}from"./device-isolation.js";import{a as Ir,i as Lr,n as Rr,r as zr}from"./device-inventory-context.js";import{l as Br}from"./selector-pipeline-policy.js";import{a as Vr,c as Hr,l as Ur,o as Wr,s as Gr,t as Kr}from"./request.js";import{i as qr,n as Jr}from"./session-capture-binding.js";import{n as H,t as Yr}from"./runtime-admission.js";import{c as Xr,f as Zr,o as Qr,r as $r}from"./runtime-session.js";import{n as ei}from"./snapshot-node-lookup.js";import{a as ti,i as U,n as W,r as G,t as ni}from"./session-runtime-admission.js";import{n as ri}from"./gesture-runtime.js";import{a as ii,c as ai,i as oi,l as si,o as ci,r as li,s as ui,t as di}from"./app-log-session-resource.js";import{t as fi}from"./record-runtime.js";import{t as pi}from"./snapshot-runtime.js";import{n as mi,r as hi}from"./device-selection-resolver.js";import{t as gi}from"./audio-probe-result.js";import{a as _i,c as vi,d as yi,g as bi,h as xi,l as Si,m as Ci,n as wi,o as Ti,p as Ei,r as Di,t as Oi,u as ki}from"./session-replay-vars.js";import{n as Ai}from"./replay.js";import{t as ji}from"./replay-backend-registry.js";import{n as Mi}from"./status-markers.js";import{n as Ni,r as Pi}from"./doctor-lines.js";import{t as Fi}from"./project-runtime.js";import{createHash as Ii}from"node:crypto";import K,{promises as Li}from"node:fs";import q from"node:path";import{setTimeout as Ri}from"node:timers/promises";function zi(e){throw new i(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function Bi(e){let t=e.meta?.installSource;if(!t)throw new i(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(t.kind){case`url`:if(!t.url||t.url.trim().length===0)throw new i(`INVALID_ARGS`,`install_from_source url source requires a non-empty url`);return t;case`path`:if(!t.path||t.path.trim().length===0)throw new i(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return t;case`github-actions-artifact`:throw new i(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:zi(t)}}function Vi(e){let t=Bi(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:Yn(n,e.meta?.tenantId)},cleanup:()=>{Xn(n)}}}function J(e,t,n){return t||$t(n)?null:m(`INVALID_ARGS`,`${e} requires an active session or an explicit device selector (e.g. --platform ios).`,f())}async function Y(e){return Qt(e.flags)||!e.session?await Jn(e.flags??{},{env:e.env,androidAvdSelection:e.androidAvdSelection}):await Hi(e.session.device,e.platformServices,e.env)}async function Hi(e,t,n){if(Zn(e)||!N(e)||e.kind!==`simulator`||process.platform!==`darwin`)return e;if((await t.appleSessionObservation.observeRunnerSession(e.id))?.alive)return{...e,booted:!0};let r={platform:`ios`,target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await Jn(r,{env:n})}catch(e){if(!(e instanceof i)||e.code!==`DEVICE_NOT_FOUND`)throw e}return await Jn({platform:`ios`,target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}},{env:n})}function Ui(e,t){return t?hn(t,e).length===0:!1}async function Wi(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o,s,l;try{o=Vi(t);let c=Ji(t),u=await Ki(a,t.flags,r.host.env,e.platformServices),d=await G(e.inspectFacts)(u),f=U(`install_from_source`,d.operations.ensureReady)??U(`install_from_source`,d.operations.materializeAppSource)??U(`install_from_source`,d.operations.deployMaterializedApp);if(f)return f;let p=await W(e.bindDevice)(u,Ge);await p.operations.ensureReady({}),s=await p.operations.materializeAppSource({source:o.source}),l=await Yi({artifact:s,retention:c,req:t,session:a,sessionName:n}),i&&B(r.requireCurrent(i));let m=await p.operations.deployMaterializedApp({artifact:s}),h=Xi(u,s,m,l),g=L(h,`Installed: ${On(h)}`);return I(r,i,t,`install_source`,g,{positionals:[]}),{ok:!0,data:g}}catch(e){return l&&await Nr(l.materializationId,t.meta?.tenantId).catch(()=>{}),{ok:!1,error:c(e)}}finally{await s?.cleanup(),o?.cleanup()}}async function Gi(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new i(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await Nr(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:c(e)}}}async function Ki(e,t,n,r){let a=qi(t?.platform);if(e&&a&&!_e(e.device,a))throw new i(`INVALID_ARGS`,`install_from_source requested platform ${a}, but session is bound to ${M(e.device)}`);if(!e&&!a)throw new i(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);return e?e.device:await Y({session:e,flags:t,env:n,platformServices:r})}function qi(e){return e===`ios`||e===`android`?e:void 0}function Ji(e){let t=e.meta?.retainMaterializedPaths===!0,n=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(n!==void 0&&n<=0)throw new i(`INVALID_ARGS`,`install_from_source retentionMs must be a positive integer`);return{enabled:!0,...n===void 0?{}:{ttlMs:n}}}async function Yi(e){if(e.retention.enabled)return await mr({archivePath:e.artifact.archivePath,installablePath:e.artifact.installablePath,tenantId:e.req.meta?.tenantId,sessionName:e.session?e.sessionName:void 0,ttlMs:e.retention.ttlMs})}function Xi(e,t,n,r){return N(e)?Zi(t,n,r):Qi(t,n,r)}function Zi(e,t,n){let r=t.bundleId??e.bundleId;if(!r)throw new i(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`);return{...ea(n),bundleId:r,...$i(t,e),launchTarget:t.launchTarget??r}}function Qi(e,t,n){let r=t.packageName??t.launchTarget??e.packageName;if(!r)throw new i(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{...ea(n),packageName:r,...$i(t,e),launchTarget:t.launchTarget??r}}function $i(e,t){let n=e.appName??t.appName;return n?{appName:n}:{}}function ea(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function ta(e){let{req:t,session:n,inspectFacts:r,bindDevice:i,platformServices:a}=e,o=na(t);if(!o.ok)return o.response;let s=J(`runtime port-reverse`,n,t.flags);if(s)return s;let c=await Y({session:n,flags:t.flags,env:e.env,platformServices:e.platformServices}),l=await H({device:c,inspectFacts:r,bindDevice:i,platformServices:a,command:`runtime port-reverse`,use:Ce});if(l.type===`response`)return l.response;if(l.runtime.owner.kind!==`provider-runtime`||l.runtime.owner.provider!==o.options.provider)return m(`UNSUPPORTED_OPERATION`,`The selected device is not owned by the requested port-reverse provider.`,{provider:o.options.provider});let u=await l.runtime.operations.configureProviderPortReverse(o.options);return u?{ok:!0,data:{action:`port-reverse`,...u}}:m(`UNSUPPORTED_OPERATION`,`The selected provider device runtime does not support port reverse for this lease.`)}function na(e){let t=ra(e);if(!t.ok)return t;let n=ia(e);return n.ok?{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:e.flags?.portReverseName?.trim()||`runtime`}}:n}function ra(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:m(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:m(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function ia(e){let t=aa(e.flags?.devicePort),n=aa(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:m(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}function aa(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}async function oa(e){return await H({...e,command:`runtime clear`,use:Fe})}async function sa(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(i===`port-reverse`)return await ta({req:t,session:r.get(n),env:r.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i===`gesture-viewport`)return await ca({...e,session:r.get(n)});if(!la(i))return m(`INVALID_ARGS`,`runtime requires set, show, clear, port-reverse, or gesture-viewport`);let a=r.lookup(n),o=a?.session,s=r.getRuntimeHints(n);return i===`clear`?await ua({sessionName:n,sessionStore:r,ref:a,current:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}):i===`show`?da(n,s):pa({req:t,sessionName:n,sessionStore:r,session:o,current:s})}async function ca(e){if(!e.session)return m(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let t=await ri({device:e.session.device,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!t.ok)return t.response;let n=nr(e.logPath,e.req.flags,e.session.appBundleId,e.session.trace?.outPath,e.req.meta?.requestId,e.req.meta);return{ok:!0,data:{viewport:await t.read(n)}}}function la(e){return e===`set`||e===`show`||e===`clear`}async function ua(e){let{sessionName:t,sessionStore:n,ref:r,current:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=r?n.requireCurrent(r):void 0;if(kr(i)&&c?.appBundleId){let e=await oa({device:c.device,inspectFacts:a,bindDevice:o,platformServices:s});if(e.type===`response`)return e.response;let t=n.requireCurrent(r);B(t),await e.runtime.operations.clearRuntimeHints({appId:t.appBundleId,values:Ar(i)})}let l=r?n.clearRuntimeHints(r):!!i;return r||n.setRuntimeHints(t,void 0),{ok:!0,data:{session:t,cleared:l}}}function da(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function fa(e){return e?M(e.device):void 0}function pa(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=fa(i),s=Mr(t.flags?.platform??a?.platform??o);if(!s)return m(`INVALID_ARGS`,`runtime set only supports iOS, Android, and HarmonyOS sessions. Pass --platform ios|android|harmonyos or open a supported session first.`);if(o!==void 0&&o!==s)return m(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=_r(a,jr(t.flags,s));return Er(c)===0?m(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}const ma=/^[A-Za-z0-9_.:-]{1,64}$/,ha=8192,ga=4096;function _a(e){let t=e[0]?.trim(),n=e[1]?.trim();if(!t)throw new i(`INVALID_ARGS`,`trigger-app-event requires <event> [payloadJson]`);if(!ma.test(t))throw new i(`INVALID_ARGS`,`Invalid trigger-app-event event name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});if(e.length>2)throw new i(`INVALID_ARGS`,`trigger-app-event accepts at most two arguments: <event> [payloadJson]`);return{eventName:t,payload:ya(n,t)}}function va(e,t,n,r){let a=M(e),o=ba(e,r);if(!o)throw new i(`UNSUPPORTED_OPERATION`,`No app event URL template configured for ${a}.`,{hint:`Set AGENT_DEVICE_${a.toUpperCase()}_APP_EVENT_URL_TEMPLATE or AGENT_DEVICE_APP_EVENT_URL_TEMPLATE, for example "myapp://agent-device/event?name={event}&payload={payload}".`});let s=n?JSON.stringify(n):``,c=o.replaceAll(`{event}`,encodeURIComponent(t)).replaceAll(`{payload}`,encodeURIComponent(s)).replaceAll(`{platform}`,encodeURIComponent(a));if(c.length>ga)throw new i(`INVALID_ARGS`,`trigger-app-event URL exceeds maximum supported length`,{hint:`Reduce payload size or shorten AGENT_DEVICE_*_APP_EVENT_URL_TEMPLATE.`,length:c.length,maxLength:ga});return c}function ya(e,t){if(e)try{let n=JSON.parse(e);if(!n||typeof n!=`object`||Array.isArray(n))throw new i(`INVALID_ARGS`,`trigger-app-event payload for "${t}" must be a JSON object`);let r=JSON.stringify(n);if(Buffer.byteLength(r,`utf8`)>ha)throw new i(`INVALID_ARGS`,`trigger-app-event payload for "${t}" exceeds ${ha} bytes`);return n}catch(t){throw t instanceof i?t:new i(`INVALID_ARGS`,`Invalid trigger-app-event payload JSON: ${e}`)}}function ba(e,t){return((N(e)?t.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:F(e)?t.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:t.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??t.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE)?.trim()||void 0}async function xa(e,t,n,r,i){let{eventName:a,payload:o}=_a([...r]),s=va(t,a,o,i),c={eventUrl:s,...n.appBundleId===void 0?{}:{options:{appBundleId:n.appBundleId}},execution:tr(n)};return await e.operations.triggerAppEvent(c),{event:a,eventUrl:s,transport:`deep-link`,...R(`Triggered app event: ${a}`)}}async function Sa(e){let{host:t,device:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s}=e,c=await H({command:`trigger-app-event`,device:n,use:et,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s});if(c.type===`response`)return{ok:!1,response:c.response};let l=c.runtime;return{ok:!0,execute:e=>xa(l,n,e,r,t.env)}}function Ca(e){let t=(e[0]??`status`).toLowerCase();if(!Bn(t))throw new i(`INVALID_ARGS`,`keyboard requires a subcommand: status, get, dismiss, enter, or return`);if(e.length>1)throw new i(`INVALID_ARGS`,`keyboard accepts at most one subcommand argument`);return wa(t)}function wa(e){return e===`get`?`status`:e===`return`?`enter`:e}const Ta={"ime-probe":`android`},Ea={"ime-probe":`android`,mechanism:`ios`,acknowledged:`harmonyos`},Da={"visibility-echo":`ios`,"android-acknowledged":`android`,"harmonyos-acknowledged":`harmonyos`};function Oa(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:tr(e)}}async function ka(e,t){let n=await H(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:e=>t(r,e)}}function Aa(e,t){return e.operations.keyboardStatus(Oa(t)).then(e=>({platform:Ta[e.kind],action:`status`,visible:e.visible,inputType:e.inputType,type:e.type,inputMethodPackage:e.inputMethodPackage,focusedPackage:e.focusedPackage,focusedResourceId:e.focusedResourceId,inputOwner:e.inputOwner}))}async function ja(e,t){let n=await e.operations.keyboardDismiss(Oa(t)),r=Ea[n.kind];return n.kind===`mechanism`?{platform:r,action:`dismiss`,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,mechanism:n.mechanism,...R(Pa(n.dismissed===!0,n.mechanism))}:n.kind===`acknowledged`?{platform:r,action:`dismiss`,...R(`Keyboard dismissed`)}:{platform:r,action:`dismiss`,attempts:n.attempts,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,inputType:n.inputType,type:n.type,inputMethodPackage:n.inputMethodPackage,focusedPackage:n.focusedPackage,focusedResourceId:n.focusedResourceId,inputOwner:n.inputOwner}}async function Ma(e,t){let n=await e.operations.keyboardEnter(Oa(t)),r=Da[n.kind];return n.kind===`visibility-echo`?{platform:r,action:`enter`,visible:n.visible,wasVisible:n.wasVisible,...R(`Keyboard enter pressed`)}:{platform:r,action:`enter`,...R(`Keyboard enter pressed`)}}async function Na(e){let t=Ca(e.positionals),{device:n,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o}=e;return t===`status`?await ka({command:`keyboard status`,device:n,use:He,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>Aa(e,t)):t===`dismiss`?await ka({command:`keyboard dismiss`,device:n,use:Te,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>ja(e,t)):await ka({command:`keyboard enter`,device:n,use:ft,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>Ma(e,t))}function Pa(e,t){return e?t===`dismissKey`?`Keyboard dismissed via its dismiss key`:`Keyboard dismissed`:`Keyboard already hidden`}async function Fa(e){let{req:t,sessionName:n,sessionStore:r,command:i,positionals:a,recordPositionals:o,updateSession:s,prepare:c}=e,l=r.lookup(n),u=l?.session,d=t.flags??{},f=J(i,u,d);if(f)return f;let p=await Y({session:u,flags:d,env:r.host.env,platformServices:e.platformServices});l&&r.requireCurrent(l);let m=await c(p,l);if(!m.ok)return m.response;let h=l?r.requireCurrent(l):void 0;h&&Fr(t)===`may-invalidate`&&B(h);let g=await m.execute();return l&&(s&&await s(l,g),I(r,l,t,i,g??{},{positionals:o??a})),{ok:!0,data:g??{}}}function Ia(e,t,n){if(!(e||t!==`dismiss`&&t!==`enter`&&t!==`return`||n?.platform!==`ios`))return m(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`)}async function La(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=t.positionals??[];return await Fa({req:t,sessionName:n,sessionStore:i,command:e.command,positionals:c,platformServices:s,...e.updateSession?{updateSession:e.updateSession}:{},prepare:async(n,l)=>{let u=await e.resolveRuntime({host:e.host,device:n,positionals:c,readiness:!0,inspectFacts:a,bindDevice:o,platformServices:s});if(!u.ok)return{ok:!1,response:u.response};let d=l?i.requireCurrent(l):void 0,f={...nr(r,t.flags,d?.appBundleId,d?.trace?.outPath),surface:d?.surface};return{ok:!0,execute:()=>u.execute(f)}}})}async function Ra(e){return Ia(e.sessionStore.get(e.sessionName),e.req.positionals?.[0]?.trim().toLowerCase(),e.req.flags??{})||await La({...e,command:D.keyboard,resolveRuntime:e=>Na(e)})}async function za(e){return await La({...e,command:D.triggerAppEvent,resolveRuntime:e=>Sa(e),updateSession:async(t,n)=>{let r=typeof n?.eventUrl==`string`?n.eventUrl:void 0;if(!r)return;let i=e.sessionStore.requireCurrent(t),a=await e.platformServices.resolveSessionAppBundleIdForTarget(i.device,r,i.appBundleId);a!==void 0&&e.sessionStore.update(t,{appBundleId:a})}})}function Ba(e){let t=e.trim();return t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith(`[`)&&t.endsWith(`]`)}function Va(e,t){let n=t?.subject??`Payload`,r=e.trim();if(!r)throw new i(`INVALID_ARGS`,`${n} cannot be empty`);let a=t?.expandPath?t.expandPath(r,t.cwd):r;try{if(!K.statSync(a).isFile())throw new i(`INVALID_ARGS`,`${n} path is not a file: ${a}`);return{kind:`file`,path:a}}catch(e){if(e instanceof i)throw e;let t=e.code;if(t===`EACCES`||t===`EPERM`)throw new i(`INVALID_ARGS`,`${n} file is not readable: ${a}`);if(t&&t!==`ENOENT`)throw new i(`COMMAND_FAILED`,`Unable to read ${n} file: ${a}`,{cause:String(e)})}if(Ba(r))return{kind:`inline`,text:r};throw new i(`INVALID_ARGS`,`${n} file not found: ${a}`)}async function Ha(e){let t=Va(e,{subject:`Push payload`}),n=t.kind===`inline`?t.text:await Ua(t.path);try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw new i(`INVALID_ARGS`,`push payload must be a JSON object`);return e}catch(t){throw t instanceof i?t:new i(`INVALID_ARGS`,`Invalid push payload JSON: ${e}`)}}async function Ua(e){try{return await Li.readFile(e,`utf8`)}catch(t){let n=t.code;throw n===`ENOENT`?new i(`INVALID_ARGS`,`Push payload file not found: ${e}`):n===`EISDIR`?new i(`INVALID_ARGS`,`Push payload path is not a file: ${e}`):n===`EACCES`||n===`EPERM`?new i(`INVALID_ARGS`,`Push payload file is not readable: ${e}`):new i(`COMMAND_FAILED`,`Unable to read push payload file: ${e}`,{cause:String(t)})}}async function Wa(e){let{req:t,command:n,sessionName:r,sessionStore:i}=e,a=i.lookup(r),o=a?.session,s=t.flags??{},c=J(n,o,s);if(c)return c;let l=Za(n,t.positionals??[]);if(!l.ok)return l.response;let u=t.meta?.uploadedArtifactId;try{let r=u?Yn(u,t.meta?.tenantId):z(l.appPathInput,e.host.cwd);if(!K.existsSync(r))return m(`INVALID_ARGS`,`App binary not found: ${r}`);let c=await Y({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),d=await G(e.inspectFacts)(c),f=U(n,d.operations.deployApp);if(f)return f;let p=await W(e.bindDevice)(c,Ke);a&&B(i.requireCurrent(a));let h=await p.operations.deployApp({app:l.app,appPath:r,replaceExisting:n===`reinstall`}),g=qa(c,l.app,r,h),_=L(g,`Installed: ${g.appName??kn(g)}`);return Xa(i,a,g),I(i,a,t,n,_),{ok:!0,data:_}}finally{u&&Xn(u)}}async function Ga(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=J(`push`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim(),l=t.positionals?.[1]?.trim();if(!c||!l)return m(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`);let u=await Ha(Qa(l,t.meta?.cwd??e.host.cwd)),d=await Y({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),f=await G(e.inspectFacts)(d),p=U(`push`,f.operations.ensureReady)??U(`push`,f.operations.sendPushNotification);if(p)return p;let h=await W(e.bindDevice)(d,Je);await h.operations.ensureReady({}),i&&B(r.requireCurrent(i));let g=await h.operations.sendPushNotification({appId:c,payload:u}),_=N(d)?L({platform:`ios`,bundleId:c},`Pushed notification to ${c}`):L({platform:M(d),package:c,action:g.action,extrasCount:g.extrasCount},`Pushed notification to ${c}`);return I(r,i,t,`push`,_,{positionals:[c,l]}),{ok:!0,data:_}}async function Ka(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=J(`uninstall`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim();if(!c)return m(`INVALID_ARGS`,`uninstall requires <app>`);let l=await Y({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),u=await G(e.inspectFacts)(l),d=U(`uninstall`,u.operations.uninstallApp);if(d)return d;let f=await W(e.bindDevice)(l,Re);i&&B(r.requireCurrent(i));let p=await f.operations.uninstallApp({app:c}),h=N(l)?`ios`:`android`,g=p.wasInstalled?`bundleId`in p?p.bundleId:p.packageName:void 0,_=g?L({platform:h,app:c,wasInstalled:!0,appId:g},`Uninstalled: ${g}`):L({platform:h,app:c,wasInstalled:!1},`Not installed: ${c}`);return I(r,i,t,`uninstall`,_),{ok:!0,data:_}}function qa(e,t,n,r){return N(e)?Ja(t,n,r):Ya(e,t,n,r)}function Ja(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function Ya(e,t,n,r){let i=r.packageName,a=e.platform===`harmonyos`?`harmonyos`:`android`;return{app:t||i||r.launchTarget||n,appPath:n,platform:a,...i?{appId:i,package:i,packageName:i}:{},appName:r.appName,launchTarget:r.launchTarget}}function Xa(e,t,n){!t||n.platform!==`harmonyos`||!n.appId||e.update(t,{appBundleId:n.appId,appName:n.appName??n.app})}function Za(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:m(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:m(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}function Qa(e,t){let n=Va(e,{subject:`Push payload`,cwd:t,expandPath:(e,n)=>z(e,n??t)});return n.kind===`file`?n.path:n.text}async function $a(e){let{host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e;return n.command===`install`||n.command===`reinstall`?await Wa({host:t,req:n,command:n.command,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`install_source`?await Wi({req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`uninstall`?await Ka({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`push`?await Ga({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):null}async function eo(e,t,n){return await x(e,t,async(e,t)=>{let r=e;return await n({...r,internal:{...r.internal,executionPlan:{remainingSteps:t.remainingSteps}}})})}const to=new Set(`acceptAlert.actionButton.appLogCleanup.appLogDoctor.appLogInspect.appLogReattach.appLogStart.appState.appSwitcher.applyRuntimeHints.audioProbeCleanup.audioProbeQuery.audioProbeReattach.audioProbeStart.awaitAlert.back.bootTarget.bootTargetHeadless.captureScreenshot.captureSnapshot.captureSnapshotWithCustomActions.captureSnapshotWithoutActiveApp.clearRuntimeHints.closeApplication.configureProviderPortReverse.deployApp.deployMaterializedApp.dismissAlert.ensureReady.fillPoint.fillRef.finalizeApplicationClose.findText.focusPoint.gestureViewport.home.hoverPoint.hoverRef.keyboardDismiss.keyboardEnter.keyboardStatus.listApps.longPressPoint.materializeAppSource.networkDump.openApplication.perfFrames.perfMemorySample.perfMemorySnapshot.perfNativeCaptureCleanup.perfNativeCaptureReattach.perfNativeCaptureStart.perfProfileReport.performDirectionalFlingPlan.performGesturePlan.performMultiTouchGesturePlan.performTargetAuthoredDrag.power.prepareAppleRunner.prepareApplicationOpen.querySelector.readAlert.readClipboard.readSetting.readTextAtPoint.resolveOpenTarget.screenRecordingCleanup.screenRecordingReattach.screenRecordingStart.scrollDirection.sendPushNotification.sendTelephonyEvent.setFoldPose.setOrientation.setSetting.setViewport.shutdownTarget.tapElementSelector.tapPoint.tapRef.triggerAppEvent.tvRemote.typeText.uninstallApp.unlockOrientation.volumeDown.volumeUp.writeClipboard`.split(`.`));function no(e){return to.has(e)}const ro=new Map(Xe.map(e=>[e.name,e]));function io(e){let t=new Set;for(let n of e){let e=ao(n);if(e===void 0)return;for(let n of e)t.add(n)}return Object.freeze([...t].sort())}function ao(e){let t=ro.get(e.command)?.platformExecution;if(t===void 0)return;if(t.kind!==`device-runtime`)return[];let n=(`uses`in t?t.selectUses?.(e)??t.uses:[t.use]).flatMap(e=>e.required);return n.every(no)?n:void 0}function oo(e){if(e!==void 0&&e.remainingSteps.length!==0)return io(e.remainingSteps)}function so(e,t,n){return{requestId:e.meta?.requestId,logPath:t,traceLogPath:n,verbose:e.flags?.verbose,activity:e.flags?.activity,launchConsole:e.flags?.launchConsole,launchArgs:e.flags?.launchArgs,clearAppState:e.flags?.clearAppState,iosXctestrunFile:e.flags?.iosXctestrunFile,iosXctestDerivedDataPath:e.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:e.flags?.iosXctestEnvDir,runnerLeaseContext:fr(e),plannedOperations:oo(e.internal?.executionPlan)}}function co(e,t,n){let r=e.requireCurrent(t);e.recordAction(t,{command:`close`,positionals:n.positionals??[],flags:n.flags??{},result:{session:r.name,...R(`Closed: ${r.name}`)}})}function lo(e,t,n){let r=e.requireCurrent(t);if(!St(r))return{kind:`not-armed`};let i=r.actions.length;co(e,t,n);let a=Gt(r),o=e.writeSessionLog(t,{force:qt(r,n.flags?.force)});return o.written?{kind:`committed`,path:o.path}:o.error?(r.actions.length=i,{kind:`failed`,error:o.error}):a?{kind:`committed`}:(xt(r),{kind:`aborted`})}function uo(e,t){let n=c(t),r=Ft(e.scriptPublication??Lt);return{ok:!1,error:{...n,details:{...n.details,session:e.name,...r?{savedScript:r}:{}},retriable:!0}}}function fo(e){let{req:t,ref:n,sessionStore:r,platformCloseError:i}=e,a=r.requireCurrent(n);i||co(r,n,t);try{let e=r.writeSessionLog(n,{force:qt(a,t.flags?.force)});e.written&&Bt(a,e.path);return}catch(e){return po(e)}}function po(e){let t={hint:`Remove the existing target (or pass --force/--overwrite), then re-record with open --save-script.`,retriable:!1};return e instanceof i?new i(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${e.message}`,{...e.details,...t},e.cause):new i(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${c(e).message}`,t)}async function mo(e){let t=e.clearRuntimeHints?pt:ze,n=await Yr({...e,command:`close`,required:t.required});if(n.type===`response`)return n;if(!e.clearRuntimeHints)return{type:`runtime`,runtime:await n.bind(e.device,ze)};let r=await n.bind(e.device,pt);return{type:`runtime`,runtime:r,clearRuntimeHints:r.operations.clearRuntimeHints}}async function ho(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a,clearRuntimeHints:o,cleanupFailures:s,repairArmed:c,dispatchTargetedPlatformClose:l,finalizeOrdinaryCloseScript:u}=e,{address:d}=n,f=i.requireCurrent(n),p=async(e,t)=>{try{return await t()}catch(t){s.push({step:e,error:t});return}},m=e.platformResourceCleanup.retainExecutionHostAfterClose({device:f.device,shutdownRequested:t.flags?.shutdown===!0,hasScreenRecording:!!f.screenRecording,hasLease:!!f.lease}),h=i.getRuntimeHints(d);await go(n,i,p,e.platformResourceCleanup),f=i.requireCurrent(n);let g=c?void 0:await l({req:t,session:f,logPath:r,lifecycle:a});o&&f.appBundleId&&kr(h)&&await p(`runtime_hints`,async()=>{await o({appId:f.appBundleId,values:Ar(h)})});let _=await p(`application_lifecycle`,async()=>await a.operations.finalizeApplicationClose({appBundleId:f.appBundleId,surface:f.surface??`app`,retainRunner:m,stateDir:i.resolveDaemonStateDir(),shutdownTarget:t.flags?.shutdown===!0})??{}),v=c?void 0:u({req:t,ref:n,sessionStore:i,platformCloseError:g});return await p(`materialized_paths`,()=>hr(d)),{platformCloseError:g,saveScriptError:v,shutdownResult:_?.shutdown}}async function go(e,t,n,r){let i=t.resolveCurrent(e)??e.session;await n(`recording`,()=>Or({ref:e,sessionStore:t})),await n(`app_log`,()=>Sr({ref:e,sessionStore:t})),await n(`audio_probe`,()=>br({ref:e,sessionStore:t})),await n(`perf_capture`,()=>xr({ref:e,sessionStore:t})),await n(`platform_snapshot_helper`,()=>gr(i,r))}function _o(e,t){return Tr({sessionName:e,phase:`session_close_cleanup_failed`,failures:t})}function vo(e){if(e instanceof i)return e;let t=e instanceof Error?e.message:String(e);return new i(`COMMAND_FAILED`,`The platform close failed: ${t}`,{hint:`The repair transaction was not committed because the platform close failed; fix the underlying issue and retry close --save-script.`})}const yo=(e,t)=>(e.positionals?.length??0)>0||Pr(t);async function bo(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a}=e,o=i.requireCurrent(n),s=St(o),c=JSON.stringify(t.positionals??[]);if(s&&!vt(o,c)){let e=await So({req:t,session:o,logPath:r,lifecycle:a});if(e)return{response:uo(o,vo(e))};bt(i.requireCurrent(n),c)}let l=lo(i,n,t);return l.kind===`failed`?{response:uo(o,l.error)}:{repairArmed:s,...l.kind===`committed`&&l.path?{healedScriptPath:l.path}:{},...l.kind===`aborted`?{aborted:!0}:{}}}async function xo(e){try{let{endedLeaseId:t,providerData:n}=await en(e);return t&&fn(e.req,t),{providerData:n}}catch(t){let n=c(t);return{response:{ok:!1,error:{...n,hint:`The provider device could not be released. Retry close after the provider is reachable.`,details:{...n.details,session:e.session.name},retriable:!0}}}}}async function So(e){let{req:t,session:n,logPath:r,lifecycle:i}=e;if(yo(t,n))try{await i.operations.closeApplication({positionals:t.positionals??[],outPath:t.flags?.out,appBundleId:n.appBundleId,surface:n.surface??`app`,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:so(t,r,n.trace?.outPath)});return}catch(e){return e}}function Co(e,t){if(!e.flags?.saveScript||Rt(t))return;let n=t.scriptPublication;if(n?.kind!==`repair`)throw n===void 0||n.kind===`none`?new i(`INVALID_ARGS`,`close --save-script cannot publish this session: recording was not armed before this journey began, so there is no recording-time target evidence to publish.`,{hint:`Retry with plain close (it tears down without writing). To capture a publishable recording, start a fresh session with open <app> --save-script[=<path>].`}):new i(`INVALID_ARGS`,`close --save-script cannot ${n.status===`published`?`re-publish`:`publish`} this terminal recording. Retry with plain close; it will tear down the session without writing.`)}async function wo(e){let{req:t,sessionName:n,logPath:r,sessionStore:a,leaseRegistry:o,leaseLifecycleProvider:s}=e,c=a.lookup(n);if(!c)return await Oo({req:t,sessionName:n,logPath:r,env:e.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});let l=a.requireCurrent(c);Co(t,l);let u=t.positionals?.[0];if(t.internal?.closeAppOnly===!0&&!u)return m(`INVALID_ARGS`,`App-only close requires an app target`);if(!e.platformResourceCleanup)throw new i(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let d=e.platformResourceCleanup,f=await mo({device:l.device,clearRuntimeHints:t.internal?.closeAppOnly!==!0&&!!l.appBundleId&&kr(a.getRuntimeHints(n)),inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(f.type===`response`)return f.response;if(l=a.requireCurrent(c),B(l),t.internal?.closeAppOnly===!0&&u)return await Do({req:t,session:l,logPath:r,lifecycle:f.runtime,app:u});let p=await bo({req:t,ref:c,logPath:r,sessionStore:a,lifecycle:f.runtime});if(`response`in p)return p.response;let h=await To({env:e.host.env,req:t,ref:c,logPath:r,sessionStore:a,leaseRegistry:o,leaseLifecycleProvider:s,lifecycle:f.runtime,clearRuntimeHints:f.clearRuntimeHints,repairArmed:p.repairArmed,platformResourceCleanup:d});return h.kind===`response`?h.response:Eo({session:l,repair:p,requestedSaveScript:!!t.flags?.saveScript,shutdownResult:h.shutdownResult,providerData:h.providerData})}async function To(e){let{req:t,ref:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,lifecycle:s,clearRuntimeHints:c}=e,{address:l}=n,u=[],{platformCloseError:d,saveScriptError:f,shutdownResult:p}=await ho({req:t,ref:n,logPath:r,sessionStore:i,lifecycle:s,clearRuntimeHints:c,cleanupFailures:u,repairArmed:e.repairArmed,dispatchTargetedPlatformClose:So,finalizeOrdinaryCloseScript:fo,platformResourceCleanup:e.platformResourceCleanup}),m=i.requireCurrent(n),h=await xo({req:t,session:m,leaseRegistry:a,leaseLifecycleProvider:o});if(h.response)return{kind:`response`,response:h.response};m=i.resolveCurrent(n)??m;let g=_o(l,u),_=d??g;if(_?m.deviceClaim&&j({level:`warn`,phase:`device_claim_close_effects_unconfirmed`,data:{deviceKey:m.deviceClaim.deviceKey,session:l}}):await or(m.deviceClaim,e.env),i.retire(n),_)throw _;if(f)throw f;return{kind:`closed`,providerData:h.providerData,shutdownResult:p}}function Eo(e){let{session:t,repair:n,requestedSaveScript:r,shutdownResult:i,providerData:a}=e;if(n.aborted&&r)return{ok:!1,error:{code:`COMMAND_FAILED`,message:`The repair was aborted and no script was written.`,hint:`Recovery: replay --from <n> --plan-digest <digest> before closing.`,details:{session:t.name}}};let o=n.healedScriptPath?{savedScript:n.healedScriptPath}:{},s=a?{provider:a}:{},c=`Closed: ${t.name}`;return i?{ok:!0,data:L({session:t.name,shutdown:i,...o,...s},c)}:{ok:!0,data:{session:t.name,...R(c),...o,...s}}}async function Do(e){let{req:t,session:n,logPath:r,lifecycle:i,app:a}=e,o=await So({req:t,session:n,logPath:r,lifecycle:i});if(o)throw o;return{ok:!0,data:{app:a,...R(`Closed: ${a}`)}}}async function Oo(e){let{req:t,sessionName:n,logPath:r,env:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,{requireNamedSessionHoldsDevice:c}=await import(`./explicit-session-resolution.js`);if(c({req:t,sessionAddress:n,session:void 0}),!t.positionals||t.positionals.length===0)return m(`SESSION_NOT_FOUND`,`No active session`);let l=await mo({device:await Y({session:void 0,flags:t.flags,env:i,platformServices:s}),clearRuntimeHints:!1,inspectFacts:a,bindDevice:o,platformServices:s});return l.type===`response`?l.response:(await l.runtime.operations.closeApplication({positionals:t.positionals,outPath:t.flags?.out,surface:`app`,ensureReady:!0,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:so(t,r)}),{ok:!0,data:{app:t.positionals[0],...R(`Closed: ${t.positionals[0]}`)}})}function ko(e,t){return e.operations.ensureReady(t)}function Ao(e,t,n){return e.operations.listApps({device:t,filter:n})}async function jo(e){let{req:t,sessionName:n,sessionStore:r}=e;switch(t.command){case`session_list`:return Mo(t,r);case`devices`:return await Po(t,e.host.env);case`capabilities`:return await Ho({req:t,sessionName:n,sessionStore:r,inspectFacts:e.inspectFacts,platformServices:e.platformServices});case`apps`:return await Jo({env:e.host.env,req:t,sessionName:n,sessionStore:r,bindDevice:e.bindDevice,platformServices:e.platformServices,inspectFacts:e.inspectFacts,providerAppCatalog:e.providerAppCatalog});default:return null}}function Mo(e,t){let n=on(e);return{ok:!0,data:{sessions:t.listRefs().filter(e=>tn(e.session,n)).map(e=>No(e,t))}}}function No({address:e,session:t},n){let r=n.resolveSessionDir(e);return{name:t.name,address:e,sessionStateDir:r,runnerLogPath:Sn(r),platform:M(t.device),...P(t.device.platform)&&t.device.appleOs?{appleOs:t.device.appleOs}:{},target:t.device.target??`mobile`,surface:t.surface??`app`,device:t.device.name,id:t.device.id,device_id:t.device.id,createdAt:t.createdAt,...P(t.device.platform)&&!F(t.device)&&{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}}}async function Po(t,n){try{let e=Fo(n);return{ok:!0,data:{devices:(await Lo(t,n)).map(t=>({...ts(t),...Io(t,e)}))}}}catch(t){let n=e(t);return{ok:!1,error:{code:n.code,message:n.message,...n.details?{details:n.details}:{}}}}}function Fo(e){let t=new Map;for(let n of ar({},e)){let e=n.claim;!e||dr(n.classification)||t.set(e.deviceKey,{session:e.session,workspace:e.workspace})}return t}function Io(e,t){let n=t.get(lr(ir(e)));return n?{claimedBy:n}:{}}async function Lo(e,t){let n=e.flags?.platform;return Vo(await Rr(Ro(e,n,t)),e.flags?.platform,e.flags?.target)}function Ro(e,t,n){let r=e.flags;return{platform:t,target:r?.target,deviceName:r?.device,udid:r?.udid,serial:r?.serial,iosSimulatorSetPath:zo(r?.iosSimulatorDeviceSet,t,r?.target,n),androidSerialAllowlist:Bo(r?.androidDeviceAllowlist,n)}}function zo(e,t,n,r){return ve({requestedSetPath:e,platform:t,target:n,env:r})}function Bo(e,t){let n=V(e,t);return n?Array.from(n).sort():void 0}function Vo(e,t,n){let r=t?e.filter(e=>ns(e,t)):e;return n?r.filter(e=>(e.target??`mobile`)===n):r}async function Ho(e){let t=await es({...e,androidAvdSelection:`include-stopped`});if(`response`in t)return t.response;let{device:n}=t,r=Uo(n,e.sessionStore.get(e.sessionName),e.req.flags),i=await Zo(n,e.inspectFacts);return{ok:!0,data:{device:ts(n),...n.platform===`android`&&Ko(`press`,i)?{targetReadiness:{press:`bounded-geometry`}}:{},availableCommands:ut().filter(e=>e===`appstate`&&r?!0:Ko(e,i))}}}function Uo(e,t,n){return!t||!N(e)&&!F(e)||!Ui(n,t)?!1:Wo(t)||Go(e,t)}function Wo(e){return!!(e.appName||e.appBundleId)}function Go(e,t){return!!(F(e)&&t.surface!==void 0&&t.surface!==`app`&&t.surface!==`frontmost-app`)}function Ko(e,t){let n=Ze(e);return!n||!t?!1:n.some(e=>e.length>0&&e.every(e=>qo(t,e)))}function qo(e,t){return Object.hasOwn(e.operations,t)?e.operations[t]?.available===!0:!1}async function Jo(e){let{req:t,sessionName:n,sessionStore:r,bindDevice:i,inspectFacts:a,platformServices:o}=e,s=await Yo(t,e.providerAppCatalog);if(s)return s;let c=await es({req:t,sessionName:n,sessionStore:r,androidAvdSelection:`include-stopped`,platformServices:o});if(`response`in c)return c.response;let{device:l}=c,u=yn(t.flags?.appsFilter),d=V(t.flags?.androidDeviceAllowlist,e.env),f=await Qo({device:l,inspectFacts:a,bindDevice:i,platformServices:o});if(`response`in f)return f.response;let p=f.runtime;return $o(await Ao(p,await ko(p,{serial:t.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0}),u))}async function Yo(e,t){let n=Xo(e);if(!(!t||!n||!t.supports(n.provider)))return{ok:!0,data:{apps:[...await t.list(n,Wr(e.meta?.requestId))]}}}function Xo(e){let t=pr(e);if(t.leaseId)return;let n=t.leaseProvider;if(!n)return;let r=e.flags?.platform;if(r===`android`||r===`ios`)return{provider:n,platform:r,...e.internal?.publicNetworkOnly?{publicNetworkOnly:!0}:{}}}async function Zo(e,t){if(t)try{return await t(e)}catch{return}}async function Qo(e){let t=await G(e.inspectFacts)(e.device),n=[t.operations.ensureReady,t.operations.listApps].find(e=>!e.available);return n&&!n.available?{response:{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`apps is not supported on this device`,...n.hint?{hint:n.hint}:{}}}}:{runtime:await W(e.bindDevice)(e.device,st)}}function $o(e){return{ok:!0,data:{apps:e.map(e=>e.name&&e.name!==e.id?`${e.name} (${e.id})`:e.id)}}}async function es(e){let{req:t,sessionName:n,sessionStore:r,androidAvdSelection:i,platformServices:a}=e,o=r.get(n),s=t.flags??{},c=J(t.command,o,s);return c?{response:c}:{device:await Y({session:o,flags:s,env:r.host.env,platformServices:a,androidAvdSelection:i})}}function ts({simulatorSetPath:e,iosPhysicalDeviceBackend:t,appleOs:n,...r}){return{...r,platform:M({platform:r.platform,appleOs:n}),...P(r.platform)&&n?{appleOs:n}:{}}}function ns(e,t){return _e(e,t)}function rs(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Date.now()+e:void 0}function is(e){return m(`INVALID_ARGS`,e)}function as(e,t,n,r,a){try{return e.resolveRequestedOpenSurface({device:t,surfaceFlag:n,openTarget:r,existingSurface:a})}catch(e){return m(e instanceof i?e.code:`INVALID_ARGS`,String(e.message))}}async function os(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i,platformServices:a}=e;if(!t)return null;let o=await a.validateOpenRelaunchTarget({target:n,platform:i.platform,surface:r});return o?is(o):null}async function ss(e){let{shouldRelaunch:t,openTarget:n,platform:r,platformServices:i}=e;if(!t)return null;let a=await i.validateOpenRelaunchTarget({target:n,platform:r});return a?is(a):null}function cs(e){let t=yr(e);if(!t.ok)return{type:`response`,response:t};let{runtime:n,previousRuntime:r,replacedStoredRuntime:i}=t.data;return{type:`plan`,plan:{runtime:n,previousRuntime:r,replacedStoredRuntime:i,applyRuntimeHints:kr(n),clearRemovedRuntimeHints:wr({replacedStoredRuntime:i,previousRuntime:r,runtime:n,session:e.existingSession})}}}async function ls(e){let{req:t,logPath:n,surface:r,openTarget:a,existingSession:o,runtime:s,runtimeHintPlan:c,clearRuntimeHints:l,foreground:u}=e;await s.operations.prepareApplicationOpen({target:a,currentAppBundleId:o?.appBundleId,hasExistingSession:o!==void 0,surface:r,prewarmRunnerOnColdBoot:r===`app`&&!!a&&!y(a??``),execution:{startupDeadlineAtMs:ds(t),requestId:t.meta?.requestId,logPath:n,traceLogPath:o?.trace?.outPath,verbose:t.flags?.verbose,iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir,runnerLeaseContext:fr(t)}});let{appBundleId:d,appName:f}=await us({runtime:s,surface:r,openTarget:a,existingAppBundleId:o?.appBundleId,foreground:u});if(c.clearRemovedRuntimeHints){if(!l)throw new i(`COMMAND_FAILED`,`Runtime hint clear operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await Cr({replacedStoredRuntime:c.replacedStoredRuntime,previousRuntime:c.previousRuntime,runtime:c.runtime,session:o,clearRuntimeHints:l})}return{type:`details`,details:{appBundleId:d,appName:f,runtime:c.runtime}}}async function us(e){let{runtime:t,surface:n,openTarget:r,existingAppBundleId:i,foreground:a}=e,o=await t.operations.resolveOpenTarget({target:r,currentAppBundleId:i,surface:n,foreground:a});return{appBundleId:o.appBundleId,appName:o.appName}}function ds(e){return rs(e.flags?.timeoutMs)}async function fs(e){let{req:t,hasExistingSession:n}=e;return t.flags?.foreground===!0?t.positionals?.[0]?{type:`resolved`,req:t}:n?{type:`response`,response:m(`INVALID_ARGS`,`open --foreground only applies to a fresh session. Close the current session first, or omit --foreground.`)}:t.flags?.udid!==void 0||t.flags?.device!==void 0?{type:`response`,response:m(`INVALID_ARGS`,`open --foreground resolves the device itself; drop --udid/--device or open explicitly: agent-device open <app> --udid <udid>.`)}:t.flags?.platform!==void 0&&t.flags.platform!==`ios`?{type:`response`,response:m(`INVALID_ARGS`,`open --foreground only supports --platform ios; drop the flag or pass --platform ios.`)}:{type:`resolved`,req:{...t,flags:{...t.flags,platform:`ios`}}}:{type:`not-requested`}}async function ps(e){let{req:t,ref:n,logPath:r,sessionStore:i,openResponse:a}=e;if(!a.ok||t.flags?.foreground!==!0)return a;try{let o=await pi({createCommandSurface:e.createCommandSurface,req:{...t,command:`snapshot`,positionals:[],flags:{...t.flags,snapshotInteractiveOnly:!0,noRecord:!0}},sessionName:n.address,sessionRef:n,logPath:r,sessionStore:i,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return o.ok?{ok:!0,data:{...a.data,snapshot:o.data}}:ms(a.data,o.error)}catch(e){return ms(a.data,c(e))}}function ms(e,t){return{ok:!0,data:{...e,warnings:[...vn(e),`The session is open, but the initial interactive snapshot failed (${t.code}: ${t.message}). Run: agent-device snapshot -i`],initialSnapshotError:t}}}function hs(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,appName:o,appBundleId:s,surface:c,startup:l,timing:u,device:d,runtime:f,runtimeHintCount:p,sessionReused:m,selection:h,launchConfirmation:g}=e,_={session:t,surface:c,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,sessionReused:m,...gs(h)};return o&&(_.appName=o),s&&(_.appBundleId=s),l&&(_.startup=l),u&&(_.timing=u),Object.assign(_,g??{}),f&&p(f)>0&&(_.runtime=f),d&&(_.platform=M(d),_.target=d.target??`mobile`,_.device=d.name,_.id=d.id,_.kind=d.kind,ye(d.platform)&&(_.serial=d.id)),d&&N(d)&&(_.device_udid=d.id,_.ios_simulator_device_set=d.simulatorSetPath??null),{..._,...R(`Opened: ${o??s??t}`)}}function gs(e){if(!e)return{};let{device:t,...n}=e;return{selection:n}}function X(e,t,n){n?(e.assertAdmissionOpen(n.address),e.requireCurrent(n)):e.assertPublishable(t)}function _s(e){let{req:t,sessionStore:n,sessionName:r,existingRef:i,device:a,surface:o,appBundleId:s,appName:c,deviceClaim:l}=e;if(X(n,r,i),i){let e=n.update(i,{device:a,surface:o,appBundleId:s,appName:c});return e.lease=cn({req:t,existingLease:e.lease}),l&&(e.deviceClaim=l),Qr(e),n.refresh(i)}return n.publish(r,{name:sn(t),sessionScope:t.internal?.resolvedSessionScope??on(t),device:a,surface:o,appBundleId:s,appName:c,createdAt:Date.now(),actions:[],lease:cn({req:t}),deviceClaim:l})}function vs(e,t){e.warnings=[...vn(e),t]}function ys(e){let{session:t,existingSession:n,saveScriptRequested:r,responseData:i,hostCwd:a}=e;if(!n&&r){Ut(t,{},a);return}Rt(n)&&(Kt(t),vs(i,`Script publication was aborted because this session completed a second open. Start a fresh session with open --save-script to author another script.`))}function bs(e){return`Took the device from session "${e.session}" in workspace "${e.workspace}": that device rebooted after its claim was taken, so its app and runner were already gone.`}function xs(e){switch(e.launchConfirmation){case`accepted`:return{launchConfirmation:`accepted`};case`unanswered`:return{launchConfirmation:`unanswered`,launchConfirmationReason:e.launchConfirmationReason};default:return e.launchConfirmationProbeFailure?{launchConfirmationProbeFailure:e.launchConfirmationProbeFailure}:{}}}function Ss(){return"agent-device could not read whether iOS is asking to confirm the launch URL, so the launch URL may still be held by a prompt. Check with `alert get` before retrying."}function Cs(e){return e===`url-owner-unresolved`?"iOS is still holding the launch confirmation and the installed app that owns the launch URL's scheme could not be resolved, so this launch URL has not reached the app. Answer it with `alert accept`.":"iOS shows an alert this open did not recognize (alert-unrecognized), so it left the launch URL unconfirmed. Inspect the current alert with `alert get` before answering it with `alert accept`."}function ws(e,t){if(e.platform!==`android`)return!1;let n=t.flags?.testIme;return n===void 0?e.kind===`emulator`:n}function Ts(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:`open-command-roundtrip`,appTarget:t,appBundleId:n}}async function Es(e,t,n){if(!t)return;let r=await sr(t,n);if(r.status!==`renewed`)return r.conflict?an(e,r.conflict):m(`DEVICE_IN_USE`,`${e.name} no longer holds the claim this open was made with.`,{reason:`claim-lost-during-open`,deviceKey:t.deviceKey,hint:`Close this session and open the device again to claim it.`})}async function Ds(e){let{req:t,sessionName:n,sessionStore:r,logPath:i,device:a,openTarget:s,openPositionals:c,appName:l,surface:u,appBundleId:d,runtimeHints:f,lifecycle:p,applyRuntimeHints:h,existingRef:g,deviceClaim:_,tookOverDeviceClaim:v,selection:y}=e;X(r,n,g);let b=g?r.requireCurrent(g):void 0,x=b?.snapshot,S=t.flags?.relaunch===!0,C=d,w=Date.now(),ee=await Os({req:t,sessionName:n,sessionStore:r,device:a,surface:u,sessionAppBundleId:C,appName:l,existingRef:g});if(ee.type===`response`)return ee;let T=ee.ref;X(r,n,T);let E=T?r.requireCurrent(T):void 0,te=Date.now(),D=await p.operations.openApplication({target:s,positionals:c,outPath:t.flags?.out,runtimeLaunchUrl:f?.launchUrl,appBundleId:C,surface:u,hasExistingSession:b!==void 0,relaunch:S,prewarmRunnerBeforeOpen:t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,enableTestIme:ws(a,t),stateDir:r.resolveDaemonStateDir(),runtimeHints:Ar(f),applyRuntimeHints:h,execution:so(t,i,E?.trace?.outPath)});C=D.appBundleId??C;let O={...D.timing},ne=mi(y),re=s?Ts(te,s,C):void 0;if(Gr(t.meta?.requestId)){let e=o();return{type:`response`,response:m(e.code,e.message,e.details)}}X(r,n,T),g&&er({session:r.requireCurrent(g),command:`open`,positionals:[],flags:void 0,androidFreshnessBaseline:x});let k=r.ensureSessionDir(n),ie=Cn(k,t.meta?.requestId??he().requestId);O.totalDurationMs=Math.max(0,Date.now()-w),j({level:`info`,phase:`open_timing`,durationMs:O.totalDurationMs,data:O});let A=hs({sessionName:E?.name??sn(t),sessionStateDir:k,runnerLogPath:Sn(k),requestLogPath:ie,eventLogPath:r.resolveEventLogPath(n),appName:l,appBundleId:C,surface:u,startup:re,timing:O,device:a,runtime:f,runtimeHintCount:Er,sessionReused:b!==void 0,selection:ne,launchConfirmation:xs(D)});v&&vs(A,bs(v)),D.launchConfirmation===`unanswered`&&vs(A,Cs(D.launchConfirmationReason)),D.launchConfirmation===void 0&&D.launchConfirmationProbeFailure&&vs(A,Ss());let ae=_s({req:t,sessionStore:r,sessionName:n,existingRef:T,device:a,surface:u,appBundleId:C,appName:l,deviceClaim:_}),oe=r.requireCurrent(ae);return Qn(oe,O.postOpenObservation),t.runtime!==void 0&&vr(r,n,f),ys({session:oe,existingSession:g?oe:void 0,saveScriptRequested:!!t.flags?.saveScript,responseData:A,hostCwd:r.host.cwd}),r.recordAction(ae,{command:`open`,positionals:c,flags:t.flags??{},runtime:t.runtime===void 0?void 0:f,result:A}),{type:`opened`,ref:ae,response:{ok:!0,data:A}}}async function Os(e){let{req:t,sessionName:n,sessionStore:r,existingRef:i}=e,a=t.internal?.openLifecycle?.beforeDispatch;if(!a)return{type:`session`,ref:i};let o=_s({req:t,sessionName:n,sessionStore:r,existingRef:i,device:e.device,surface:e.surface,appBundleId:e.sessionAppBundleId,appName:e.appName}),s=await a();return s&&!s.ok?{type:`response`,response:s}:(X(r,n,o),{type:`session`,ref:r.refresh(o)})}function ks(e){return e.internal?.admittedLease?.backend===`macos-app`}function As(e){let{req:t,device:n,sessionStore:r}=e,i=ks(t)?r.listRefs().find(e=>e.session.device.id===n.id&&e.session.lease?.leaseBackend!==`macos-app`):r.findByDevice(n.id);if(!i)return;let a=dn(t);return ln(t,i.session)?mn(i,n,a):nn(i,n,a)}async function js(e){let{req:t,device:n,owner:r,sessionName:i,sessionStore:a,reconcileOrphanedDeviceClaim:o,platformServices:s}=e;switch(rn(r,t.internal?.admittedLease)){case`none`:return{status:`not-required`};case`ordinary`:return await cr({device:n,session:i,workspace:t.meta?.cwd??e.host.cwd,stateDir:a.resolveDaemonStateDir(),env:e.host.env,reconcileOrphanedDeviceClaim:o,observeDeviceBoot:s.deviceBootObservation})}}async function Ms(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,device:a,surface:o,openTarget:s,lifecycle:c,runtimeHintPlan:l,applyRuntimeHints:u,clearRuntimeHints:d,reconcileOrphanedDeviceClaim:f,selection:p,platformServices:m}=e;X(i,n,void 0);let h=As({req:t,device:a,sessionStore:i});if(h)return{type:`response`,response:h};let g=await js({host:e.host,req:t,device:a,owner:c.owner,sessionName:n,sessionStore:i,reconcileOrphanedDeviceClaim:f,platformServices:m});if(g.status===`conflict`)return{type:`response`,response:an(a,g.conflict)};let _=g.status===`acquired`?g.ownership:void 0,v=g.status===`acquired`?g.tookOver:void 0,y={mayHaveStarted:!1},b=async()=>await Ns({ownership:_,effects:y,sessionName:n,sessionStore:i,env:e.host.env});try{X(i,n,void 0);let f=await ls({req:t,logPath:r,surface:o,openTarget:s,runtime:c,runtimeHintPlan:l,clearRuntimeHints:d,foreground:t.flags?.foreground===!0&&s===void 0});if(f.type===`response`)return await b(),{type:`response`,response:f.response};let m=await Es(a,_,e.host.env);if(m)return{type:`response`,response:m};y.mayHaveStarted=!0;let h=t.positionals??[],g=s??f.details.appBundleId,x=await Ds({req:t,sessionName:n,sessionStore:i,logPath:r,device:a,openTarget:g,openPositionals:h.length>0?h:g?[g]:[],appBundleId:f.details.appBundleId,appName:f.details.appName,runtimeHints:f.details.runtime,lifecycle:c,applyRuntimeHints:u,surface:o,deviceClaim:_,tookOverDeviceClaim:v,selection:p});return x.response.ok||await b(),x}catch(e){throw await b(),e}}async function Ns(e){let{ownership:t,effects:n,sessionName:r,sessionStore:i,env:a}=e;if(!t)return;if(!n.mayHaveStarted){await or(t,a);return}if(i.get(r)?.deviceClaim?.ownerToken===t.ownerToken)return;let o=await ur(t,a);j({level:`warn`,phase:`device_claim_open_effects_unconfirmed`,data:{deviceKey:t.deviceKey,outcome:o}})}const Ps=new WeakMap;function Fs(e){let t=Ps.get(e);return t||(t=new Map,Ps.set(e,t)),t}async function Is(e){let t=Ae({applyRuntimeHints:e.runtimeHintPlan.applyRuntimeHints,clearRemovedRuntimeHints:e.runtimeHintPlan.clearRemovedRuntimeHints}),n=await Yr({...e,command:`open`,required:t.use.required});if(n.type===`response`)return n;let r=n.bind;switch(t.kind){case`open`:return{type:`runtime`,runtime:await r(e.device,Ue)};case`open-apply-runtime-hints`:{let t=await r(e.device,De);return{type:`runtime`,runtime:t,applyRuntimeHints:t.operations.applyRuntimeHints}}case`open-clear-runtime-hints`:{let t=await r(e.device,Me);return{type:`runtime`,runtime:t,clearRuntimeHints:t.operations.clearRuntimeHints}}case`open-apply-and-clear-runtime-hints`:{let t=await r(e.device,We);return{type:`runtime`,runtime:t,applyRuntimeHints:t.operations.applyRuntimeHints,clearRuntimeHints:t.operations.clearRuntimeHints}}}}async function Ls(e){let t=cs(e);if(t.type===`response`)return t;let n=await Is({device:e.device,runtimeHintPlan:t.plan,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return n.type===`response`?n:{type:`runtime`,runtimeHintPlan:t.plan,admission:n}}async function Rs(e){let{sessionName:t,logPath:n,sessionStore:r}=e,i=r.lookup(t),a=await fs({req:e.req,hasExistingSession:!!i});if(a.type===`response`)return{type:`response`,response:a.response};let o=a.type===`resolved`?a.req:e.req;if(X(r,t,i),i){let a=r.requireCurrent(i);if(o.flags?.saveScript)return{type:`response`,response:m(`INVALID_ARGS`,`open --save-script can only arm a fresh session. Use the current session without --save-script, or close it and start a fresh session.`)};let s=o.flags?.relaunch===!0,c=o.positionals?.[0],l=c??(s?a.appName:void 0),u=as(e.platformServices,a.device,o.flags?.surface,l,a.surface);if(typeof u!=`string`)return{type:`response`,response:u};if(!l&&u===`app`)return{type:`response`,response:is(s?`open --relaunch requires an app name or an active session app.`:`Session already active. Close it first or pass a new --session name.`)};let d=await os({shouldRelaunch:s,openTarget:l,surface:u,device:a.device,platformServices:e.platformServices});if(d)return{type:`response`,response:d};let f=r.requireCurrent(i),p=await Es(f.device,f.deviceClaim,e.host.env);if(p)return{type:`response`,response:p};let h=await Hi(a.device,e.platformServices,e.host.env),g=hi(h);await o.internal?.retainDeviceExecutionLock?.(h.id);let _=await Ls({req:o,sessionStore:r,sessionName:t,device:h,existingSession:a,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(_.type===`response`)return{type:`response`,response:_.response};let{admission:v,runtimeHintPlan:y}=_;X(r,t,i);let b=r.requireCurrent(i);B(b);let x=await ls({req:o,logPath:n,surface:u,openTarget:l,existingSession:b,runtime:v.runtime,runtimeHintPlan:y,clearRuntimeHints:v.clearRuntimeHints,foreground:!1});if(x.type===`response`)return{type:`response`,response:x.response};X(r,t,i);let S=await Es(h,r.requireCurrent(i).deviceClaim,e.host.env);return S?{type:`response`,response:S}:await Ds({req:o,sessionName:t,sessionStore:r,logPath:n,device:h,openTarget:l,openPositionals:c?o.positionals??[]:l?[l]:[],appBundleId:x.details.appBundleId,appName:x.details.appName,runtimeHints:x.details.runtime,lifecycle:v.runtime,applyRuntimeHints:v.applyRuntimeHints,surface:u,existingRef:i,selection:g})}let s=o.flags?.relaunch===!0,c=o.positionals?.[0];if(s&&!c)return{type:`response`,response:is(`open --relaunch requires an app argument.`)};let l=await ss({shouldRelaunch:s,openTarget:c,platform:o.flags?.platform===`android`?`android`:void 0,platformServices:e.platformServices});if(l)return{type:`response`,response:l};let u=await Un(o.flags??{},qn(c,e.host.env)),d=u.device;await o.internal?.retainDeviceExecutionLock?.(d.id);let f=as(e.platformServices,d,o.flags?.surface,c);if(typeof f!=`string`)return{type:`response`,response:f};let p=await os({shouldRelaunch:s,openTarget:c,surface:f,device:d,platformServices:e.platformServices});if(p)return{type:`response`,response:p};let h=await Ls({req:o,sessionStore:r,sessionName:t,device:d,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(h.type===`response`)return{type:`response`,response:h.response};let{admission:g,runtimeHintPlan:_}=h;return await Tn(Fs(r),d.id,async()=>await Ms({host:e.host,req:o,sessionName:t,logPath:n,sessionStore:r,device:d,surface:f,openTarget:c,lifecycle:g.runtime,runtimeHintPlan:_,applyRuntimeHints:g.applyRuntimeHints,clearRuntimeHints:g.clearRuntimeHints,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim,platformServices:e.platformServices,selection:u}))}async function zs(e){let t=await Rs(e),n=t.response;return t.type!==`opened`||e.req.flags?.foreground!==!0?n:await ps({...e,inspectFacts:G(e.inspectFacts),bindDevice:W(e.bindDevice),openResponse:n,ref:t.ref})}function Bs(e,t){return{ok:!0,data:{platform:M(e),target:e.target??`mobile`,device:e.name,id:e.id,kind:e.kind,...t,...P(e.platform)&&e.appleOs?{appleOs:e.appleOs}:{}}}}function Vs(e){return t=>m(e?`INVALID_ARGS`:`UNSUPPORTED_OPERATION`,e?`boot --headless is supported only for Android emulators.`:`boot is not supported on this device`,void 0,t.hint?{hint:t.hint}:void 0)}function Hs(e,t){return!!(e?.trim()||t?.platform===`android`&&t.kind===`emulator`)}async function Us(t,n){let{sessionName:r,sessionStore:i,req:a,platformServices:o}=t,s=i.get(r),c=a.flags??{};try{let e=await Y({session:s,flags:c,env:i.host.env,androidAvdSelection:`include-stopped`,platformServices:o});return c.target&&(e.target??`mobile`)!==c.target?{refusal:m(`DEVICE_NOT_FOUND`,`No ${e.platform} device found matching --target ${c.target}.`)}:e}catch(t){if(n&&!Hs(c.device,s?.device)&&e(t).code===`DEVICE_NOT_FOUND`)return{refusal:m(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`)};throw t}}async function Ws(e){let t=e.req.flags??{},n=J(e.req.command,e.sessionStore.get(e.sessionName),t);if(n)return n;let r=V(t.androidDeviceAllowlist,e.host.env),i=r?[...r].sort():void 0,a=ke({headless:t.headless===!0}),o=await Us(e,a.kind===`boot-target-headless`);if(`refusal`in o)return o.refusal;let s=await Yr({command:`boot`,device:o,required:a.use.required,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,unavailableResponse:Vs(a.kind===`boot-target-headless`)});if(s.type===`response`)return s.response;let c={serial:t.serial,androidSerialAllowlist:i,deadlineAtMs:rs(t.timeoutMs)};return Bs(a.kind===`boot-target-headless`?await(await s.bind(o,a.use)).operations.bootTargetHeadless(c):await(await s.bind(o,a.use)).operations.bootTarget(c),{booted:!0})}function Gs(e){return e.available?null:m(`UNSUPPORTED_OPERATION`,`shutdown is supported only for Apple simulators and Android emulators.`,void 0,e.hint?{hint:e.hint}:void 0)}function Ks(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}async function qs(e){let t=e.sessionStore.get(e.sessionName),n=e.req.flags??{},r=J(e.req.command,t,n);if(r)return r;let i=await Y({flags:n,session:t,env:e.sessionStore.host.env,androidAvdSelection:`include-stopped`,platformServices:e.platformServices}),a=Gs((await G(e.inspectFacts)(i)).operations.shutdownTarget);if(a)return a;if(t&&t.device.platform===i.platform&&t.device.id===i.id)return m(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${e.sessionName}`,session:e.sessionName,platform:M(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind});let o=await(await W(e.bindDevice)(i,Pe)).operations.shutdownTarget();return o.success?Bs(i,{shutdown:o}):m(o.error?.code??`COMMAND_FAILED`,Ks(o),{platform:M(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind,shutdown:o})}function Js(e,t){return P(t)?m(`SESSION_NOT_FOUND`,`No active session "${e}". Run open with --session ${e} first.`,r(e)):m(`SESSION_NOT_FOUND`,`No active session "${e}". Run open with --session ${e} first, or omit --session to query by device selector.`,r(e))}function Ys(e){return m(`SESSION_NOT_FOUND`,e===`macos`?`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`:`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`)}async function Xs(t,n){if(!n.appBundleId)return;let r=await H({command:`appstate`,device:n.device,use:Ye,inspectFacts:t.inspectFacts,platformServices:t.platformServices,bindDevice:t.bindDevice});if(r.type!==`response`)try{return(await r.runtime.operations.appState({appBundleId:n.appBundleId})).applicationState}catch(t){if(s(t))throw t;j({level:`warn`,phase:`apple_appstate_runner_read_failed`,data:{code:e(t).code,message:e(t).message}});return}}function Zs(e){if(!(!F(e.device)||!e.surface)&&e.surface!==`app`&&e.surface!==`frontmost-app`)return{ok:!0,data:{platform:M(e.device),appName:e.surface,appBundleId:e.appBundleId,source:`session`,surface:e.surface}}}async function Qs(e,t){if(!t.appName&&!t.appBundleId){let e=Zs(t);if(e)return e;let n=F(t.device)?`macOS`:`iOS`;return m(`COMMAND_FAILED`,`No foreground app is tracked for this ${n} session. Open an app in the session, then retry appstate.`)}let n=await Xs(e,t),r=t.appName??t.appBundleId;return{ok:!0,data:{platform:M(t.device),appName:r??`unknown`,appBundleId:t.appBundleId,source:n?`runner`:`session`,...n?{state:n}:{},surface:t.surface??`app`,...N(t.device)?{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}:{}}}}function $s(e,t){let n=V(e,t);return n?[...n].sort():void 0}async function ec(e,t,n){if(N(t)||F(t))return n?Js(e.sessionName,t.platform):Ys(F(t)?`macos`:`ios`);let r=e.req.flags??{},i=await H({command:`appstate`,device:t,use:Ye,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i.type===`response`)return i.response;let a=i.runtime;await a.operations.ensureReady({serial:r.serial,androidSerialAllowlist:$s(r.androidDeviceAllowlist,e.host.env)});let o=await a.operations.appState();return{ok:!0,data:{platform:M(t),package:o.package,activity:o.activity}}}function tc(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&l(t)&&(!Qt(a)||P(o)))return{refusal:Js(n,o)};let s=J(`appstate`,i,a);if(s)return{refusal:s};let c=P(i?.device.platform)&&Ui(a,i);return o===`ios`&&!c?{refusal:Ys(`ios`)}:o===`macos`&&!c?{refusal:Ys(`macos`)}:c&&i?{answeredBy:`apple-session`,session:i}:{answeredBy:`device-runtime`,session:i,namedSessionMissing:!i&&l(t)}}async function nc(e){let t=tc(e);return`refusal`in t?t.refusal:t.answeredBy===`apple-session`?await Qs(e,t.session):await ec(e,await Y({session:t.session,flags:e.req.flags??{},env:e.sessionStore.host.env,platformServices:e.platformServices}),t.namedSessionMissing)}function rc(e){return Rn.createNextFence({admissionLedger:e.ledger,resourcePath:e.resourcePath,device:e.device})}async function ic(e){try{return await ac(e)}catch(e){return{ok:!1,error:c(e)}}}async function ac(e){let t=oc(e);if(!t.ok)return t;let n=t.ref,r=e.sessionStore.requireCurrent(n),i=Ie(e.req.positionals),a=await e.inspectFacts(r.device),o=a.operations.audioProbeStart,s=a.operations.audioProbeQuery,c=o.available?`capture`:s.available?`query`:void 0;if(c===void 0)return sc(o,s);let l=Le({probeAction:i.probeAction,mode:c});switch(l.kind){case`query`:return{ok:!0,data:await(await e.bindDevice(r.device,l.use)).operations.audioProbeQuery({action:l.action,durationMs:i.durationMs,bucketMs:i.bucketMs})};case`capture-start`:return await cc(e,n,i,l.use);case`capture-status`:return await lc(e,n);case`capture-stop`:return await uc(e,n)}}function oc(e){let t=e.sessionStore.lookup(e.sessionName);return t?{ok:!0,ref:t}:m(`SESSION_NOT_FOUND`,`audio requires an active session`)}function sc(e,t){let n=(e.available?void 0:e.hint)??(t.available?void 0:t.hint);return m(`UNSUPPORTED_OPERATION`,n??`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`)}async function cc(e,t,n,r){let i=e.sessionStore.requireCurrent(t),a=Jr(e.sessionStore,t);i.audioProbe&&(await Mn({intent:`disposal`,binding:a}),i=e.sessionStore.requireCurrent(t));let o=await e.bindDevice(i.device,r),s=Nn.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),c=Nn.createNextFence({admissionLedger:e.audioProbeAdmissionLedger,resourcePath:s,device:i.device}),l=q.join(e.sessionStore.ensureSessionDir(e.sessionName),`audio-probe.json`);a.assertAdoptable();let u=await o.operations.audioProbeStart({sessionId:e.sessionName,statusPath:l,durationMs:n.durationMs,bucketMs:n.bucketMs,fence:c});await Fn({admissionLedger:e.audioProbeAdmissionLedger,binding:a,device:i.device,owner:o.owner,fence:c,...u,throwIfCanceled:e.throwIfCanceled});let d=a.read();if(!d)throw TypeError(`Audio probe adoption did not publish a live handle`);return{ok:!0,data:await d.handle.status()}}async function lc(e,t){let n=Jr(e.sessionStore,t),r=n.read();if(!r)return{ok:!0,data:dc()};let i=await r.handle.status();return i.state===`stopped`&&await Mn({intent:`disposal`,binding:n}),{ok:!0,data:i}}async function uc(e,t){let n=Jr(e.sessionStore,t);return n.read()?{ok:!0,data:await Mn({intent:`capture`,binding:n})}:{ok:!0,data:dc()}}function dc(){return gi({state:`stopped`,source:`system-audio`,backend:`host-system-audio`,durationMs:0,bucketMs:0,sourceCount:0,reason:`not-started`,notes:[`No active host audio probe is running.`]})}async function fc(e){let t=e.sessionStore.lookup(e.sessionName);if(!t)return m(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let n=e.sessionStore.requireCurrent(t),r={...e,ref:t};try{if(gn(e.req.positionals?.[0]))throw new i(`INVALID_ARGS`,_n);Mc(e.req);let t=jn({positionals:e.req.positionals,kind:Pc(e.req.flags?.kind),outPath:Pc(e.req.flags?.out)}),a=In(t);if(a.kind===`capture-stop`)return pc(r,await _c(r,n,a.request));let o=await ni({device:n.device,plan:a,inspectFacts:e.inspectFacts});return o.admitted?pc(r,await mc(r,n,o)):U(`perf`,o.fact)??m(`UNSUPPORTED_OPERATION`,`perf is not supported on this device`)}catch(e){return{ok:!1,error:c(e)}}}function pc(e,t){return t.ok&&I(e.sessionStore,e.ref,e.req,`perf`,C(t.data)?{...t.data}:{}),t}async function mc(e,t,n){let{device:r,plan:a}=ti(n),o=W(e.bindDevice);switch(a.kind){case`frames`:return{ok:!0,data:Cc(t,await(await o(r,a.use)).operations.perfFrames({appId:t.appBundleId}))};case`memory-sample`:return{ok:!0,data:Oc(t,await(await o(r,a.use)).operations.perfMemorySample({appId:t.appBundleId}))};case`memory-snapshot`:return{ok:!0,data:kc(t,await(await o(r,a.use)).operations.perfMemorySnapshot({appId:t.appBundleId,kind:a.request.kind,outPath:a.request.outPath?z(a.request.outPath,e.req.meta?.cwd??e.host.cwd):void 0,artifactsDir:q.join(e.sessionStore.ensureSessionDir(e.sessionName),`artifacts`)}))};case`capture-start`:return await hc(e,t,await o(r,a.use),a.request);case`profile-report`:{let n=await o(r,a.use),s=t.lastPerfProfile,c=a.request.tracePath??s?.outPath;if(!c)throw new i(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`);if(t.perfCapture)throw new i(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let l=jc(e,a.request.outPath,`cpu-report.json`);return{ok:!0,data:{perf:`reported`,...await n.operations.perfProfileReport({appId:t.appBundleId,kind:a.request.kind,tracePath:z(c,e.req.meta?.cwd??e.host.cwd),outPath:l,template:a.request.template??(s?.kind===`xctrace`?s.template:void 0),profile:s})}}}}}async function hc(e,t,n,r){if(t.perfCapture)return m(`INVALID_ARGS`,`native perf capture already in progress`);if(!t.appBundleId)return m(`COMMAND_FAILED`,`No app is associated with this session.`,{hint:`Run open <app> first so perf can resolve the app process identity.`});let i=r.kind===`xctrace`?`perf-${r.area===`cpu`?`cpu-profile`:`trace`}.trace`:r.kind===`perfetto`?`app.perfetto-trace`:`cpu.perf.data`,a=jc(e,r.outPath,i),o=An.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),s=An.createNextFence({admissionLedger:gc(e),resourcePath:o,device:t.device}),c=qr(e.sessionStore,e.ref);c.assertAdoptable();let l=await n.operations.perfNativeCaptureStart({sessionId:e.sessionName,appId:t.appBundleId,mode:r.area===`cpu`?`cpu-profile`:`trace`,kind:r.kind,template:r.template,outPath:a,fence:s});return await Pn({admissionLedger:gc(e),binding:c,device:t.device,owner:n.owner,fence:s,pendingHandle:l.pendingHandle,envelope:l.envelope,throwIfCanceled:e.throwIfCanceled}),{ok:!0,data:l.response}}function gc(e){if(e.perfCaptureAdmissionLedger)return e.perfCaptureAdmissionLedger;throw new i(`COMMAND_FAILED`,`Perf capture admission ledger is not configured`,{reason:`runtime-gateway-missing`})}async function _c(e,t,n){let r=t.perfCapture;if(!r)return m(`INVALID_ARGS`,`no active native perf capture`);let i=Sc(r.handle.inspect(),n);if(i)return m(`INVALID_ARGS`,i);n.outPath&&r.handle.setOutputPath(z(n.outPath,e.req.meta?.cwd??e.host.cwd));let a=await Ln({intent:`capture`,binding:qr(e.sessionStore,e.ref)});if(n.area===`cpu`){let t=vc(a);e.sessionStore.update(e.ref,{lastPerfProfile:t})}return{ok:!0,data:a}}function vc(e){if(yc(e)||bc(e))return e;throw new i(`COMMAND_FAILED`,`Stopped CPU profile metadata is malformed.`)}function yc(e){return e.kind===`xctrace`&&e.mode===`cpu-profile`&&typeof e.outPath==`string`&&typeof e.template==`string`}function bc(e){return e.kind===`simpleperf`&&e.mode===`cpu-profile`&&xc(e,[`outPath`,`packageName`,`appPid`,`profilerPid`,`remotePath`])}function xc(e,t){return t.every(t=>typeof e[t]==`string`)}function Sc(e,t){let n=t.area===`cpu`?`cpu-profile`:`trace`;if(e.kind!==t.kind||e.mode!==n)return`No ${t.kind} ${n} is active for this session.`}function Cc(e,t){return{...Ac(e),metrics:{fps:wc(t.metric,e)},sampling:{fps:t.sampling}}}function wc(e,t){if(!C(e)||e.available!==!0)return e;let n=Tc(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function Tc(e,t){let n=Ec(t.windowStartedAt),r=Ec(t.windowEndedAt)??Ec(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(({ts:e})=>e>=n&&e<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:Dc(e)})).slice(-12)}function Ec(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Dc(e){for(let t of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=e.result?.[t];if(typeof n==`string`&&n.length>0)return n}}function Oc(e,t){return{...Ac(e),metrics:{memory:t.metric},sampling:{memory:t.sampling}}}function kc(e,t){return{...Ac(e),artifact:t.artifact,sampling:{snapshot:t.sampling},support:t.support}}function Ac(e){return{session:e.name,platform:M(e.device),device:e.device.name,deviceId:e.device.id}}function jc(e,t,n){return t?z(t,e.req.meta?.cwd??e.host.cwd):q.join(e.sessionStore.ensureSessionDir(e.sessionName),`${Nc()}-${n}`)}function Mc(e){let t=e.positionals?.[0]?.toLowerCase(),n=e.positionals?.[1]?.toLowerCase();if(e.flags?.out&&t!==`cpu`&&t!==`trace`&&(t!==`memory`||n!==`snapshot`))throw new i(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}function Nc(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function Pc(e){return typeof e==`string`&&e.length>0?e:void 0}const Fc=[`dump`,`log`],Ic=`network requires ${Fc.join(` or `)}`,Lc=`network include mode must be one of: ${d.join(`, `)}`,Rc=2048;async function zc(e){let t=e.sessionStore.get(e.sessionName);if(!t)return m(`SESSION_NOT_FOUND`,`network requires an active session`);try{let n=Bc(e.bindDevice),r=(await n(t.device,Se)).facts.networkDump;if(!r.available)return Gc(r.hint);let i=Vc(e.req);if(!i.ok)return i;let a=tt({action:i.action,include:i.include}),o=await n(t.device,a.use),s=t.appLog?.handle.inspect();return Kc(await o.operations.networkDump({sessionId:e.sessionName,appBundleId:t.appBundleId,...s?{appLogSnapshot:{state:s.state,startedAt:s.startedAt}}:{},maxEntries:i.maxEntries,include:a.include,maxPayloadChars:Rc,maxScanLines:4e3}),i,!!t.appLog,s?.state)}catch(e){return{ok:!1,error:c(e)}}}function Bc(e){if(e)return e;throw new i(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`})}function Vc(e){let t=Hc(e);if(!t.ok)return t;let n=Uc(e);if(!n.ok)return n;let r=Wc(e);return r.ok?{ok:!0,action:t.action,include:r.include,maxEntries:n.maxEntries}:r}function Hc(e){let t=(e.positionals?.[0]??`dump`).toLowerCase();return Fc.includes(t)?{ok:!0,action:t}:m(`INVALID_ARGS`,Ic)}function Uc(e){let t=e.positionals?.[1]?Number.parseInt(e.positionals[1],10):25;return!Number.isInteger(t)||t<1||t>200?m(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`):{ok:!0,maxEntries:t}}function Wc(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return m(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return d.includes(r)?{ok:!0,include:r}:m(`INVALID_ARGS`,Lc)}function Gc(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`network is not supported on this device`,hint:e}}}function Kc(e,t,n,r){return e.source===`app-log`?{ok:!0,data:{...e.dump,active:n,state:r??`inactive`,backend:e.backend,notes:e.notes}}:{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:Rc,maxScanLines:e.entries.length},notes:e.notes}}}function qc(e,t){let n=ci(e);return{...n,backend:n.backend??t,notes:n.state===`failed`&&e.appLogFailure?[Jc(e.appLogFailure)]:Yc(n.state)}}function Jc(e){return e.hint?`${e.message} ${e.hint}`:e.message}function Yc(e){return e===`failed`?[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`]:e===`ended`?[`The app log stream process ended. Run logs clear --restart before the next capture window.`]:void 0}function Xc(e,t){return nt([...e,...t.notes??[]])}async function Zc(e){let{req:t}=e;return t.command===`perf`?await fc({...e,throwIfCanceled:e.throwIfCanceled??(()=>{})}):t.command===`logs`?$c(e):t.command===`events`?await Qc(e):t.command===`network`?await zc(e):t.command===`audio`?await ic(dl(e)):null}async function Qc(e){let{req:t,sessionName:n,sessionStore:r}=e;try{return await r.flushEvents(n),{ok:!0,data:r.readEvents(n,{limit:t.positionals?.[0],cursor:t.positionals?.[1]})}}catch(e){return{ok:!1,error:c(e)}}}async function $c(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n);if(!i)return m(`SESSION_NOT_FOUND`,`logs requires an active session`);try{let n=r.requireCurrent(i),a=fl({...e,session:n,ref:i}),o=(await a.bindDevice(n.device,Ee)).facts.appLogInspect;if(!o.available)return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`logs is not supported on this device`,hint:o.hint}};let s=nl(Oe({action:t.positionals?.[0],restart:!!t.flags?.restart,marker:t.positionals?.slice(1).join(` `)}),n);return`ok`in s?s:await el(a,s)}catch(e){return{ok:!1,error:c(e)}}}async function el(e,t){switch(t.kind){case`path`:return rl(e,(await(await e.bindDevice(e.session.device,t.use)).operations.appLogInspect()).backend);case`doctor`:return il(e,await(await e.bindDevice(e.session.device,t.use)).operations.appLogDoctor({appBundleId:e.session.appBundleId}));case`start`:case`clear-restart`:return await tl(e,t);case`stop`:return await e.bindDevice(e.session.device,t.use),await ll(e);case`mark`:return await e.bindDevice(e.session.device,t.use),al(t.marker,e.sessionName,e.sessionStore,e.host.env);case`clear`:return await e.bindDevice(e.session.device,t.use),ol(e)}}async function tl(e,t){let n=await e.bindDevice(e.session.device,t.use);return t.kind===`start`?await cl(e,t.appBundleId,n.owner,n.operations.appLogStart):await sl(e,t.appBundleId,n.owner,n.operations.appLogStart)}function nl(e,t){return e.requiresAppSession?t.appBundleId?Object.freeze({...e,appBundleId:t.appBundleId}):m(`INVALID_ARGS`,`logs ${e.kind===`start`?`start`:`clear --restart`} requires an app session; run open <app> first`):e}function rl(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=si(a),s=qc(n,t);return{ok:!0,data:{path:a,active:s.active,state:s.state,backend:s.backend,sizeBytes:o.sizeBytes,modifiedAt:o.modifiedAt,startedAt:s.startedAt?new Date(s.startedAt).toISOString():void 0,failureCode:s.failureCode,failureMessage:s.failureMessage,hint:s.hint??String.raw`Grep the file for token-efficient debugging, e.g. grep -n "Error\|Exception" <path>`,notes:s.notes}}}async function il(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=qc(n,t.backend);return{ok:!0,data:{path:a,active:o.active,state:o.state,backend:o.backend,checks:t.checks,failureCode:o.failureCode,failureMessage:o.failureMessage,hint:o.hint,notes:Xc(t.notes,o)}}}function al(e,t,n,r){let i=n.resolveAppLogPath(t);return ai(i,e,r),{ok:!0,data:{path:i,marked:!0}}}function ol(e){return{ok:!0,data:oi(e)}}async function sl(e,t,n,r){let{session:i,sessionStore:a}=e;i.appLog&&await ii({intent:`disposal`,ref:e.ref,sessionStore:a});let o=oi(e),s=await ul(e,t,r,n);return s.ok?{ok:!0,data:{...o,restarted:!0}}:s}async function cl(e,t,n,r){let{session:i}=e;return i.appLog?m(`INVALID_ARGS`,`app log already streaming; run logs stop first`):await ul(e,t,r,n)}async function ll(e){let{session:t,sessionName:n,sessionStore:r}=e;if(!t.appLog)return m(`INVALID_ARGS`,`no app log stream active`);let i=r.resolveAppLogPath(n);return await ii({intent:`capture`,ref:e.ref,sessionStore:r}),{ok:!0,data:{path:i,stopped:!0}}}async function ul(e,t,n,r){let{session:i,sessionName:a,sessionStore:o}=e,s=o.resolveAppLogPath(a),c=zn.resolvePath(o.resolveSessionDir(a));try{let l=rc({ledger:e.appLogAdmissionLedger,resourcePath:c,device:i.device});li(o,e.ref).assertAdoptable();let u=await n({sessionId:a,appBundleId:t,outputPath:s,pidPath:o.resolveAppLogPidPath(a),fence:l});return await di({admissionLedger:e.appLogAdmissionLedger,ref:e.ref,sessionStore:o,device:i.device,owner:r,fence:l,pendingHandle:u.pendingHandle,envelope:u.envelope,throwIfCanceled:e.throwIfCanceled??(()=>{})}),{ok:!0,data:{path:s,started:!0}}}catch(t){return{ok:!1,error:ui({ref:e.ref,sessionStore:o,error:t})}}}function dl(e){if(!e.bindDevice||!e.inspectFacts)throw new i(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.audioProbeAdmissionLedger)throw new i(`COMMAND_FAILED`,`Audio probe admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{req:e.req,sessionName:e.sessionName,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,audioProbeAdmissionLedger:e.audioProbeAdmissionLedger,throwIfCanceled:e.throwIfCanceled??(()=>{})}}function fl(e){if(!e.bindDevice)throw new i(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.appLogAdmissionLedger)throw new i(`COMMAND_FAILED`,`App-log admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{...e,bindDevice:e.bindDevice,platformServices:e.platformServices,appLogAdmissionLedger:e.appLogAdmissionLedger}}const pl=new WeakMap;function ml(e){return{store:t=>hl(e,t),finalize:(t,n)=>gl({...e,evidence:t,projection:n})}}function hl(e,t){let{sessionStore:n,ref:r}=e;if(!r)throw Error(`Internal observation session is no longer available.`);let i=n.requireCurrent(r);Zr(i,t);let a=i.snapshotGeneration;if(a===void 0)throw Error(`Internal observation did not establish a snapshot generation.`);let o={};return pl.set(o,{ref:r,snapshot:t,snapshotGeneration:a,runtimeRevision:rr(i),refFrame:$n(i)}),{evidence:o,refsGeneration:a}}function gl(e){let t=pl.get(e.evidence);pl.delete(e.evidence);let n=vl(e.projection.refs);if(n.size===0)return{published:!1,reason:`empty`};if(e.signal?.aborted===!0)return{published:!1,reason:`cancelled`};let r=t&&_l(e,t);return!t||!r?{published:!1,reason:`stale-capture`}:e.projection.refsGeneration!==t.snapshotGeneration||!yl(n,t.snapshot)?{published:!1,reason:`invalid-projection`}:(Xr(r,n),{published:!0,refsGeneration:t.snapshotGeneration,refCount:n.size})}function _l(e,t){if(!e.ref||e.ref.lifetime!==t.ref.lifetime)return;let n=e.sessionStore.resolveCurrent(e.ref);return n&&n.snapshot===t.snapshot&&n.snapshotGeneration===t.snapshotGeneration&&rr(n)===t.runtimeRevision&&$n(n)===t.refFrame?n:void 0}function vl(e){let t=new Set;for(let n of e){let e=n.startsWith(`@`)?n.slice(1):n,r=e.indexOf(`~`),i=r===-1?e:e.slice(0,r);i.length>0&&t.add(i)}return t}function yl(e,t){let n=new Set(t.nodes.flatMap(e=>typeof e.ref==`string`?[e.ref]:[]));return[...e].every(e=>n.has(e))}function bl(e){let t=xl(e),n=$e(t);return Ii(`sha256`).update(n,`utf8`).digest(`hex`)}function xl(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>Sl(e,n[t]??null,r?.[t]??null))}}function Sl(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,targetEvidences:e.targetEvidences??null,source:{path:n,line:t}}}function Cl(e,t,n){let{from:r,digest:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e;if(r===void 0&&i===void 0)return{ok:!0,value:0};if(r===void 0||i===void 0)return{ok:!1,message:`replay --from requires --plan-digest (and --plan-digest requires --from).`};let s=wl({from:r,digest:i,planDigest:n,actionCount:t,pendingRecordAndHeal:a,sessionActionsLength:o});return s?{ok:!1,message:s}:{ok:!0,value:r-1}}function wl(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>Tl({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>El({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>Dl(n,r)];for(let e of s){let t=e();if(t)return t}}function Tl(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function El(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(n?.expectedFrom===t&&r===n.actionsCountAtDivergence)return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function Dl(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function Ol(e,t){let n=e.trimStart()[0];if(n===`{`||n===`[`)throw new i(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let r=O(e),a=re(e),o=bl({actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:{platform:t?.platform??A(r.actions)??a.platform,target:t?.target??a.target}}),s=r.actions.length;return{actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:a,planDigest:o,resolveEntryIndex:e=>Cl(e,s,o)}}function kl(e){let{recorded:t,isSelectorWait:n}=e;return n?t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`deferred-landmark`,landmark:t}:{kind:`skip`}}function Al(e){let{recorded:t,token:n}=e;return n===void 0||!n.startsWith(`@`)&&we(`positional`,[n]).kind!==`expression`?{kind:`skip`}:t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`verify`,token:n}}function jl(e,t){if(!(!e||!t)&&(e.documentOrder!==t.documentOrder||e.sibling!==t.sibling))return`position: recorded=doc${e.documentOrder}/sibling${e.sibling} observed=doc${t.documentOrder}/sibling${t.sibling}`}function Ml(e,t,n){let{observed:r,expectedStructural:i,observedStructural:a}=t,o=jl(i,a);return{matchCount:n,observed:r,mismatches:[...r?qe(e,r):[],...o?[o]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}}function Nl(e,t){let{matchCount:n,observed:r,observedAncestry:i}=t;return{matchCount:n,observed:r,mismatches:r?[...qe(e,r),...je(e.ancestry,i)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}}async function Pl(e,t,n,r,i,a){if(n.targetEvidences)return Fl(e,t,n,r,i,a);let o=n.targetEvidence;if(!o)return Z(e,n,r,i,a);let s=e.beginTargetVerification(n,r,i);if(s.kind===`inactive`)return Z(e,n,r,i,a);if(s.kind===`post-resolution`){let c=kl({recorded:o,isSelectorWait:s.isSelectorWait});switch(c.kind){case`skip`:return Z(e,n,r,i,a);case`recorded-unverifiable`:return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};case`deferred-landmark`:return Ll(e,t,n,r,i,a,{kind:`landmark`,landmark:c.landmark})}}let c=Al({recorded:o,token:s.token});if(c.kind===`skip`)return Z(e,n,r,i,a);if(c.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};let l=c.token,u=await e.observeTarget({action:n,index:i,token:l});if(u.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,Il(u),a,t)};let{classification:d}=u;return d.verified?Ll(e,t,n,r,i,a,{kind:`target`,guard:d.guard}):{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,{kind:d.kind,matchCount:d.matchCount,observed:d.observed,candidateNodes:d.candidateNodes,mismatches:d.mismatches,causeCode:d.causeCode,causeMessage:d.causeMessage},a,t)}}async function Fl(e,t,n,r,i,a){let o=n.targetEvidences,s={};for(let c of[`source`,`destination`]){let l={...n,targetEvidence:o[c]},u=e.beginTargetVerification(l,r,i,c);if(u.kind!==`pre-dispatch`)return Z(e,n,r,i,a);let d=Al({recorded:o[c],token:u.token});if(d.kind===`skip`)return Z(e,n,r,i,a);if(d.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(l,i,a,t)};let f=await e.observeTarget({action:l,index:i,token:d.token});if(f.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,Il(f),a,t)};let{classification:p}=f;if(!p.verified)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,{kind:p.kind,matchCount:p.matchCount,observed:p.observed,candidateNodes:p.candidateNodes,mismatches:p.mismatches,causeCode:p.causeCode,causeMessage:p.causeMessage},a,t)};s[c]=p.guard}return Ll(e,t,n,r,i,a,{kind:`targets`,guards:{source:s.source,destination:s.destination}})}function Il(e){return{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${e.reason}).`,...e.hint===void 0?{}:{causeHint:e.hint}}}async function Z(e,t,n,r,i){let a=await e.dispatchStep(t,n,r,i,void 0);switch(a.status){case`ok`:return{status:`ok`,artifactPaths:a.artifactPaths};case`failed`:return{status:`failed`,failure:a.failure};case`guard-mismatch`:case`landmark-mismatch`:return{status:`failed`,failure:a.plainFailure}}}async function Ll(e,t,n,r,i,a,o){let s=await e.dispatchStep(n,r,i,a,o);if(s.status===`ok`)return{status:`ok`,artifactPaths:s.artifactPaths};if(s.status===`failed`)return{status:`failed`,failure:s.failure};let c=Rl(n,o,s);if(!c)return{status:`failed`,failure:s.plainFailure};let l=zl(c.recorded,c.matchCount,s);return{status:`failed`,failure:await e.buildPostDispatchTargetBindingFailure(c.reportAction,i,{kind:`identity-mismatch`,matchCount:l.matchCount,observed:l.observed,candidateNodes:[],mismatches:l.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:l.causeMessage},a,t)}}function Rl(e,t,n){if(n.status!==`guard-mismatch`||t.kind!==`targets`)return e.targetEvidence?{recorded:e.targetEvidence,reportAction:e,matchCount:t.kind===`target`?t.guard.matchCount:0}:void 0;let r=n.evidence.targetRole??`source`,i=e.targetEvidences?.[r];return i?{recorded:i,reportAction:{...e,targetEvidence:i},matchCount:t.guards[r].matchCount}:void 0}function zl(e,t,n){return n.status===`guard-mismatch`?Ml(e,n.evidence,t):Nl(e,n.evidence)}async function Bl(e,t){let{actions:n,entryIndex:r,keepSession:i}=e,a=Pt(e.varSources),o=[],s=[],c=Wl(n),l=0;for(let u=r;u<n.length;u+=1){let r=n[u];if(!Ul(r)||(t.armStep(),u===c&&(i||t.isRepairArmed())))continue;if(l+=1,t.onStep){let e=t.describeStepValue(r);t.onStep(Gl(u,n.length,r,e))}let d=Nt(r,a,Hl(e,u)),f=At(a),p=t.diagnosticsMarker(),m=await Pl(t,f,r,d,u,o);if(s.push(...t.diagnosticsSince(p)),m.status===`ok`){o=m.artifactPaths;continue}let h=await t.handleActionFailure({action:r,index:u,artifactPaths:Vl(o,m.failure.artifactPaths),snapshotDiagnosticSamples:s,scrubVars:f});return{status:`failed`,stepIndex:u,failure:h}}return{status:`completed`,replayed:l,artifactPaths:[...o],snapshotDiagnosticSamples:s}}function Vl(e,t){return t.length===0?e:[...new Set([...e,...t])]}function Hl(e,t){return{file:e.actionSourcePaths?.[t]??e.resolvedPath,line:e.actionLines[t]??1}}function Ul(e){return!!(e&&e.command!==`replay`)}function Wl(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(Ul(n))return n.command===`close`?t:void 0}}function Gl(e,t,n,r){return{index:e+1,total:t,command:n.command,...r===void 0?{}:{value:r}}}async function Kl(e){return await ql({...e,snapshotDiagnostics:w(e.snapshotDiagnosticSamples)})}async function ql(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scrubVars:l,req:u,sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,planActions:h,planDigest:g}=e;if(t.ok)return t;let _=Jl(t.error.details?.replaySource),v=_i(t.error),y=await vi({error:v,action:n,index:r,sourcePath:_?.path??a,sourceLine:_?.line??o,session:f.get(),sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,responseLevel:u.meta?.responseLevel,scrubVars:l,planActions:h,planDigest:g,signal:Wr(u.meta?.requestId)});return Di({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:l})}function Jl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(n!==void 0||r!==void 0)return{path:n,line:r}}async function Yl(e){let{req:t,sessionName:n,action:r,resolved:a,filePath:o,line:s,step:l,sourcePath:u,tracePath:d,invoke:f,resolvedSessionScope:p,dependencies:m}=e,h=Date.now();wi(d,{type:`replay_action_start`,ts:new Date(h).toISOString(),replayPath:o,...u?{sourcePath:u}:{},line:s,step:l,command:a.command,positionals:Wn(a)??[]});let g;try{g=await Zl({req:t,sessionName:n,resolved:a,sourceAction:r,invoke:f,resolvedSessionScope:p,dependencies:m})}catch(e){if(!(e instanceof i))throw e;g={ok:!1,error:c(e)}}let _=Date.now();return wi(d,{type:`replay_action_stop`,ts:new Date(_).toISOString(),replayPath:o,...u?{sourcePath:u}:{},line:s,step:l,command:a.command,ok:g.ok,durationMs:_-h,resultTiming:g.ok?$l(g.data):void 0,errorCode:g.ok?void 0:g.error.code}),Xl(g,u??o,s)}function Xl(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function Zl(e){let{req:t,sessionName:n,resolved:r,sourceAction:a,invoke:o,resolvedSessionScope:s,dependencies:c}=e,l=E(r.command,r.positionals??[],r.flags??{},`after variable substitution`);if(l)throw new i(`INVALID_ARGS`,l);let u=S(t.flags,{...r.flags??{}}),d=a.command===`fill`?It(Vt(a)):void 0;return d&&(u.recordAs=d),await o(Ql({token:t.token,session:n,flags:u,runtime:r.runtime,meta:t.meta,dispatch:{...t.dispatch,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:s??c.resolveSessionScope(t)}:{}}},r))}function Ql(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:fe(n,{pointerCount:e.flags?.pointerCount,holdMs:e.flags?.holdMs,count:e.flags?.count,pauseMs:e.flags?.pauseMs})}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:se(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function $l(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function eu(e){return su(e.ok?nu(e.data):tu(e.error.details?.artifactPaths))}function tu(e){return Array.isArray(e)?e.filter(ou):[]}function nu(e){return e?[au(e.path),au(e.outPath),...ru(e.artifacts)].filter(ou):[]}function ru(e){return Array.isArray(e)?e.map(iu).filter(ou):[]}function iu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return au(t.localPath)??au(t.path)}function au(e){return typeof e==`string`?e:void 0}function ou(e){return typeof e==`string`}function su(e){return[...new Set(e.filter(cu))]}function cu(e){try{return K.statSync(e).isFile()}catch{return!1}}function lu(e){let{recorded:t,token:r,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}=e,l=uu({token:r,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}),u=Jt(i),d=Ne(t),f=Yt(l.matchedNodes,u,d,t.ancestry),p=f.filter(e=>Tt(i,e)===t.sibling),m=f.filter(e=>wt(e,u,t.scrollRegion)),h=Ct(m)[t.viewportOrder]?.ref,g=Et({winnerRef:l.winnerRef,matchedRefs:n(l.matchedNodes),identitySetRefs:n(f),siblingMatchRefs:n(p),regionMemberRefs:n(m),viewportCandidateRef:h}),_=l.matchedNodes.find(e=>e.ref===l.winnerRef);return g.outcome===`verified`&&_?{verified:!0,winnerNode:_,matchCount:l.matchedNodes.length}:g.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:l.matchedNodes.length,observedNode:void 0,candidateNodes:f.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,...pu({classification:g,matchCount:l.matchedNodes.length,winnerNode:_,identitySet:f,byIndex:u,recorded:t})}}function uu(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?du(n,t,i,a):fu(n,t,r,a,o)}function du(e,t,n,r){let i=e=>e!==null&&(!r||!!e.rect),o=u(t),s=o?a(e,o):null;if(i(s)&&s.ref!==void 0)return{matchedNodes:[s],winnerRef:s.ref};let c=n?ei(e,n):null;return i(c)&&h(c)?{matchedNodes:[c],winnerRef:c.ref}:{matchedNodes:[],winnerRef:``}}function fu(e,t,n,r,i){let a=dt(t,e,{platform:n,requireRect:r,allowDisambiguation:i});if(a.kind===`resolved`&&a.winner.ref!==void 0)return{matchedNodes:[...a.matchedNodes],winnerRef:a.winner.ref};let o=Br(e,a.matchedNodes);return{matchedNodes:[...a.matchedNodes],winnerRef:o?.ref??``}}function pu(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?mu(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?mu(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?mu(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function mu(e,t,n){let r=Dt(t),i=Xt(t,n,Math.max(e.ancestry.length,1)).chain;return[...qe(e,r),...je(e.ancestry,i)].slice(0,5)}function hu(e,t){let n=e.positionals??[];if(e.command===`gesture`){let e=ce(n);return e?e[t??`source`]:void 0}if(e.command===`get`)return n[1];if(e.command===`is`){let e=we(`is`,n);return e.kind===`expression`?e.expression:void 0}if(!oe(e.command)&&e.command!==`fill`)return;let r=n[0];if(r!==void 0&&!(_u(r)&&_u(n[1])))return r}function gu(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function _u(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function vu(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionStore:l,resumeStamper:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=Dn(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:Ou(Ne(n),h),...t.observed?{observed:Ou(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>ku(e,h))},_=Ci({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=xi({failedIndex:i,actions:p,planDigest:m,repairHint:_,resumeStamper:u}),y={version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(ne(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},b=Ei({sessionStore:l,observationStore:e.observationStore,divergence:y,responseLevel:d,evidence:t.publicationEvidence,...e.signal?{signal:e.signal}:{}}),x={code:t.causeCode,message:t.causeMessage};return Di({error:x,action:r,step:i,replayPath:s,artifactPaths:c,divergence:b,scrubVars:f})}function yu(e,t,n){let r=Dn(e.scrubVars);return vu(e,{kind:t.kind,matchCount:t.matchCount,observed:t.observed,candidateNodes:t.candidateNodes,mismatches:t.mismatches,causeCode:t.causeCode,causeMessage:t.causeMessage,...t.causeHint===void 0?{}:{causeHint:t.causeHint},screen:Ti(n,r),publicationEvidence:Cu(n),repairCapture:yi(n)})}async function bu(e){let{session:t,observationStore:n,logPath:r,action:i,unavailableHint:a}=e;return t?await Si({session:t,observationStore:n,logPath:r,action:i}):{state:`unavailable`,reason:`no-session`,hint:a}}async function xu(e,t){return yu(e,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`},await bu({...t,unavailableHint:`The session closed before a screen could be captured to verify the recorded target evidence.`}))}async function Su(e,t,n){return yu(e,t,await bu({...n,unavailableHint:`The session closed before a post-failure screen could be captured.`}))}function Cu(e){return e.state===`available`?e.evidence:void 0}function wu(e){let{action:t,resolvedAction:n,sessionStore:r,targetRole:i}=e,a=r.get();return a?Ve(t.command)===`post-resolution`?{kind:`post-resolution`,isSelectorWait:Qe(n.positionals??[])?.kind===`selector`}:{kind:`pre-dispatch`,token:hu(n,i),platform:a.device.platform}:{kind:`inactive`}}function Tu(e){let{recorded:t,token:n,action:r,nodes:i,platform:a}=e,o=ki(r),s=lu({recorded:t,token:n,nodes:i,platform:a,refLabel:gu(r),requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});return s.verified?{verified:!0,guard:{expected:{identity:Dt(s.winnerNode),structural:ct(s.winnerNode,i)},matchCount:s.matchCount}}:{verified:!1,kind:s.kind,matchCount:s.matchCount,observed:s.observedNode?Dt(s.observedNode):void 0,candidateNodes:s.candidateNodes,mismatches:s.mismatches,causeCode:s.causeCode,causeMessage:s.causeMessage}}function Eu(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}function Du(e){return!e.ok&&e.error.details?.reason===Ai}function Ou(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function ku(e,n){let r=t(e.type??`Element`),i=de(e,r);return{...e.ref?{ref:e.ref}:{},role:n(r),...i?{label:n(i)}:{}}}function Au(e,t){let n=t?.kind===`target`?{replayTargetGuard:t.guard.expected}:t?.kind===`targets`?{replayTargetGuards:{source:t.guards.source.expected,destination:t.guards.destination.expected}}:t?.kind===`landmark`?{replayLandmarkGuard:t.landmark}:void 0;return n?{...e,dispatch:{...e.dispatch,...n}}:e}function ju(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function Mu(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function Nu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.documentOrder==`number`&&typeof t.sibling==`number`)return{documentOrder:t.documentOrder,sibling:t.sibling}}function Pu(e){return{...e?.targetRole===`source`||e?.targetRole===`destination`?{targetRole:e.targetRole}:{},observed:ju(e?.observed),expectedStructural:Nu(e?.expectedStructural),observedStructural:Nu(e?.observedStructural)}}function Fu(e){return{matchCount:typeof e?.matchCount==`number`?e.matchCount:void 0,observed:ju(e?.observed),observedAncestry:Mu(e?.observedAncestry)}}function Iu(e,t){return{kind:e.error.code,message:e.error.message,artifactPaths:t}}function Lu(e,t,n){let r=Iu(e,n);return(t?.kind===`target`||t?.kind===`targets`)&&Eu(e)?{status:`guard-mismatch`,evidence:Pu(e.error.details),plainFailure:r,artifactPaths:n}:t?.kind===`landmark`&&Du(e)?{status:`landmark-mismatch`,evidence:Fu(e.error.details),plainFailure:r,artifactPaths:n}:{status:`failed`,failure:r}}function Ru(e){let{ctx:t,req:n,artifactPaths:r,onStep:i,armSaveScript:a}=e,o,s,c=(e,n,r,i)=>({recorded:e.targetEvidence,action:e,step:n+1,sourcePath:t.actionSourcePaths?.[n]??t.resolved,sourceLine:t.actionLines[n]??1,replayPath:t.resolved,artifactPaths:[...r],sessionStore:t.sessionStore,observationStore:t.observationStore,resumeStamper:t.coordinator.resumeStamper,responseLevel:t.responseLevel,scrubVars:i,planActions:t.actions,planDigest:t.planDigest,signal:t.signal}),l=e=>(o=e,Iu(zu(e),eu(e))),u=async e=>{let n=t.observationStore.get();return n?await Si({session:n,observationStore:t.observationStore,logPath:t.logPath,action:e,retryLaunchRace:!0}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a screen could be captured to verify the recorded target.`}};return{runtime:{beginTargetVerification(e,n,r,i){return wu({action:e,resolvedAction:n,sessionStore:t.sessionStore,targetRole:i})},async observeTarget({action:e,token:n}){let r=await u(e);if(s=r,r.state!==`available`)return{state:`unavailable`,reason:r.reason,hint:r.hint};let i=t.sessionStore.get();return{state:`classified`,classification:Tu({recorded:e.targetEvidence,token:n,action:e,nodes:[...r.nodes],platform:i.device.platform})}},async dispatchStep(e,n,i,a,s){let c=t.actionLines[i]??1,l=await Yl({req:Au(t.replayReq,s),sessionName:t.sessionName,action:e,resolved:n,filePath:t.resolved,line:c,sourcePath:t.actionSourcePaths?.[i],step:i+1,tracePath:t.actionTracePath,invoke:t.invoke,resolvedSessionScope:t.resolvedSessionScope,dependencies:t.dependencies});o=l,eu(l).forEach(e=>r.add(e));let u=[...r];return l.ok?{status:`ok`,artifactPaths:u}:Lu(l,s,u)},async buildRecordedUnverifiableFailure(e,n,r,i){let a=await xu(c(e,n,r,i),{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(a)},async buildTargetBindingFailure(e,t,n,r,i){let a=s??{state:`unavailable`,reason:`observation-missing`,hint:`No capture was recorded before this target-binding failure.`},o=yu(c(e,t,r,i),n,a);return l(o)},async buildPostDispatchTargetBindingFailure(e,n,r,i,a){let o=await Su(c(e,n,i,a),r,{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(o)},async handleActionFailure({action:e,index:r,artifactPaths:i,snapshotDiagnosticSamples:a,scrubVars:s}){let c=zu(o),u=await Bu(t,n,e,r,c,[...i],[...a],s);return l(u)},armStep:()=>{s=void 0,a()},isRepairArmed:()=>t.coordinator.view()?.repairBoundary!==void 0,describeStepValue:e=>Vu(e),onStep:i,diagnosticsMarker:()=>Uu(t.sessionStore),diagnosticsSince:e=>Wu(t.sessionStore,e)},readLastResponse:()=>o}}function zu(e){return e&&!e.ok?e:m(`COMMAND_FAILED`,`replay step reported failure with no recorded response`)}async function Bu(e,t,n,r,i,a,o,s){let c=t=>e.coordinator.markSessionHeldIfArmed(t);return Hu(i)?c(i):c(await Kl({response:i,action:n,index:r,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[r]??e.resolved,sourceLine:e.actionLines[r]??1,artifactPaths:a,snapshotDiagnosticSamples:o,scrubVars:s,req:t,sessionStore:e.sessionStore,observationStore:e.observationStore,resumeStamper:e.coordinator.resumeStamper,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function Vu(e){let t=e.positionals??[],n=Be(t[0]);if(n)return n;if(t.length!==0)return t.join(` `)}function Hu(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function Uu(e){return e.get()?.snapshotDiagnostics?.samples.length??0}function Wu(e,t){return e.get()?.snapshotDiagnostics?.samples.slice(t)??[]}async function Gu(e){let{resolved:t,keepSession:n,coordinator:r,command:i}=e,{request:a}=i,o=k(t,a.flags?.replayBackend);if(o!==`ad`)return n?m(`INVALID_ARGS`,`--keep-session is supported only for native .ad replay; Maestro YAML owns its lifecycle.`):r.view()?.repairBoundary===void 0?await(await ji(o)).runReplay(i):m(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function Ku(e){let{req:t,host:n,sessionName:r,sessionStore:i,tracePath:a,resolved:o,script:s,coordinator:c,dispatch:l}=e,u=qu(t);if(u)return{ok:!1,response:u};let{manifest:d,replayReq:f}=Ju(t,s,l),{metadata:p,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_}=d,v=i.get(),y=Yu({req:t,coordinator:c,manifest:d,preEntrySession:v});return y.ok?{ok:!0,value:{replayReq:f,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,preEntrySession:v,entryIndex:y.value,varSources:Zu({req:t,host:n,replayReq:f,sessionName:r,resolved:o,metadata:p}),actionTracePath:a??v?.trace?.outPath}}:{ok:!1,response:y.response}}function qu(e){let t=e.flags?.replayBackend;if(t&&!te(t))return m(`INVALID_ARGS`,ie(t))}function Ju(e,t,n){let r=Ol(t,{platform:e.flags?.platform,target:e.flags?.target});return{manifest:r,replayReq:Xu({...e,flags:Kn(e.flags,r.actions),...n?{dispatch:n}:{}},r.metadata)}}function Yu(e){let{req:t,coordinator:n,manifest:r,preEntrySession:i}=e,a=r.resolveEntryIndex({from:t.flags?.replayFrom,digest:t.flags?.replayPlanDigest,pendingRecordAndHeal:n.view()?.pendingRecordAndHeal,sessionActionsLength:i?.actions.length??0});return a.ok?{ok:!0,value:a.value}:{ok:!1,response:m(`INVALID_ARGS`,a.message)}}function Xu(e,t){return!t.platform&&!t.target?e:{...e,flags:Qu(e.flags,t)}}function Zu(e){let{req:t,host:n,replayReq:r,sessionName:i,resolved:a,metadata:o}=e;return{builtins:Oi({req:r,sessionName:i,metadata:o,resolvedPath:a,hostCwd:n.cwd}),fileEnv:o.env,shellEnv:Mt(jt(t.flags?.replayShellEnv,n.env)),cliEnv:kt(Ot(t.flags?.replayEnv))}}function Qu(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}const $u={kind:`none`,status:void 0,targetPath:void 0,targetForce:!1};function ed(e){let{req:t,entryIndex:n,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}=e,s=td({entryIndex:n,sessionStore:i,coordinator:o});return s?{ok:!1,response:s}:(id({req:t,coordinator:o}),rd({req:t,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}))}function td(e){let t=ad(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get())return p()}function nd(e){let{saveScript:t,force:n,hostCwd:r,preRunState:i,sourcePath:a}=e;return t&&i.kind===`authoring`?m(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${i.status}. Close this session and use a fresh one for repair authoring.`):od({saveScript:t,liveForce:n,persistedForce:i.targetForce||void 0,hostCwd:r,sourcePath:a,existingSaveScriptPath:i.targetPath})}function rd(e){let{req:t,hostCwd:n,sourcePath:r,coordinator:i}=e,{saveScript:a,force:o}=t.flags??{},s=nd({saveScript:a,force:o,hostCwd:n,preRunState:i.view()?.scriptPublication??$u,sourcePath:r});return s?{ok:!1,response:s}:(i.demoteForRerunIfArmed(),{ok:!0,armSaveScript:sd({saveScript:a,force:o,coordinator:i,sourcePath:r})})}function id(e){let{req:t,coordinator:n}=e;n.clearCorrectiveWatermarkIfExpected(t.flags?.replayFrom),t.flags?.saveScript&&n.clearTombstone()}function ad(e){let{entryIndex:t,coordinator:n}=e;if(!(t>0)&&n.view()?.repairBoundary!==void 0)return m(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function od(e){let{saveScript:t,liveForce:n,persistedForce:r,hostCwd:i,sourcePath:a,existingSaveScriptPath:o}=e;if(!t)return;let s=typeof t==`string`?z(t,i):o??bi(a);if(!(n||r&&s===o)&&K.existsSync(s))return m(`COMMAND_FAILED`,`A file already exists at ${s}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function sd(e){let{saveScript:t,force:n,coordinator:r,sourcePath:i}=e;if(!t)return()=>{};let a=!0;return()=>{r.armStep({saveScript:t,force:n,sourcePath:i,firstArm:a}),a=!1}}async function cd(e){let{request:t,host:n,session:{name:r,logPath:i,store:a,observationStore:o,coordinator:s},tracePath:l,onStep:u,invoke:d}=e,f=t.flags?.replayScriptSource;if(!f)return m(`INVALID_ARGS`,Vn);let p=Date.now(),h=t.flags?.replayKeepSession===!0,g=``,_=new Set;try{if(g=f.entry,ue(g)&&t.flags?.replayBackend!==`maestro`)return m(`INVALID_ARGS`,le(`replay`,g));let c=await Gu({resolved:g,keepSession:h,coordinator:s,command:e});if(c)return c;let v=Ku({req:t,host:n,sessionName:r,sessionStore:a,tracePath:l,resolved:g,script:Gn(f,g),coordinator:s,dispatch:e.dispatch});if(!v.ok)return v.response;let{replayReq:y,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,entryIndex:w,varSources:ee,actionTracePath:T}=v.value,E=ed({req:t,entryIndex:w,hostCwd:n.cwd,sessionStore:a,sourcePath:g,coordinator:s});if(!E.ok)return E.response;let{runtime:te,readLastResponse:D}=Ru({ctx:{replayReq:y,sessionName:r,sessionStore:a,observationStore:o,logPath:i,resolved:g,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,actionTracePath:T,responseLevel:t.meta?.responseLevel,invoke:d,signal:Wr(t.meta?.requestId),coordinator:s,resolvedSessionScope:e.resolvedSessionScope,dependencies:e.dependencies},req:t,artifactPaths:_,onStep:u,armSaveScript:E.armSaveScript}),O=await Bl({actions:b,entryIndex:w,keepSession:h,actionLines:x,actionSourcePaths:S,resolvedPath:g,varSources:ee},te);return O.status===`failed`?D()??m(`COMMAND_FAILED`,`replay step failed with no recorded response`):ld({startedAt:p,sessionName:r,sessionStore:a,replayed:O.replayed,artifactPaths:O.artifactPaths,snapshotDiagnosticSamples:O.snapshotDiagnosticSamples,armSaveScript:E.armSaveScript,coordinator:s,keepSession:h})}catch(e){let t=c(e);return _.size===0?{ok:!1,error:t}:{ok:!1,error:{...t,details:{...t.details,artifactPaths:[..._]}}}}}function ld(e){let{startedAt:t,sessionName:n,sessionStore:r,replayed:i,artifactPaths:a,snapshotDiagnosticSamples:o,armSaveScript:s,coordinator:c,keepSession:l}=e;s(),c.markCompleteIfArmed();let u=r.get(),d=dd({keepSession:l,sessionName:n,completedSession:u,artifactPaths:a});if(d)return d;let f=w([...o]);return{ok:!0,data:{replayed:i,healed:0,session:n,sessionActive:u!==void 0,artifactPaths:[...a],...f?{snapshotDiagnostics:f}:{},message:ud(i,Date.now()-t)}}}function ud(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function dd(e){let{keepSession:t,sessionName:n,completedSession:r,artifactPaths:i}=e;if(!(!t||r))return m(`COMMAND_FAILED`,`Replay completed but --keep-session could not preserve session "${n}". Run the script again after checking which action closed the session.`,i.length>0?{artifactPaths:[...i]}:void 0)}function fd(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=q.resolve(n??`.`,t??`.agent-device/test-artifacts`);return q.join(i,r)}function pd(e,t){let n=t?q.relative(t,e):q.basename(e),r=n.length===0||n.startsWith(`..`)?q.basename(e):n;return it(r.toLowerCase().replaceAll(/[\\/]+/g,`__`).replaceAll(/[^a-z0-9._-]+/g,`-`))||`test`}function md(e,t){K.mkdirSync(t,{recursive:!0}),_d(e,t)}function hd(e){let{outcome:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=t.status===`passed`,c=new Set(t.artifactPaths);t.status===`failed`&&typeof t.error.logPath==`string`&&c.add(t.error.logPath);let l=q.join(o,`result.txt`),u=q.join(o,`failure.txt`),d=gd([...c],o,[l,u]),f=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${s?`passed`:`failed`}`];t.status===`passed`?f.push(`replayed: ${t.replayed}`,`healed: ${t.healed}`):(f.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&f.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&f.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&f.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&f.push(`timeoutMode: cooperative`)),d.length>0&&f.push(`copiedArtifacts: ${d.map(e=>q.basename(e)).join(`, `)}`);let p=`${f.join(`
2
- `)}\n`;K.writeFileSync(l,p),s||K.writeFileSync(u,p)}function gd(e,t,n){let r=[],i=new Set(n.map(e=>q.basename(e).toLowerCase()));for(let n of e){if(!yd(n))continue;let e=q.basename(n);if(q.resolve(n)===q.resolve(t,e)&&!i.has(e.toLowerCase())){r.push(n);continue}let a=vd(e,t,i),o=q.join(t,a);K.copyFileSync(n,o),r.push(o)}return r}function _d(e,t){let n=q.join(t,`replay.ad`);if(K.copyFileSync(e,n),q.extname(e).toLowerCase()===`.ad`)return;let r=q.join(t,q.basename(e));q.resolve(r)!==q.resolve(n)&&K.copyFileSync(e,r)}function vd(e,t,n){let r=q.extname(e),i=r?e.slice(0,-r.length):e,a=e,o=2;for(;n.has(a.toLowerCase())||K.existsSync(q.join(t,a));)a=`${i}-${o++}${r}`;return a}function yd(e){try{return K.statSync(e).isFile()}catch{return!1}}function bd(e){let{platformFilter:t,discoverSources:n}=e,r=n(),a=[],o={undeclared:0,declaredOther:0};for(let e of r){let{path:n,manifest:r}=e,i={kind:`run`,path:n,title:r.title,manifest:r};if(!t){a.push(i);continue}let s=r.device.platform;if(s.kind===`caller-bound`){a.push(i);continue}if(s.kind===`unspecified`){o.undeclared+=1,a.push({kind:`skip`,path:n,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${t}`});continue}if(!Ad(t,s.value)){o.declaredOther+=1;continue}a.push(i)}if(a.filter(e=>e.kind===`run`).length===0)throw new i(`INVALID_ARGS`,Cd({platformFilter:t,...o}));return a}const xd={web:!0};function Sd(e){return!Object.hasOwn(xd,e)}function Cd(e){let{platformFilter:t,undeclared:n,declaredOther:r}=e,i=t?` for --platform ${t}`:``;return t===void 0||n===0&&r===0?`No replay tests matched${i}.`:`No replay tests matched${i}: ${[...n>0?[`${n} without a platform declaration`]:[],...r>0?[`${r} declaring another platform`]:[]].join(`, `)}. ${wd(t,n)}`}function wd(e,t){return Sd(e)?t>0?`Add "context platform=${e}" to the first line of a script that has none, or drop --platform when the device is already selected.`:`Run a source that declares ${e}, or drop --platform.`:`No script can declare ${e} as its platform; run this suite without --platform.`}function Td(e,t,n,r,i=0){let a=q.basename(n,q.extname(n)),o=it(a.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`));return`${e}:test:${t}:${r+1}${o?`-${o}`:``}:attempt-${i+1}`}function Ed(e){let t=e?.trim()||`${process.pid}-${Date.now().toString(36)}`;return it(t.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`))||`suite`}function Dd(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e;return[t??n,...o===void 0?[]:[`shard`,o+1],`test`,i+1,q.basename(r),`attempt`,a+1].join(`:`)}function Od(e,t){return typeof e==`number`?e:t}function kd(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function Ad(e,t){return e===`apple`?P(t):t===e}function jd(e){return{status:`failed`,error:e.error,artifactPaths:e.artifactPaths??[],warnings:e.warnings??[],infrastructure:e.infrastructure??!1,...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}const Md=2e3;async function Nd(e){let{filePath:t,sessionName:n,requestId:r,parentRequestId:i,timeoutMs:a,platform:o,target:s,artifactsDir:l,shard:u,onStep:d,runReplay:f,cleanupSession:p,finalizeAttempt:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=g({attemptId:r,parentAttemptId:i}),v=new Set,y,b=!1,x,S=Date.now(),C=Bd({artifactsDir:l,artifactPaths:v,filePath:t,sessionName:n,requestId:r,timeoutMs:a,platform:o,target:s}),w=f({filePath:t,sessionName:n,platform:o,target:s,requestId:r,artifactsDir:l,artifactPaths:v,tracePath:C,appendTimingEvent:e=>Q(C,e),shard:u,onStep:d}).catch(e=>jd({error:c(e)})).finally(()=>{_.release()});try{x=typeof a==`number`?await Promise.race([w,new Promise(e=>{y=setTimeout(()=>{b=!0,_.cancel(),e(Vd(a,[...v]))},a)})]):await w,Q(C,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:n,ok:x.status===`passed`,timedOut:b,durationMs:Date.now()-S,errorCode:x.status===`passed`?void 0:x.error.code})}finally{y&&clearTimeout(y),b&&(await Fd(w)||(x=Rd(x),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:n,requestId:r,graceMs:Md}}),Id({replayPromise:w,cleanupSession:p,sessionName:n,requestId:r,emitDiagnostic:h})));let e=await Ld({finalizeAttempt:m,sessionName:n,artifactPaths:v,artifactsDir:l,tracePath:C,emitDiagnostic:h});x?.status===`passed`&&e&&(x=zd(x,`Replay test finalization failed: ${e.error.message}`));let t=Date.now();try{Q(C,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:n}),await p(n),Q(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!0,durationMs:Date.now()-t})}catch(e){let r=c(e);Q(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-t,errorCode:r.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:n,error:r.message}}),x=Pd(x,r,v)}}return x??jd({error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}})}function Pd(e,t,n){return e?.status===`failed`?{...e,infrastructure:!0}:jd({error:t,artifactPaths:[...n],infrastructure:!0})}async function Fd(e){return await Promise.race([e.then(()=>!0),Ri(Md).then(()=>!1)])}async function Id(e){let{replayPromise:t,cleanupSession:n,sessionName:r,requestId:i,emitDiagnostic:a}=e;try{await t}finally{try{await n(r)}catch(e){a({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:r,requestId:i,error:c(e).message}})}}}async function Ld(e){let{finalizeAttempt:t,sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,emitDiagnostic:o}=e;if(!t)return;let s=Date.now();Q(a,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:n});try{let e=await t({sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,appendTimingEvent:e=>Q(a,e)});return Q(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:e===void 0,durationMs:Date.now()-s,errorCode:e?.error.code}),e}catch(e){let t=c(e);return Q(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-s,errorCode:t.code}),o({level:`warn`,phase:`test_finalize_failed`,data:{session:n,error:t.message}}),jd({error:t})}}function Rd(e){return!e||e.status===`passed`?e:{...e,infrastructure:!0,error:{...e.error,details:{...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0}}}}function zd(e,t){return{...e,warnings:[...e.warnings,t]}}function Bd(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=q.join(t,`replay-timing.ndjson`);return K.mkdirSync(q.dirname(l),{recursive:!0}),K.writeFileSync(l,``),n.add(l),Q(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function Q(e,t){e&&K.appendFileSync(e,`${JSON.stringify(t)}\n`)}function Vd(e,t=[]){return jd({artifactPaths:t,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}})}async function Hd(e){let t=Ud(e),n=await Wd(e,t);return{result:Xd(e,t,n),infrastructure:n.finalOutcome?.status===`failed`&&n.finalOutcome.infrastructure}}function Ud(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:q.join(i,...a?[`shard-${a.shardIndex+1}`]:[],pd(t.path,n)),maxAttempts:r+1}}async function Wd(e,t){Kd(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!e.isCanceled();r+=1){let i=await Gd(e,t,r);if(qd(n,i),Jd(e,i.outcome,r))break;Yd(e,t,i)}return n}async function Gd(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=Td(i,a,r.path,o,n),h=q.join(t.testArtifactsDir,`attempt-${f}`);md(r.path,h);let g=Dd({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_={file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...tf(d)},v=await Nd({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.manifest.device.platform.kind===`declared`?r.manifest.device.platform.value:void 0,target:r.manifest.device.target,artifactsDir:h,shard:d,onStep:t=>{e.emitProgress({type:`replay-test`,..._,status:`progress`,stepIndex:t.index,stepTotal:t.total,...t.command===void 0?{}:{stepCommand:t.command},...t.value===void 0?{}:{stepValue:t.value}})},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt,emitDiagnostic:e.emitDiagnostic,bindAttemptCancellation:e.bindAttemptCancellation}),y=Date.now()-p;return hd({outcome:v,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{outcome:v,sessionName:m,attempt:f,durationMs:y}}function Kd(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;e.emitProgress({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:Td(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...tf(c)})}function qd(e,t){e.finalOutcome=t.outcome,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,t.outcome.status!==`passed`&&e.attemptFailures.push({attempt:t.attempt,message:t.outcome.error.message,durationMs:t.durationMs})}function Jd(e,t,n){return t.status===`passed`||e.isCanceled()||t.infrastructure||n>=e.retries}function Yd(e,t,n){n.outcome.status!==`passed`&&e.emitProgress({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.outcome.error.message,hint:n.outcome.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...tf(e.shard)})}function Xd(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalOutcome?.status===`passed`?Zd(e,t,n,r):Qd(e,t,n,r)}function Zd(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome;if(c?.status!==`passed`)throw Error(`Expected passing replay test outcome.`);return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...tf(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,replayed:c.replayed,healed:c.healed,...c.warnings.length>0?{warnings:[...c.warnings]}:{},...c.snapshotDiagnostics?{snapshotDiagnostics:c.snapshotDiagnostics}:{},...ef(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function Qd(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome,l=c?.status===`failed`?c.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`};return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:l.message,hint:l.hint,...tf(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:l,...$d(c),...ef(s)}}function $d(e){let t=e?.status===`failed`?e:void 0;return{...t&&t.warnings.length>0?{warnings:[...t.warnings]}:{},...t?.infrastructure?{infrastructure:!0}:{},...e?.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}function ef(e){return tf(e)}function tf(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function nf(e,t,n,r){if(!e||t.length===0)return;let i=await r(e.count);return{mode:e.kind,shardCount:e.count,total:n+(e.kind===`all`?t.length*e.count:t.length),shards:i.map((n,r)=>({shardIndex:r,shardCount:e.count,device:n,entries:e.kind===`all`?t:t.filter((t,n)=>n%e.count===r)}))}}async function rf(t){let{request:n,runReplay:r,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l,discoverSources:u,resolveShardTargets:d}=t,f=n.sessionName;if(n.inputs.length===0)return{status:`failed`,error:{code:`INVALID_ARGS`,message:`test requires at least one path or glob`}};try{let e=Date.now(),t=await af(n,u,d);lf(t,o);let p=t.shardPlan?uf({entries:t.entries,total:t.total,emitProgress:o}):[];return t.shardPlan?p.push(...await df({shards:t.shardPlan.shards,sessionName:f,suiteInvocationId:t.suiteInvocationId,cwd:n.cwd,requestId:n.requestId,request:n,suiteArtifactsDir:t.suiteArtifactsDir,suiteTotal:t.total,runReplay:r,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l})):p.push(...await hf({discoveryEntries:t.entries,sessionName:f,suiteInvocationId:t.suiteInvocationId,cwd:n.cwd,requestId:n.requestId,request:n,suiteArtifactsDir:t.suiteArtifactsDir,suiteTotal:t.total,runReplay:r,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l})),{status:`completed`,data:vf(t.total,p,Date.now()-e,t.suiteArtifactsDir)}}catch(t){let n=e(t);return{status:`failed`,error:{code:n.code,message:n.message}}}}async function af(e,t,n){let r=of(e,t),i=sf(r),a=r.length-i.length,o=Ed(e.requestId),s=await nf(e.shard?{kind:e.shard.mode,count:e.shard.count}:void 0,i,a,n);return{entries:r,runnable:i,shardPlan:s,suiteInvocationId:o,suiteArtifactsDir:cf(e,o),total:s?.total??r.length}}function of(e,t){return bd({platformFilter:e.platformFilter,discoverSources:t})}function sf(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function cf(e,t){return fd({artifactsDir:typeof e.artifactsDir==`string`?e.artifactsDir:void 0,cwd:e.cwd,suiteInvocationId:t})}function lf(e,t){t({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function uf(e){let{entries:t,total:n}=e,r=[];for(let[i,a]of t.entries())a.kind===`skip`&&(e.emitProgress({type:`replay-test`,file:a.path,status:`skip`,index:i+1,total:n,message:a.message}),r.push({file:a.path,status:`skipped`,durationMs:0,reason:a.reason,message:a.message}));return r}async function df(e){return(await Promise.allSettled(e.shards.map(async t=>await pf({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[ff(r,e.sessionName,t.reason)]:[]})}function ff(e,t,n){let r=c(n);return{file:e.entries[0]?.entry.path??`shard-${e.shardIndex+1}`,session:mf(t,e),status:`failed`,durationMs:0,attempts:1,error:{code:r.code,message:r.message,hint:r.hint,diagnosticId:r.diagnosticId,logPath:r.logPath,details:r.details},shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}}async function pf(e){let{shard:t,sessionName:n}=e;return await gf({...e,entries:t.entries,sessionName:mf(n,t),shard:t})}function mf(e,t){return`${e}:shard-${t.shardIndex+1}`}async function hf(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h}=e,g=[],_=0;for(let[e,v]of t.entries()){if(p())break;if(v.kind===`skip`){f({type:`replay-test`,file:v.path,status:`skip`,index:e+1,total:c,message:v.message}),g.push({file:v.path,status:`skipped`,durationMs:0,reason:v.reason,message:v.message});continue}_+=1;let t=await Hd({entry:v,sessionName:n,suiteInvocationId:r,caseIndex:_-1,cwd:i,requestId:a,retries:kd(o.retries,v.manifest.attemptDefaults?.retries),timeoutMs:Od(o.timeoutMs,v.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h});if(g.push(t.result),_f(t,o,p))break}return g}async function gf(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=[];for(let[e,v]of t.entries()){if(m())break;let{entry:t,suiteIndex:y}=v,b=await Hd({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:kd(o.retries,t.manifest.attemptDefaults?.retries),timeoutMs:Od(o.timeoutMs,t.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:y,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g});if(_.push(b.result),_f(b,o,m))break}return _}function _f(e,t,n){return n()||t.failFast===!0&&e.result.status===`failed`||e.infrastructure}function vf(e,t,n,r){let i=t.filter(e=>e.status===`passed`).length,a=t.filter(e=>e.status===`failed`),o=a.length,s=t.filter(e=>e.status===`skipped`).length,c=i+o,l=T(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:c,passed:i,failed:o,skipped:s,notRun:Math.max(0,e-c-s),durationMs:n,failures:a,tests:t,artifactsDir:r,...l?{snapshotDiagnostics:l}:{}}}async function yf(e,t){let n=te(t)&&e.some(e=>k(e.entry,t)!==`ad`)?await ji(t):void 0;return()=>e.map(e=>bf(e,t,n))}function bf(e,t,n){let r=e.entry,i=Gn(e,r),a=k(r,t)!==`ad`,o=re(i);return{path:r,manifest:{...a?{title:n?.inspectSource(i,r).title}:{},device:{platform:o.platform?{kind:`declared`,value:o.platform}:a?{kind:`caller-bound`}:{kind:`unspecified`},...o.target===void 0?{}:{target:o.target}},...o.timeoutMs!==void 0||o.retries!==void 0?{attemptDefaults:{...o.timeoutMs===void 0?{}:{timeoutMs:o.timeoutMs},...o.retries===void 0?{}:{retries:o.retries}}}:{}}}}function xf(e,t){return async n=>(await wf(e,n,t)).map(Sf)}function Sf(e){if(e.platform===`web`||!xe(e))throw new i(`INVALID_ARGS`,`test sharding requires a mobile device; ${e.id} is ${e.platform}`);return{id:e.id,name:e.name,platform:e.platform,...e.target===void 0?{}:{target:e.target}}}function Cf(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}async function wf(e,t,n){let r=Of(e),a=Ef(await Rr(Tf(e,n)),r,e);if(a.length<t)throw new i(`DEVICE_NOT_FOUND`,`test sharding requires ${Df(t)}, but only ${a.length} matched`);return a.slice(0,t)}function Tf(e,t){let n=V(e?.androidDeviceAllowlist,t);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:ve({requestedSetPath:e?.iosSimulatorDeviceSet,platform:e?.platform,target:e?.target,env:t}),androidSerialAllowlist:n?Array.from(n).sort():void 0}}function Ef(e,t,n){return t.length>0?kf(e,t,n):e.filter(e=>Af(e,n)).sort(Nf)}function Df(e){return`${e} device${e===1?``:`s`}`}function Of(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function kf(e,t,n){return t.map(t=>{let r=Mf(t),a=e.find(e=>jf(e,n)&&(e.id===t||Mf(e.name)===r));if(!a)throw new i(`DEVICE_NOT_FOUND`,`No shard device matched ${t}`);return a})}function Af(e,t){return!jf(e,t)||!xe(e)?!1:e.booted!==!1}function jf(e,t){return!(!_e(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Mf(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function Nf(e,t){return e.id.localeCompare(t.id)}function Pf(e){let t=Ff(e?.shardAll,`--shard-all`),n=Ff(e?.shardSplit,`--shard-split`);if(t!==void 0&&n!==void 0)throw new i(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(t!==void 0)return{mode:`all`,count:t};if(n!==void 0)return{mode:`split`,count:n}}function Ff(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new i(`INVALID_ARGS`,`${t} requires a positive integer`);return e}}const If=new Set([`IOS_BOOT_TIMEOUT`,`IOS_RUNNER_CONNECT_TIMEOUT`,`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,`IOS_TOOL_MISSING`,`ANDROID_BOOT_TIMEOUT`,`ADB_TRANSPORT_UNAVAILABLE`,`CI_RESOURCE_STARVATION_SUSPECTED`]);function Lf(e){return If.has(e.toUpperCase())}const Rf=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function zf(e){if(!(`ok`in e)&&e.status===`failed`&&e.infrastructure===!0)return!0;let t=Bf(e);return t?Vf(t.details)||Hf(t.code,t.message):!1}function Bf(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Vf(e){if(e?.recovery===`runner_recycle_budget_exhausted`)return!0;let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`||_(t)?!0:t?Lf(t):!1}function Hf(e,t){let n=`${e}\n${t}`.toLowerCase();return Rf.some(e=>n.includes(e))}function Uf(e){if(!e.ok)return{status:`failed`,error:e.error,artifactPaths:Kf(e.error.details?.artifactPaths),warnings:vn(e.error.details),infrastructure:zf(e),...qf(e.error.details?.snapshotDiagnostics)};let t=e.data;return{status:`passed`,replayed:typeof t?.replayed==`number`?t.replayed:0,healed:typeof t?.healed==`number`?t.healed:0,warnings:vn(t),artifactPaths:Kf(t?.artifactPaths),...qf(t?.snapshotDiagnostics)}}function Wf(e){if(!e||e.ok)return;let t=Uf(e);return t.status===`failed`?t:void 0}function Gf(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Kf(e){return[...new Set(Gf(e))]}function qf(e){let t=ee(e);return t?{snapshotDiagnostics:t}:{}}const Jf=1e3,Yf=3e3;function Xf(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Zf(e)}}async function Zf(e){let{req:t,sessionName:n,sessionStore:r,artifactsDir:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0)return;let o=r.get();if(!o||o.screenRecording)return;let s=xn(o.device.platform),c=i?q.join(i,`recording${s}`):bn(o.device.platform);$f(a,{type:`video_recording_start`,session:n,videoPath:c}),j({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:c}}),e.video.throwIfCanceled();let l=await e.video.record(ep({req:t,sessionName:n,phase:`start`,outputPath:c}));if(!l.ok)return $f(a,{type:`video_recording_start_failed`,session:n,videoPath:c,errorCode:l.error.code}),l;let u=Date.now();return await pe(Jf),$f(a,{type:`video_preroll_done`,session:n,durationMs:Date.now()-u,requestedDurationMs:Jf}),j({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-u,data:{session:n,requestedDurationMs:Jf}}),l}async function Qf(e){let{req:t,sessionName:n,sessionStore:r,artifactPaths:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0||!r.get()?.screenRecording)return;$f(a,{type:`video_tail_start`,session:n,requestedDurationMs:Yf});let o=Date.now();await pe(Yf);let s=Date.now(),c=await e.video.record(ep({req:t,sessionName:n,phase:`stop`}));return eu(c).forEach(e=>i.add(e)),$f(a,{type:`video_recording_stop`,session:n,ok:c.ok,durationMs:Date.now()-s,tailDurationMs:s-o,errorCode:c.ok?void 0:c.error.code}),j({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-s,data:{session:n,ok:c.ok,tailDurationMs:s-o}}),c}function $f(e,t){e({...t,ts:new Date().toISOString()})}function ep(e){let t={token:e.req.token,meta:e.req.meta};return e.phase===`start`?{request:t,sessionName:e.sessionName,phase:`start`,outputPath:e.outputPath}:{request:t,sessionName:e.sessionName,phase:`stop`}}const tp=[{keys:[`replayKeepSession`],requested:e=>e.replayKeepSession===!0,message:`test does not support --keep-session; suite attempts own their cleanup. Run one native .ad script directly with replay --keep-session.`},{keys:[`replayFrom`,`replayPlanDigest`],requested:e=>e.replayFrom!==void 0||e.replayPlanDigest!==void 0,message:`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`},{keys:[`saveScript`,`force`],requested:e=>!!e.saveScript||e.force===!0,message:`test does not support --save-script/--force; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`}],np=({attemptId:e,parentAttemptId:t})=>{Ur(e);let n=rp(e,t);return{cancel:()=>Hr(e),release:()=>{n(),Vr(e)}}};function rp(e,t){if(!t||t===e)return()=>{};let n=Wr(t);if(!n)return()=>{};let r=()=>{Hr(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}function ip(e){let{platform:t,target:n,artifactsDir:r,shard:i,sourceBundle:a}=e,o=ap(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0&&a===void 0?o:Cf({...o??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r},...a===void 0?{}:{replayScriptSource:a}},i)}function ap(e){if(!e||e.recordVideo!==!0&&e.replayScriptSources===void 0)return e;let t={...e};return delete t.recordVideo,delete t.replayScriptSources,Object.keys(t).length>0?t:void 0}async function op(t){let{request:n,session:{name:r,logPath:i},createSession:a,invoke:o,cleanupSession:s,video:c}=t;if(n.flags?.recordVideo===!0&&c===void 0)return m(`COMMAND_FAILED`,`Screen-recording runtime is not configured for replay video capture`);let l=n.flags??{};for(let e of tp)if(e.requested(l))return m(`INVALID_ARGS`,e.message);let u,d;try{u=lp(n,r,t.host.cwd),d=cp(n)}catch(t){let n=e(t);return m(n.code,n.message)}let f=new Map(d.map(e=>[e.entry,e])),p=await rf({request:u,emitProgress:Kr,isCanceled:()=>Gr(n.meta?.requestId),emitDiagnostic:j,bindAttemptCancellation:np,runReplay:async({filePath:e,sessionName:r,platform:s,target:l,requestId:u,artifactsDir:d,artifactPaths:p,tracePath:m,appendTimingEvent:h,shard:g,onStep:_})=>{let v=e=>(p&&eu(e).forEach(e=>p.add(e)),e),y=ip({parentFlags:n.flags,platform:s,target:l,artifactsDir:d,shard:g,sourceBundle:f.get(e)}),b=a(r,i),x=c?{req:n,sessionName:r,sessionStore:b.store,artifactsDir:d,appendTimingEvent:h,video:c}:void 0,S=x?Xf(x):void 0;return Uf(await cd({...up(t,{request:{...n,command:`replay`,session:r,positionals:[e],flags:y,meta:{...n.meta??{},...u?{requestId:u}:{}}},openLifecycle:S}),session:b,tracePath:m,onStep:_,publicNetworkOnly:t.publicNetworkOnly,invoke:async e=>{let t=x?await Zf(x):void 0;return t&&!t.ok?t:v(await o(e))}}))},finalizeAttempt:async({sessionName:e,artifactPaths:t,artifactsDir:r,appendTimingEvent:o})=>{if(c)return Wf(await Qf({req:n,sessionName:e,sessionStore:a(e,i).store,artifactsDir:r,appendTimingEvent:o,artifactPaths:t,video:c}))},discoverSources:await yf(d,n.flags?.replayBackend),resolveShardTargets:xf(n.flags,t.host.env),cleanupSession:s});return p.status===`completed`?{ok:!0,data:sp(p.data,n)}:m(p.error.code,p.error.message)}function sp(e,t){let n=t.meta?.clientArtifactPaths?.artifactsDir,r=e.artifactsDir;if(!n||!r)return e;let i=q.join(n,q.basename(r)),a=e=>e===r||e.startsWith(r+q.sep)?i+e.slice(r.length):e,o={...e,artifactsDir:i,tests:e.tests.map(e=>`artifactsDir`in e&&e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e),failures:e.failures.map(e=>e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e)};return K.existsSync(r)?{...o,artifacts:[{field:`artifactsDir`,artifactType:`test-artifacts`,path:r,localPath:n,fileName:q.basename(r)}]}:o}function cp(e){let t=e.flags?.replayScriptSources;if(!t)throw new i(`INVALID_ARGS`,Vn);return t}function lp(e,t,n){let r=e.flags??{},i=e.meta?.cwd,a=fp(r.artifactsDir);return{inputs:e.positionals??[],sessionName:t,cwd:i,requestId:e.meta?.requestId,platformFilter:r.platform,artifactsDir:a===void 0?void 0:z(a,i??n),failFast:r.failFast===!0,retries:dp(r.retries),timeoutMs:dp(r.timeoutMs),shard:Pf(r)}}function up(e,t){let{host:n,publicNetworkOnly:r,resolvedSessionScope:i,dispatch:a,dependencies:o}=e,s=a||t.openLifecycle?{...a,...t.openLifecycle?{openLifecycle:t.openLifecycle}:{}}:void 0;return{request:t.request,host:n,...r?{publicNetworkOnly:r}:{},...i?{resolvedSessionScope:i}:{},...s?{dispatch:s}:{},dependencies:o}}function dp(e){return typeof e==`number`?e:void 0}function fp(e){return typeof e==`string`?e:void 0}function pp(e,t,n,r){return{name:e,logPath:t,store:{...n,assertSelectorMatches:r.assertSelectorMatches,resolveOpenRuntimeHints:r.resolveOpenRuntimeHints},observationStore:{get:n.get,bindAuthority:r.bindAuthority},coordinator:r.createCoordinator()}}function mp(e){let{internal:t,...n}=e;return{request:n,...t?.publicNetworkOnly?{publicNetworkOnly:!0}:{},...t?.resolvedSessionScope?{resolvedSessionScope:t.resolvedSessionScope}:{}}}function hp(e,t){let n=b({...e,...t});return Object.keys(n).length>0?n:void 0}function gp(e,t){return async({dispatch:n,...r})=>{let i=hp(t.internal,n);return await e(i?{...r,internal:i}:r)}}function _p(e){let{sessionStore:t,mutationStore:n,hostCwd:r}=e,i=()=>t.get();return{view(){let e=i();if(e)return{repairBoundary:yt(e),pendingRecordAndHeal:e.pendingRecordAndHeal,scriptPublication:vp(e.scriptPublication??Lt)}},armStep(e){n.update(t=>{mt(t,{saveScript:e.saveScript,force:e.force,sourcePath:e.sourcePath,healedSiblingPath:bi(e.sourcePath),firstArm:e.firstArm},r)})},demoteForRerunIfArmed(){yt(i())!==void 0&&n.update(_t)},markCompleteIfArmed(){yt(i())!==void 0&&n.update(gt)},markSessionHeldIfArmed(e){if(e.ok||!ht(i()))return e;let t=En(e.error.details?.divergence);return t&&(t.repairSessionHeld=!0),e},clearTombstone(){n.clearRepairTombstone()},clearCorrectiveWatermarkIfExpected(e){i()?.pendingRecordAndHeal?.expectedFrom===e&&n.update(t=>{t.pendingRecordAndHeal?.expectedFrom===e&&bp(t)})},resumeStamper:{sessionExists:()=>i()!==void 0,stampCorrectiveWatermark(e){n.update(t=>{yp({session:t,...e})})}}}}function vp(e){return{kind:e.kind,status:e.kind===`none`?void 0:e.status,targetPath:Ft(e),targetForce:Ht(e)}}function yp(e){let{session:t,resume:n,repairHint:r,failedIndex:i,actions:a}=e;t.pendingRecordAndHeal=xp({resume:n,repairHint:r,failedIndex:i,actions:a,actionsCountAtDivergence:t.actions.length})}function bp(e){e.pendingRecordAndHeal=void 0}function xp(e){let{resume:t,repairHint:n,failedIndex:r,actions:i,actionsCountAtDivergence:a}=e;if(n===`record-and-heal`)return t.allowed?{expectedFrom:t.from,actionsCountAtDivergence:a}:void 0;if((n===`caution`||n===`manual`)&&r===i.length)return{expectedFrom:r+1,actionsCountAtDivergence:a}}function Sp(e){let{sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,screenRecordingAdmissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c}=e;return!n||!i||!a||!o||!s||!c?void 0:{throwIfCanceled:c,record:async e=>await fi({req:Cp(e),sessionName:e.sessionName,sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,admissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c})}}function Cp(e){return{token:e.request.token,session:e.sessionName,command:`record`,positionals:e.phase===`start`?[`start`,e.outputPath]:[`stop`],flags:{},meta:e.request.meta}}const wp={resolveSessionScope:on},Tp=async({req:e,host:t,sessionName:n,logPath:r,sessionStore:i,invoke:a,invokeReplayAction:o})=>await cd({...mp(e),host:t,session:Dp(n,r,i),invoke:gp(o??a,e),dependencies:wp}),Ep=async({host:e,req:t,sessionName:n,logPath:r,sessionStore:a,leaseRegistry:o,invoke:s,invokeReplayAction:c,bindDevice:l,platformServices:u,inspectFacts:d,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g,platformResourceCleanup:_})=>{if(!_)throw new i(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let v=Sp({sessionStore:a,bindDevice:l,platformServices:u,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g});return await op({...mp(t),host:e,session:Dp(n,r,a),createSession:(e,t)=>Dp(e,t,a),invoke:gp(c??s,t),dependencies:wp,cleanupSession:async n=>await Op({host:e,req:t,sessionName:n,logPath:r,sessionStore:a,leaseRegistry:o,inspectFacts:d,bindDevice:l,platformServices:u,platformResourceCleanup:_}),...v?{video:v}:{}})};function Dp(e,t,n){let r=t=>{let r=n.get(e);return r?(t(r),!0):!1},a={get:()=>n.get(e),lookup:()=>n.lookup(e),getRuntimeHints:()=>n.getRuntimeHints(e),ensureSessionDir:()=>n.ensureSessionDir(e)};return pp(e,t,a,{createCoordinator:()=>_p({sessionStore:a,mutationStore:{update:r,clearRepairTombstone:()=>n.clearRepairTombstone(e)},hostCwd:n.host.cwd}),assertSelectorMatches:t=>{let r=n.lookup(e);r&&pn(r,t)},resolveOpenRuntimeHints:({request:t,device:r,platform:i})=>Dr({req:t,sessionStore:{getRuntimeHints:t=>t===e?n.getRuntimeHints(e):void 0},sessionName:e,device:r,platform:i}),bindAuthority:t=>{let r=n.lookup(e);return{...ml({sessionStore:n,ref:r,signal:t}),capture:async({flags:a,logPath:o})=>{let s=r?n.requireCurrent(r):void 0;if(!s)throw new i(`NO_ACTIVE_SESSION`,`Session "${e}" is no longer active.`);return await $r({device:s.device,session:s,flags:a,logPath:o,signal:t})}}}})}async function Op(e){let{req:t,sessionName:n,logPath:r,sessionStore:a}=e;if(!a.get(n))return;let o=await wo({host:e.host,req:un({token:t.token,session:n,command:`close`,positionals:[],flags:{},meta:t.meta},t),sessionName:n,logPath:r,sessionStore:a,leaseRegistry:e.leaseRegistry,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup});if(!o.ok)throw new i(o.error.code,o.error.message,{...o.error.details??{},...o.error.hint?{hint:o.error.hint}:{}})}function kp(e){let{req:t,sessionName:n,sessionStore:r}=e;if(t.command!==ae.sessionSaveScript)return null;if((t.positionals?.length??0)>1)return Np(new i(`INVALID_ARGS`,`session save-script accepts at most one output path.`));let a=r.lookup(n);if(!a)return Np(new i(`SESSION_NOT_FOUND`,`No active session "${n}".`,{hint:`Start a fresh journey with open <app> --save-script[=<path>], then retry.`}));let o=r.requireCurrent(a),s=Mp(o);if(s)return Np(s);let c=t.positionals?.[0]?.trim();if(t.positionals?.[0]!==void 0&&!c)return Np(new i(`INVALID_ARGS`,`session save-script path cannot be empty.`));zt(o,{explicitPath:c,liveForce:t.flags?.force},r.host.cwd);let l=r.writeSessionLog(a,{force:qt(o,t.flags?.force),publication:`active`});return l.written?(Wt(o,l.path),{ok:!0,data:{session:o.name,savedScript:l.path,actionCount:l.actionCount,...R(`Published script: ${l.path}`)}}):Np(l.error??new i(`COMMAND_FAILED`,`The active session script was not published.`,{retriable:!0,hint:`The session remains armed; retry session save-script.`}))}function Ap(e){if(St(e))return`repair`;let t=e.scriptPublication;return t?.kind===`authoring`&&t.status!==`armed`?t.status:Rt(e)?void 0:`not-armed`}const jp={repair:()=>new i(`COMMAND_FAILED`,`This session has an active .ad repair transaction and cannot use ordinary active-session publication.`,{hint:`Finish or abort the repair through replay --from and its existing close/teardown protocol.`}),aborted:()=>new i(`COMMAND_FAILED`,`This script recording was aborted by a second successful open and cannot be published.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`}),published:()=>new i(`COMMAND_FAILED`,`This script recording has already been published.`,{hint:`Continue using the live session, or close it and start a fresh authoring session.`}),"not-armed":()=>new i(`COMMAND_FAILED`,`Script recording was not armed before this journey began; session history cannot be published without recording-time target evidence.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`})};function Mp(e){let t=Ap(e);return t?jp[t]():void 0}function Np(e){return{ok:!1,error:c(e)}}function Pp(e){let t=(e[0]??``).toLowerCase();return t===`read`||t===`write`?t:void 0}function Fp(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:tr(e)}}async function Ip(e,t,n){if(n.length!==1)throw new i(`INVALID_ARGS`,`clipboard read does not accept additional arguments`);return{action:`read`,text:await e.operations.readClipboard(Fp(t))}}async function Lp(e,t,n){if(n.length<2)throw new i(`INVALID_ARGS`,`clipboard write requires text (use "" to clear clipboard)`);let r=n.slice(1).join(` `),a={...Fp(t),text:r};return await e.operations.writeClipboard(a),{action:`write`,textLength:Array.from(r).length,...R(`Clipboard updated`)}}async function Rp(e){let{device:t,action:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o}=e;if(n===`read`){let e=await H({command:`clipboard`,device:t,use:at,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(e.type===`response`)return{ok:!1,response:e.response};let n=e.runtime;return{ok:!0,execute:e=>Ip(n,e,r)}}let s=await H({command:`clipboard`,device:t,use:rt,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(s.type===`response`)return{ok:!1,response:s.response};let c=s.runtime;return{ok:!0,execute:e=>Lp(c,e,r)}}async function zp(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=i.lookup(n),l=c?.session,u=t.flags??{},d=J(D.clipboard,l,u);if(d)return d;let f=t.positionals??[],p=Pp(f);if(!p)return m(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let h=await Y({session:l,flags:u,env:i.host.env,platformServices:s});c&&i.requireCurrent(c);let g=await Rp({device:h,action:p,positionals:f,inspectFacts:a,bindDevice:o,platformServices:s});if(!g.ok)return g.response;let _=c?i.requireCurrent(c):void 0,v=await g.execute(nr(r,t.flags,_?.appBundleId,_?.trace?.outPath));return I(i,c,t,t.command,v),{ok:!0,data:{platform:M(h),...v}}}function Bp(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function Vp(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function Hp(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function Up(e,t,...n){for(let r of n)$(e,r,t)}function $(e,t,n){e.push(t),Kr({type:`command`,status:`progress`,message:Wp(t,n)})}function Wp(e,t){return[Pi(e,{useColor:t}),...Ni(e)].join(`
3
- `)}async function Gp(e,t){let{device:n,targetApp:r,session:i,listInstalledApps:a,useColor:o}=t;if(r)try{let t=a?Kp(r,await a(`all`))?.id:void 0;if(!t){$(e,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${M(n)}.`,evidence:{requested:r,platform:M(n)}},o);return}$(e,{id:`target-app`,status:`pass`,summary:`Target app is launchable: ${t}`,evidence:{requested:r,resolved:t,sessionApp:i?.appBundleId}},o)}catch(t){let r=c(t);$(e,{id:`target-app`,status:`fail`,summary:`Target app check failed: ${r.message}`,hint:r.hint??`Install the app or pass an exact package/bundle id or app name.`,command:`agent-device apps --platform ${M(n)} --all`,evidence:{code:r.code,message:r.message}},o)}}function Kp(e,t){let n=e.trim().toLowerCase(),r=t.find(e=>e.id.toLowerCase()===n||e.name.toLowerCase()===n);if(r)return r;let a=t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n));if(a.length===1)return a[0];throw a.length>1?new i(`AMBIGUOUS_MATCH`,`Multiple launchable apps matched "${e}"`,{matches:a.map(e=>e.id),hint:`Pass an exact package/bundle id from agent-device apps --all.`}):new i(`APP_NOT_INSTALLED`,`No launchable installed app matched "${e}"`)}async function qp(e,t,n,r,i){let a=Yp(t,n,r);try{let t=await Zp(a),n=Xp(t.devices,a);return $(e,{id:`device`,status:n.length===0?`fail`:`pass`,summary:nm(n,a,t.failures),hint:n.length===0?am(t.failures):void 0,command:n.length===0?um(a):void 0,evidence:dm(n,t.failures)},i),n.length>0&&$p(e,t.failures,i),{devices:n,hostDevices:n.filter(e=>t.hostDevices.includes(e)),platform:a.platform,target:a.target}}catch(t){let n=c(t);return $(e,{id:`device`,status:`fail`,summary:n.message,hint:n.hint,command:`agent-device devices`,evidence:{code:n.code,details:n.details}},i),{devices:[],hostDevices:[],platform:a.platform,target:a.target}}}function Jp(e,t,n,r){if(!n||!t)return;let i=t.devices.filter(e=>e.booted===!0);if(i.length===1)return i[0];$(e,{id:`target-app-device`,status:`fail`,summary:i.length===0?`Target app check needs one booted device; none matched.`:`Target app check needs one booted device; ${i.length} matched.`,hint:i.length===0?`Boot a device, or adjust --platform/--target/--device/--udid/--serial.`:`Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.`,command:t.platform?`agent-device devices --platform ${t.platform}`:`agent-device devices`,evidence:{targetApp:n,booted:i.map(e=>({platform:M(e),id:e.id,name:e.name}))}},r)}function Yp(e,t,n){let r=e.flags??{};return Hn({platform:r.platform??t?.device.platform,target:r.target??t?.device.target,device:r.device,udid:r.udid,serial:r.serial,iosSimulatorDeviceSet:r.iosSimulatorDeviceSet,androidDeviceAllowlist:r.androidDeviceAllowlist},n)}function Xp(e,t){return e.filter(e=>be(e,t,{includeExplicitSelectors:!0}))}async function Zp(e){if(e.platform)return{...Qp([await Lr(e)]),failures:[]};let t=[],n=[];for(let r of g)try{t.push(await Lr({...e,platform:r}))}catch(e){n.push(tm(r,e))}return{...Qp(t),failures:n}}function Qp(e){return{devices:e.flatMap(e=>e.devices),hostDevices:e.flatMap(e=>e.source===`local`?e.devices:[])}}function $p(e,t,n){for(let r of t)$(e,em(r),n)}function em(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${cm(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${cm(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function tm(e,t){let n=c(t);return{platform:e,message:n.message,hint:n.hint,code:n.code}}function nm(e,t,n){if(e.length===0)return n.length>0?`No ${rm(t)} devices found; ${im(n)}.`:`No ${rm(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${rm(t)} ${lm(e.length,`device`)} available; ${r} booted`,a=om(e,t);return a?`${i} (${a}).`:`${i}.`}function rm(e){let t=e.platform?cm(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function im(e){return e.slice(0,2).map(e=>`${cm(e.platform)} inventory failed: ${e.message}`).join(`; `)}function am(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function om(e,t){if(t.platform||t.target)return;let n=v(e),r=sm();return[`android`,`harmonyos`,`apple`,`vega`,`linux`,`web`].flatMap(e=>{let t=n[e];return t.available>0?[`${r[e]} ${t.available} available, ${t.booted} booted`]:[]}).join(`; `)}function sm(){return{android:`Android`,harmonyos:`HarmonyOS`,apple:`Apple`,vega:`Vega`,linux:`Linux`,web:`web`}}function cm(e){return e===`ios`?`iOS`:e===`macos`?`macOS`:e===`android`?`Android`:e===`harmonyos`?`HarmonyOS`:e===`vega`?`Vega`:e===`linux`?`Linux`:e===`web`?`web`:`Apple`}function lm(e,t){return e===1?t:`${t}s`}function um(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function dm(e,t){let n=new Map;for(let t of e){let e=M(t),r=n.get(e)??{available:0,booted:0};r.available+=1,t.booted===!0&&(r.booted+=1),n.set(e,r)}return{available:e.length,booted:e.filter(e=>e.booted===!0).length,byPlatform:Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}const fm=1500;async function pm(e,t,n,r={}){let i=`http://${e}:${t}/status`;try{let a=await fetch(i,{signal:AbortSignal.timeout(1500)}),o=await a.text(),s=a.ok&&o.toLowerCase().includes(`packager-status:running`),c=s?await mm(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?hm(i,c):`React Native dev server responded at ${i}, but did not report packager-status:running.`,hint:s?void 0:`Verify this is the Metro/Re.Pack instance for the target app, or restart the dev server.`,evidence:{url:i,statusCode:a.status,body:o.slice(0,120),kind:n,...c?{process:c}:{}}}}catch(e){return{id:`metro`,status:n===`auto`?`warn`:`fail`,summary:`React Native dev server is not reachable at ${i}.`,hint:`Start Metro or Re.Pack for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.`,command:`curl -fsS ${i}`,evidence:{url:i,error:e instanceof Error?e.message:String(e),kind:n}}}}async function mm(e,t,n){try{return await(n.resolveProcessInfo??gm)(e,t)}catch{return}}function hm(e,t){return t?.cwd?`React Native dev server is reachable at ${e} (cwd: ${t.cwd}).`:`React Native dev server is reachable at ${e}.`}async function gm(e,t){if(!_m(e))return;let n=await vm(t);if(n!==void 0)return{pid:n,cwd:await ym(n)}}function _m(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function vm(e){let t=await me(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:fm});if(t.exitCode===0)return t.stdout.split(`
4
- `).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function ym(e){let t=await me(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:fm});if(t.exitCode===0)return t.stdout.split(`
5
- `).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const bm=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],xm=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerDeviceType`,`providerProject`,`providerBuild`,`providerSessionName`,`providerDeviceOrientation`,`providerGeoLocation`,`providerTimezone`,`providerAppiumVersion`,`providerLanguage`,`providerLocale`,`providerNetworkProfile`,`providerCustomNetwork`,`providerNoResignApp`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function Sm(e,t){let n=Fi(e.meta?.cwd);return{targetApp:Dm(e.flags?.targetApp)??t?.appBundleId,metroHost:Dm(e.runtime?.metroHost)??`127.0.0.1`,metroPort:Om(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:Tm(e,n)}}function Cm(e,t={}){let n=Em(e);return n?[{id:`remote-connection`,status:t.required?`pass`:`info`,summary:`Remote daemon/session or provider scope is configured.`,evidence:n}]:t.required?[{id:`remote-connection`,status:`fail`,summary:`No remote daemon/session or provider scope is configured.`,hint:`Use connect, --remote-config <path>, or direct remote/provider flags for the command.`}]:[]}function wm(e,t,n,r={}){let i=n?e.listRefs().filter(e=>e.address!==t&&e.session.device.platform===n.device.platform&&e.session.device.id===n.device.id).map(e=>e.address):[];return n?[{id:`session`,status:i.length>0?`warn`:`pass`,summary:i.length>0?`Other active sessions target the same device: ${i.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:i.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:i.length>0?`agent-device close --session ${i[0]} --platform ${M(n.device)}`:void 0,evidence:{session:t,sameDeviceSessions:i,sessionStateDir:e.resolveSessionDir(t)}}]:[{id:`session`,status:`info`,summary:r.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:`This is expected before a run. Use open when app foreground state matters.`}]}function Tm(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function Em(e){let t={...Object.fromEntries([...bm,...xm].flatMap(t=>typeof e.flags?.[t]==`string`?[[t,`<configured>`]]:[])),...e.flags?.sessionIsolation===`tenant`?{sessionIsolation:`tenant`}:{}};return Object.keys(t).length>0?t:void 0}function Dm(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Om(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}async function km(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,inspectFacts:a,bindDevice:o}=e;if(t.command!==D.doctor)return null;let s=Am(e.hostDiagnostics),c=r.get(n),l=Sm(t,c),u=Nm(r,n),d=Mi(e.host.env,!!process.stderr.isTTY),f=[];if(Up(f,d,{id:`agent-device`,status:`pass`,summary:`agent-device ${wn()} using ${u}`,evidence:{version:wn(),stateDir:u}},...Cm(t,{required:l.remote}),...wm(r,n,c,{remote:l.remote})),l.remote)return Rm(f,l);let p=jm(l,u,i),m=await qp(f,t,c,e.host.env,d),h=await s.toolchainCheck(c?.device.platform??m?.platform,p);h&&$(f,h,d);let g=await Pm({checks:f,context:p,hostDiagnostics:s,inventory:m,options:l,session:c,inspectFacts:a,bindDevice:o,req:t,env:e.host.env,useColor:d}),_=c?.device??Mm(m,g);if(_){let e=await s.warmupCheck(_,p);e&&$(f,e,d)}return Rm(f,l,{device:g,includeMetro:!0,inventory:m})}function Am(e){if(!e)throw new i(`COMMAND_FAILED`,`Host diagnostics gateway is not configured`,{reason:`runtime-gateway-missing`});return e}function jm(e,t,n){return Object.freeze({stateDir:t,metroPort:e.metroPort,shouldProbeMetro:e.shouldProbeMetro,isProviderDevice:e=>Zn(e),emitProgress:e=>Kr({type:`command`,status:`progress`,message:e}),listLocalDeviceInventory:async e=>await zr(e),shouldPropagateInventoryProbeError:Ir,transportOverrides:Object.freeze({androidAdb:n})})}function Mm(e,t){let n=e?.hostDevices??[];if(t)return n.includes(t)?t:void 0;let r=n.filter(e=>N(e)&&e.kind===`simulator`);return r.find(e=>e.booted===!0)??r[0]}function Nm(e,t){let n=q.dirname(e.resolveSessionDir(t));return q.basename(n)===`sessions`?q.dirname(n):n}async function Pm(e){let{checks:t,context:n,hostDiagnostics:r,inventory:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=e,f=o?.device??Jp(t,i,a.targetApp,d);return f&&await Fm(t,{context:n,hostDiagnostics:r,device:f,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}),a.shouldProbeMetro&&$(t,await pm(a.metroHost,a.metroPort,a.kind),d),Up(t,d,...await r.ambientChecks(n)),f}async function Fm(e,t){let{context:n,hostDiagnostics:r,device:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=t,f;try{f=await Im({device:i,req:l,targetApp:a.targetApp,inspectFacts:s,bindDevice:c,env:u})}catch(e){f=async()=>{throw e}}await Gp(e,{device:i,session:o,targetApp:a.targetApp,listInstalledApps:f,useColor:d}),Up(e,d,...await r.deviceChecks(i,n))}async function Im(e){if(e.device.platform!==`harmonyos`)return Lm(e)}async function Lm(e){let{device:t,req:n,targetApp:r,inspectFacts:i,bindDevice:a,env:o}=e;if(!r||!i||!a)return;let s=await i(t),c=s.operations.listApps,l=s.operations.ensureReady;if(!c.available||!l.available)return;let u=await a(t,st),d=V(n.flags?.androidDeviceAllowlist,o),f=await ko(u,{serial:n.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0});return async e=>await Ao(u,f,e)}function Rm(e,t,n={}){let r=Bp(e);return{ok:!0,data:{status:r,summary:Vp(r),kind:t.kind,platform:n.device?M(n.device):n.inventory?.platform,target:n.device?.target??n.inventory?.target,targetApp:t.targetApp,metro:n.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:Hp(e)}}}async function zm(e){return await H({...e,command:`prepare`,use:ot})}async function Bm(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]??``;if(a!==`ios-runner`)return m(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let o=i.get(n),s=t.flags??{},c=J(D.prepare,o,s);if(c)return c;let l=await ge(`prepare_resolve_device`,()=>Y({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),void 0,`start`),u=await ge(`prepare_admit_runtime`,()=>zm({device:l,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}),void 0,`start`);if(u.type===`response`)return u.response;let d=Date.now(),f=await u.runtime.operations.prepareAppleRunner({timeoutMs:Vm(t),execution:{requestId:t.meta?.requestId,logPath:r,traceLogPath:o?.trace?.outPath,verbose:t.flags?.verbose,iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir,runnerLeaseContext:fr(t)}});return{ok:!0,data:Hm(a,l,Math.max(0,Date.now()-d),f)}}function Vm(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:lt}function Hm(e,t,n,r){return{action:e,platform:M(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:Um(n,r),message:`Prepared Apple runner: ${t.name}`}}function Um(e,t){let n=Wm(t.buildMs),r=Gm(t.connectMs),i=Gm(t.healthCheckMs);return{totalMs:e,additiveParts:{...n===void 0?{}:{buildMs:n},connectAfterBuildMs:Math.max(0,r-(n??0)),healthCheckMs:i},containment:n===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},note:`Top-level prepare timing fields are diagnostic and may overlap; use timing.additiveParts for additive wall-clock phases.`}}function Wm(e){return e===void 0?void 0:Gm(e)}function Gm(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}const Km=e=>jo(e),qm=e=>zs({host:e.host,req:e.req,createCommandSurface:e.createCommandSurface,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim}),Jm=e=>wo({host:e.host,req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,leaseRegistry:e.leaseRegistry,leaseLifecycleProvider:e.leaseLifecycleProvider,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup}),Ym=async({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u})=>await Zc({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u}),Xm={session_list:Km,devices:Km,capabilities:Km,apps:Km,doctor:async({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s})=>await km({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s}),boot:Ws,shutdown:qs,appstate:nc,session_save_script:async({req:e,sessionName:t,sessionStore:n})=>kp({req:e,sessionName:t,sessionStore:n}),runtime:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await sa({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),clipboard:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await zp({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),keyboard:Ra,perf:Ym,logs:Ym,events:Ym,network:Ym,audio:Ym,prepare:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await Bm({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),install:$a,reinstall:$a,uninstall:$a,install_source:$a,release_materialized_paths:async({req:e})=>await Gi({req:e}),push:$a,"trigger-app-event":za,open:qm,replay:Tp,test:Ep,batch:async({req:e,sessionName:t,invoke:n})=>await eo(e,t,n),close:Jm};async function Zm(e){let{host:t,req:n,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o=new Zt,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}=e,T=Xm[n.command];return T?await T({host:t,req:n,createCommandSurface:e.createCommandSurface,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}):null}export{Zm as handleSessionCommands};
1
+ import{$ as e,C as t,H as n,N as r,Q as i,R as a,S as o,V as s,f as c,k as l,n as u,p as d,s as f,st as p,tt as m,w as h}from"./sdk-contracts.js";import{U as g,V as _,z as v}from"./tv-remote.js";import{i as y,j as b,n as x,t as S,v as C}from"./sdk-batch-runner.js";import{a as w,n as ee,t as T}from"./snapshot-diagnostics.js";import{$ as E,A as te,E as D,F as O,G as ne,I as re,M as k,N as ie,R as A,T as ae,Y as oe,at as se,et as ce,j as le,k as ue,m as de,tt as fe}from"./back-mode.js";import{H as pe,Q as me,St as he,_t as j,yt as ge}from"./sdk-io.js";import"./diagnostics.js";import{A as _e,B as ve,D as ye,I as M,N as be,P as xe,T as N,b as P,v as Se,w as F}from"./sdk-device.js";import{$ as Ce,A as we,At as Te,B as Ee,Cr as De,F as Oe,G as ke,I as Ae,J as je,K as Me,L as Ne,Mn as Pe,N as Fe,Nn as Ie,Ot as Le,P as Re,Pn as ze,Q as Be,R as Ve,Sn as He,Sr as Ue,T as We,U as Ge,W as Ke,X as qe,Y as Je,Z as Ye,ar as Xe,d as Ze,dr as Qe,f as $e,ft as et,ir as tt,j as nt,kt as rt,lt as it,nr as at,q as ot,qt as st,rn as ct,tt as lt,ut,v as dt,vt as ft,wr as pt,yt as mt,z as ht}from"./sdk-batch.js";import{c as gt,d as _t,f as vt,h as yt,l as bt,m as xt,o as I,p as St,s as Ct,u as wt}from"./session-store.js";import{a as Tt,i as Et,n as Dt,o as Ot,t as kt}from"./target-evidence.js";import{a as At,i as jt,n as Mt,o as Nt,r as Pt,s as Ft,t as It}from"./vars.js";import{A as Lt,N as Rt,_ as zt,d as Bt,g as Vt,h as Ht,j as Ut,k as Wt,l as Gt,m as Kt,p as qt,s as Jt,u as Yt}from"./parameterized-recorded-fill.js";import{n as Xt,r as Zt,t as Qt}from"./target-evidence-tree.js";import{A as $t,D as en,E as tn,O as nn,_ as rn,b as an,d as on,f as sn,g as cn,h as ln,j as un,k as dn,m as fn,o as pn,p as mn,s as hn,v as gn,x as _n,y as vn}from"./src.js";import{g as yn,i as bn}from"./observability.js";import{i as L,n as xn,r as R}from"./success-text.js";import{t as Sn}from"./app-inventory.js";import{n as Cn,r as wn}from"./output-path.js";import"./command.js";import{t as z}from"./session-paths.js";import{c as Tn,s as En}from"./session-artifact-paths.js";import{a as Dn}from"./version.js";import{n as On}from"./keyed-lock.js";import"./retry.js";import{i as kn,n as An}from"./replay-divergence.js";import{n as jn,t as Mn}from"./deploy-result-target.js";import{_ as Nn,b as Pn,d as Fn,f as In,g as Ln,h as Rn,m as zn,p as Bn,u as Vn,y as Hn}from"./device-claim-recovery.js";import{t as Un}from"./keyboard-actions.js";import{a as Wn,c as Gn,d as Kn,h as qn,o as Jn,r as Yn,s as Xn,u as Zn}from"./replay-script-selection.js";import{a as Qn,n as $n}from"./artifact-tracking.js";import{n as er}from"./provider-device-admission.js";import{_ as tr,d as nr,g as rr,n as ir,o as B,r as ar,u as or}from"./snapshot-runtime-capture-input.js";import{a as sr,f as cr,i as lr,l as ur,n as dr,p as fr,t as pr,u as mr}from"./device-claims.js";import{i as hr,n as gr}from"./lease-context.js";import{C as _r,S as vr,_ as yr,a as br,c as xr,d as Sr,f as Cr,g as wr,h as Tr,i as Er,l as Dr,m as Or,n as kr,o as Ar,p as jr,r as Mr,s as Nr,t as Pr,u as Fr,x as Ir,y as Lr}from"./session-runtime.js";import{f as Rr}from"./daemon-command-registry.js";import{n as V}from"./device-isolation.js";import{a as zr,n as Br,o as Vr,r as Hr}from"./device-inventory-context.js";import{l as Ur}from"./selector-pipeline-policy.js";import{a as Wr,c as Gr,l as Kr,o as qr,s as Jr,t as Yr}from"./request.js";import{i as Xr,n as Zr}from"./session-capture-binding.js";import{n as H,t as Qr}from"./runtime-admission.js";import{c as $r,f as ei,o as ti,r as ni}from"./runtime-session.js";import{n as ri}from"./snapshot-node-lookup.js";import{a as ii,i as U,n as W,r as G,t as ai}from"./session-runtime-admission.js";import{n as oi}from"./gesture-runtime.js";import{a as si,c as ci,i as li,l as ui,o as di,r as fi,s as pi,t as mi}from"./app-log-session-resource.js";import{t as hi}from"./record-runtime.js";import{t as gi}from"./snapshot-runtime.js";import{n as _i,r as vi}from"./device-selection-resolver.js";import{t as yi}from"./audio-probe-result.js";import{a as bi,c as xi,d as Si,g as Ci,h as wi,l as Ti,m as Ei,n as Di,o as Oi,p as ki,r as Ai,t as ji,u as Mi}from"./session-replay-vars.js";import{n as Ni}from"./replay.js";import{t as Pi}from"./replay-backend-registry.js";import{n as Fi}from"./status-markers.js";import{n as Ii,r as Li}from"./doctor-lines.js";import{t as Ri}from"./project-runtime.js";import{createHash as zi}from"node:crypto";import K,{promises as Bi}from"node:fs";import q from"node:path";import{setTimeout as Vi}from"node:timers/promises";function Hi(e){throw new a(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function Ui(e){let t=e.meta?.installSource;if(!t)throw new a(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(t.kind){case`url`:if(!t.url||t.url.trim().length===0)throw new a(`INVALID_ARGS`,`install_from_source url source requires a non-empty url`);return t;case`path`:if(!t.path||t.path.trim().length===0)throw new a(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return t;case`github-actions-artifact`:throw new a(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:Hi(t)}}function Wi(e){let t=Ui(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:Qn(n,e.meta?.tenantId)},cleanup:()=>{$n(n)}}}const Gi=new WeakMap;function Ki(e,t,n){Gi.set(e,{originalId:t.id,selected:n})}function J(e,t,n){return t||tn(n)?null:f(`INVALID_ARGS`,`${e} requires an active session or an explicit device selector (e.g. --platform ios).`,p())}async function Y(e){if(!en(e.flags)&&e.session){let t=await Ji(e.session.device,e.platformServices,e.env);return Ki(e.platformServices,e.session.device,t),t}let t=await Zn(e.flags??{},{env:e.env,androidAvdSelection:e.androidAvdSelection}),n=e.session?.device.hostApp;return n&&t.id===n.hostDeviceId?e.session.device:t}async function qi(e){return await Y({...e,androidAvdSelection:`include-stopped`})}async function Ji(e,t,n){let r=Gi.get(t);if(r?.originalId===e.id)return r.selected;if(er(e)||!F(e)||e.kind!==`simulator`||process.platform!==`darwin`)return e;if((await t.appleSessionObservation.observeRunnerSession(e.id))?.alive)return{...e,booted:!0};let i={platform:`ios`,target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await Zn(i,{env:n})}catch(e){if(!(e instanceof a)||e.code!==`DEVICE_NOT_FOUND`)throw e}return await Zn({platform:`ios`,target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}},{env:n})}function Yi(e,t){return t?vn(t,e).length===0:!1}async function Xi(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o,s,c;try{o=Wi(t);let l=ea(t),u=await Qi(a,t.flags,r.host.env,e.platformServices),d=await G(e.inspectFacts)(u),f=U(`install_from_source`,d.operations.ensureReady)??U(`install_from_source`,d.operations.materializeAppSource)??U(`install_from_source`,d.operations.deployMaterializedApp);if(f)return f;let p=await W(e.bindDevice)(u,Ye);await p.operations.ensureReady({}),s=await p.operations.materializeAppSource({source:o.source}),c=await ta({artifact:s,retention:l,req:t,session:a,sessionName:n}),i&&B(r.requireCurrent(i));let m=await p.operations.deployMaterializedApp({artifact:s}),h=na(u,s,m,c),g=L(h,`Installed: ${jn(h)}`);return I(r,i,t,`install_source`,g,{positionals:[]}),{ok:!0,data:g}}catch(e){return c&&await Ir(c.materializationId,t.meta?.tenantId).catch(()=>{}),{ok:!1,error:m(e)}}finally{await s?.cleanup(),o?.cleanup()}}async function Zi(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new a(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await Ir(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:m(e)}}}async function Qi(e,t,n,r){let i=$i(t?.platform);if(e&&i&&!xe(e.device,i))throw new a(`INVALID_ARGS`,`install_from_source requested platform ${i}, but session is bound to ${M(e.device)}`);if(!e&&!i)throw new a(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);return e?e.device:await Y({session:e,flags:t,env:n,platformServices:r})}function $i(e){return e===`ios`||e===`android`?e:void 0}function ea(e){let t=e.meta?.retainMaterializedPaths===!0,n=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(n!==void 0&&n<=0)throw new a(`INVALID_ARGS`,`install_from_source retentionMs must be a positive integer`);return{enabled:!0,...n===void 0?{}:{ttlMs:n}}}async function ta(e){if(e.retention.enabled)return await _r({archivePath:e.artifact.archivePath,installablePath:e.artifact.installablePath,tenantId:e.req.meta?.tenantId,sessionName:e.session?e.sessionName:void 0,ttlMs:e.retention.ttlMs})}function na(e,t,n,r){return F(e)?ra(t,n,r):ia(t,n,r)}function ra(e,t,n){let r=t.bundleId??e.bundleId;if(!r)throw new a(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`);return{...oa(n),bundleId:r,...aa(t,e),launchTarget:t.launchTarget??r}}function ia(e,t,n){let r=t.packageName??t.launchTarget??e.packageName;if(!r)throw new a(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{...oa(n),packageName:r,...aa(t,e),launchTarget:t.launchTarget??r}}function aa(e,t){let n=e.appName??t.appName;return n?{appName:n}:{}}function oa(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function sa(e){let{req:t,session:n,inspectFacts:r,bindDevice:i,platformServices:a}=e,o=ca(t);if(!o.ok)return o.response;let s=J(`runtime port-reverse`,n,t.flags);if(s)return s;let c=await Y({session:n,flags:t.flags,env:e.env,platformServices:e.platformServices}),l=await H({device:c,inspectFacts:r,bindDevice:i,platformServices:a,command:`runtime port-reverse`,use:Ee});if(l.type===`response`)return l.response;if(l.runtime.owner.kind!==`provider-runtime`||l.runtime.owner.provider!==o.options.provider)return f(`UNSUPPORTED_OPERATION`,`The selected device is not owned by the requested port-reverse provider.`,{provider:o.options.provider});let u=await l.runtime.operations.configureProviderPortReverse(o.options);return u?{ok:!0,data:{action:`port-reverse`,...u}}:f(`UNSUPPORTED_OPERATION`,`The selected provider device runtime does not support port reverse for this lease.`)}function ca(e){let t=la(e);if(!t.ok)return t;let n=ua(e);return n.ok?{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:e.flags?.portReverseName?.trim()||`runtime`}}:n}function la(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:f(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:f(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function ua(e){let t=da(e.flags?.devicePort),n=da(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:f(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}function da(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}async function fa(e){return await H({...e,command:`runtime clear`,use:Ne})}async function pa(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(i===`port-reverse`)return await sa({req:t,session:r.get(n),env:r.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i===`gesture-viewport`)return await ma({...e,session:r.get(n)});if(!ha(i))return f(`INVALID_ARGS`,`runtime requires set, show, clear, port-reverse, or gesture-viewport`);let a=r.lookup(n),o=a?.session,s=r.getRuntimeHints(n);return i===`clear`?await ga({sessionName:n,sessionStore:r,ref:a,current:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}):i===`show`?_a(n,s):ya({req:t,sessionName:n,sessionStore:r,session:o,current:s})}async function ma(e){if(!e.session)return f(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let t=await oi({device:e.session.device,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!t.ok)return t.response;let n=ar(e.logPath,e.req.flags,e.session.appBundleId,e.session.trace?.outPath,e.req.meta?.requestId,e.req.meta);return{ok:!0,data:{viewport:await t.read(n)}}}function ha(e){return e===`set`||e===`show`||e===`clear`}async function ga(e){let{sessionName:t,sessionStore:n,ref:r,current:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=r?n.requireCurrent(r):void 0;if(Mr(i)&&c?.appBundleId){let e=await fa({device:c.device,inspectFacts:a,bindDevice:o,platformServices:s});if(e.type===`response`)return e.response;let t=n.requireCurrent(r);B(t),await e.runtime.operations.clearRuntimeHints({appId:t.appBundleId,values:Nr(i)})}let l=r?n.clearRuntimeHints(r):!!i;return r||n.setRuntimeHints(t,void 0),{ok:!0,data:{session:t,cleared:l}}}function _a(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function va(e){return e?M(e.device):void 0}function ya(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=va(i),s=Fr(t.flags?.platform??a?.platform??o);if(!s)return f(`INVALID_ARGS`,`runtime set only supports iOS, Android, and HarmonyOS sessions. Pass --platform ios|android|harmonyos or open a supported session first.`);if(o!==void 0&&o!==s)return f(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=br(a,Pr(t.flags,s));return kr(c)===0?f(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}const ba=/^[A-Za-z0-9_.:-]{1,64}$/,xa=8192,Sa=4096;function Ca(e){let t=e[0]?.trim(),n=e[1]?.trim();if(!t)throw new a(`INVALID_ARGS`,`trigger-app-event requires <event> [payloadJson]`);if(!ba.test(t))throw new a(`INVALID_ARGS`,`Invalid trigger-app-event event name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});if(e.length>2)throw new a(`INVALID_ARGS`,`trigger-app-event accepts at most two arguments: <event> [payloadJson]`);return{eventName:t,payload:Ta(n,t)}}function wa(e,t,n,r){let i=M(e),o=Ea(e,r);if(!o)throw new a(`UNSUPPORTED_OPERATION`,`No app event URL template configured for ${i}.`,{hint:`Set AGENT_DEVICE_${i.toUpperCase()}_APP_EVENT_URL_TEMPLATE or AGENT_DEVICE_APP_EVENT_URL_TEMPLATE, for example "myapp://agent-device/event?name={event}&payload={payload}".`});let s=n?JSON.stringify(n):``,c=o.replaceAll(`{event}`,encodeURIComponent(t)).replaceAll(`{payload}`,encodeURIComponent(s)).replaceAll(`{platform}`,encodeURIComponent(i));if(c.length>Sa)throw new a(`INVALID_ARGS`,`trigger-app-event URL exceeds maximum supported length`,{hint:`Reduce payload size or shorten AGENT_DEVICE_*_APP_EVENT_URL_TEMPLATE.`,length:c.length,maxLength:Sa});return c}function Ta(e,t){if(e)try{let n=JSON.parse(e);if(!n||typeof n!=`object`||Array.isArray(n))throw new a(`INVALID_ARGS`,`trigger-app-event payload for "${t}" must be a JSON object`);let r=JSON.stringify(n);if(Buffer.byteLength(r,`utf8`)>xa)throw new a(`INVALID_ARGS`,`trigger-app-event payload for "${t}" exceeds ${xa} bytes`);return n}catch(t){throw t instanceof a?t:new a(`INVALID_ARGS`,`Invalid trigger-app-event payload JSON: ${e}`)}}function Ea(e,t){return((F(e)?t.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:N(e)?t.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:t.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??t.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE)?.trim()||void 0}async function Da(e,t,n,r,i){let{eventName:a,payload:o}=Ca([...r]),s=wa(t,a,o,i),c={eventUrl:s,...n.appBundleId===void 0?{}:{options:{appBundleId:n.appBundleId}},execution:ir(n)};return await e.operations.triggerAppEvent(c),{event:a,eventUrl:s,transport:`deep-link`,...R(`Triggered app event: ${a}`)}}async function Oa(e){let{host:t,device:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s}=e,c=await H({command:`trigger-app-event`,device:n,use:it,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s});if(c.type===`response`)return{ok:!1,response:c.response};let l=c.runtime;return{ok:!0,execute:e=>Da(l,n,e,r,t.env)}}function ka(e){let t=(e[0]??`status`).toLowerCase();if(!Un(t))throw new a(`INVALID_ARGS`,`keyboard requires a subcommand: status, get, dismiss, enter, or return`);if(e.length>1)throw new a(`INVALID_ARGS`,`keyboard accepts at most one subcommand argument`);return Aa(t)}function Aa(e){return e===`get`?`status`:e===`return`?`enter`:e}const ja={"ime-probe":`android`},Ma={"ime-probe":`android`,mechanism:`ios`,acknowledged:`harmonyos`},Na={"visibility-echo":`ios`,"android-acknowledged":`android`,"harmonyos-acknowledged":`harmonyos`};function Pa(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:ir(e)}}async function Fa(e,t){let n=await H(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:e=>t(r,e)}}function Ia(e,t){return e.operations.keyboardStatus(Pa(t)).then(e=>({platform:ja[e.kind],action:`status`,visible:e.visible,inputType:e.inputType,type:e.type,inputMethodPackage:e.inputMethodPackage,focusedPackage:e.focusedPackage,focusedResourceId:e.focusedResourceId,inputOwner:e.inputOwner}))}async function La(e,t){let n=await e.operations.keyboardDismiss(Pa(t)),r=Ma[n.kind];return n.kind===`mechanism`?{platform:r,action:`dismiss`,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,mechanism:n.mechanism,...R(Ba(n.dismissed===!0,n.mechanism))}:n.kind===`acknowledged`?{platform:r,action:`dismiss`,...R(`Keyboard dismissed`)}:{platform:r,action:`dismiss`,attempts:n.attempts,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,inputType:n.inputType,type:n.type,inputMethodPackage:n.inputMethodPackage,focusedPackage:n.focusedPackage,focusedResourceId:n.focusedResourceId,inputOwner:n.inputOwner}}async function Ra(e,t){let n=await e.operations.keyboardEnter(Pa(t)),r=Na[n.kind];return n.kind===`visibility-echo`?{platform:r,action:`enter`,visible:n.visible,wasVisible:n.wasVisible,...R(`Keyboard enter pressed`)}:{platform:r,action:`enter`,...R(`Keyboard enter pressed`)}}async function za(e){let t=ka(e.positionals),{device:n,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o}=e;return t===`status`?await Fa({command:`keyboard status`,device:n,use:Te,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>Ia(e,t)):t===`dismiss`?await Fa({command:`keyboard dismiss`,device:n,use:Le,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>La(e,t)):await Fa({command:`keyboard enter`,device:n,use:rt,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>Ra(e,t))}function Ba(e,t){return e?t===`dismissKey`?`Keyboard dismissed via its dismiss key`:`Keyboard dismissed`:`Keyboard already hidden`}async function Va(e){let{req:t,sessionName:n,sessionStore:r,command:i,positionals:a,recordPositionals:o,updateSession:s,prepare:c}=e,l=r.lookup(n),u=l?.session,d=t.flags??{},f=J(i,u,d);if(f)return f;let p=await Y({session:u,flags:d,env:r.host.env,platformServices:e.platformServices});l&&r.requireCurrent(l);let m=await c(p,l);if(!m.ok)return m.response;let h=l?r.requireCurrent(l):void 0;h&&Rr(t)===`may-invalidate`&&B(h);let g=await m.execute();return l&&(s&&await s(l,g),I(r,l,t,i,g??{},{positionals:o??a})),{ok:!0,data:g??{}}}function Ha(e,t,n){if(!(e||t!==`dismiss`&&t!==`enter`&&t!==`return`||n?.platform!==`ios`))return f(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`)}async function Ua(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=t.positionals??[];return await Va({req:t,sessionName:n,sessionStore:i,command:e.command,positionals:c,platformServices:s,...e.updateSession?{updateSession:e.updateSession}:{},prepare:async(n,l)=>{let u=await e.resolveRuntime({host:e.host,device:n,positionals:c,readiness:!0,inspectFacts:a,bindDevice:o,platformServices:s});if(!u.ok)return{ok:!1,response:u.response};let d=l?i.requireCurrent(l):void 0,f={...ar(r,t.flags,d?.appBundleId,d?.trace?.outPath),surface:d?.surface};return{ok:!0,execute:()=>u.execute(f)}}})}async function Wa(e){return Ha(e.sessionStore.get(e.sessionName),e.req.positionals?.[0]?.trim().toLowerCase(),e.req.flags??{})||await Ua({...e,command:D.keyboard,resolveRuntime:e=>za(e)})}async function Ga(e){return await Ua({...e,command:D.triggerAppEvent,resolveRuntime:e=>Oa(e),updateSession:async(t,n)=>{let r=typeof n?.eventUrl==`string`?n.eventUrl:void 0;if(!r)return;let i=e.sessionStore.requireCurrent(t),a=await e.platformServices.resolveSessionAppBundleIdForTarget(i.device,r,i.appBundleId);a!==void 0&&e.sessionStore.update(t,{appBundleId:a})}})}function Ka(e){let t=e.trim();return t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith(`[`)&&t.endsWith(`]`)}function qa(e,t){let n=t?.subject??`Payload`,r=e.trim();if(!r)throw new a(`INVALID_ARGS`,`${n} cannot be empty`);let i=t?.expandPath?t.expandPath(r,t.cwd):r;try{if(!K.statSync(i).isFile())throw new a(`INVALID_ARGS`,`${n} path is not a file: ${i}`);return{kind:`file`,path:i}}catch(e){if(e instanceof a)throw e;let t=e.code;if(t===`EACCES`||t===`EPERM`)throw new a(`INVALID_ARGS`,`${n} file is not readable: ${i}`);if(t&&t!==`ENOENT`)throw new a(`COMMAND_FAILED`,`Unable to read ${n} file: ${i}`,{cause:String(e)})}if(Ka(r))return{kind:`inline`,text:r};throw new a(`INVALID_ARGS`,`${n} file not found: ${i}`)}async function Ja(e){let t=qa(e,{subject:`Push payload`}),n=t.kind===`inline`?t.text:await Ya(t.path);try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw new a(`INVALID_ARGS`,`push payload must be a JSON object`);return e}catch(t){throw t instanceof a?t:new a(`INVALID_ARGS`,`Invalid push payload JSON: ${e}`)}}async function Ya(e){try{return await Bi.readFile(e,`utf8`)}catch(t){let n=t.code;throw n===`ENOENT`?new a(`INVALID_ARGS`,`Push payload file not found: ${e}`):n===`EISDIR`?new a(`INVALID_ARGS`,`Push payload path is not a file: ${e}`):n===`EACCES`||n===`EPERM`?new a(`INVALID_ARGS`,`Push payload file is not readable: ${e}`):new a(`COMMAND_FAILED`,`Unable to read push payload file: ${e}`,{cause:String(t)})}}async function Xa(e){let{req:t,command:n,sessionName:r,sessionStore:i}=e,a=i.lookup(r),o=a?.session,s=t.flags??{},c=J(n,o,s);if(c)return c;let l=ro(n,t.positionals??[]);if(!l.ok)return l.response;let u=t.meta?.uploadedArtifactId;try{let r=u?Qn(u,t.meta?.tenantId):z(l.appPathInput,e.host.cwd);if(!K.existsSync(r))return f(`INVALID_ARGS`,`App binary not found: ${r}`);let c=await Y({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),d=await G(e.inspectFacts)(c),p=U(n,d.operations.deployApp);if(p)return p;let m=await W(e.bindDevice)(c,qe);a&&B(i.requireCurrent(a));let h=await m.operations.deployApp({app:l.app,appPath:r,replaceExisting:n===`reinstall`}),g=$a(c,l.app,r,h),_=L(g,`Installed: ${g.appName??Mn(g)}`);return no(i,a,g),I(i,a,t,n,_),{ok:!0,data:_}}finally{u&&$n(u)}}async function Za(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=J(`push`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim(),l=t.positionals?.[1]?.trim();if(!c||!l)return f(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`);let u=await Ja(io(l,t.meta?.cwd??e.host.cwd)),d=await Y({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),p=await G(e.inspectFacts)(d),m=U(`push`,p.operations.ensureReady)??U(`push`,p.operations.sendPushNotification);if(m)return m;let h=await W(e.bindDevice)(d,Be);await h.operations.ensureReady({}),i&&B(r.requireCurrent(i));let g=await h.operations.sendPushNotification({appId:c,payload:u}),_=F(d)?L({platform:`ios`,bundleId:c},`Pushed notification to ${c}`):L({platform:M(d),package:c,action:g.action,extrasCount:g.extrasCount},`Pushed notification to ${c}`);return I(r,i,t,`push`,_,{positionals:[c,l]}),{ok:!0,data:_}}async function Qa(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=J(`uninstall`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim();if(!c)return f(`INVALID_ARGS`,`uninstall requires <app>`);let l=await Y({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),u=await G(e.inspectFacts)(l),d=U(`uninstall`,u.operations.uninstallApp);if(d)return d;let p=await W(e.bindDevice)(l,Ce);i&&B(r.requireCurrent(i));let m=await p.operations.uninstallApp({app:c}),h=F(l)?`ios`:`android`,g=m.wasInstalled?`bundleId`in m?m.bundleId:m.packageName:void 0,_=g?L({platform:h,app:c,wasInstalled:!0,appId:g},`Uninstalled: ${g}`):L({platform:h,app:c,wasInstalled:!1},`Not installed: ${c}`);return I(r,i,t,`uninstall`,_),{ok:!0,data:_}}function $a(e,t,n,r){return F(e)?eo(t,n,r):to(e,t,n,r)}function eo(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function to(e,t,n,r){let i=r.packageName,a=e.platform===`harmonyos`?`harmonyos`:`android`;return{app:t||i||r.launchTarget||n,appPath:n,platform:a,...i?{appId:i,package:i,packageName:i}:{},appName:r.appName,launchTarget:r.launchTarget}}function no(e,t,n){!t||n.platform!==`harmonyos`||!n.appId||e.update(t,{appBundleId:n.appId,appName:n.appName??n.app})}function ro(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:f(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:f(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}function io(e,t){let n=qa(e,{subject:`Push payload`,cwd:t,expandPath:(e,n)=>z(e,n??t)});return n.kind===`file`?n.path:n.text}async function ao(e){let{host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e;return n.command===`install`||n.command===`reinstall`?await Xa({host:t,req:n,command:n.command,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`install_source`?await Xi({req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`uninstall`?await Qa({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`push`?await Za({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):null}async function oo(e,t,n){return await x(e,t,async(e,t)=>{let r=e;return await n({...r,internal:{...r.internal,executionPlan:{remainingSteps:t.remainingSteps}}})})}const so=new Set(`acceptAlert.actionButton.appLogCleanup.appLogDoctor.appLogInspect.appLogReattach.appLogStart.appState.appSwitcher.applyRuntimeHints.audioProbeCleanup.audioProbeQuery.audioProbeReattach.audioProbeStart.awaitAlert.back.bootTarget.bootTargetHeadless.captureScreenshot.captureSnapshot.captureSnapshotWithCustomActions.captureSnapshotWithoutActiveApp.clearRuntimeHints.closeApplication.configureProviderPortReverse.deployApp.deployMaterializedApp.dismissAlert.ensureReady.fillPoint.fillRef.finalizeApplicationClose.findText.focusPoint.gestureViewport.home.hoverPoint.hoverRef.keyboardDismiss.keyboardEnter.keyboardStatus.listApps.longPressPoint.materializeAppSource.mediaFastForward.mediaNext.mediaPlayPause.mediaPrevious.mediaRewind.mute.networkDump.openApplication.perfFrames.perfMemorySample.perfMemorySnapshot.perfNativeCaptureCleanup.perfNativeCaptureReattach.perfNativeCaptureStart.perfProfileReport.performDirectionalFlingPlan.performGesturePlan.performMultiTouchGesturePlan.performTargetAuthoredDrag.power.prepareAppleRunner.prepareApplicationOpen.querySelector.readAlert.readClipboard.readSetting.readTextAtPoint.resolveOpenTarget.screenRecordingCleanup.screenRecordingReattach.screenRecordingStart.scrollDirection.sendPushNotification.sendTelephonyEvent.setFoldPose.setOrientation.setSetting.setViewport.shutdownTarget.sleep.tapElementSelector.tapPoint.tapRef.triggerAppEvent.tvRemote.typeText.uninstallApp.unlockOrientation.volumeDown.volumeUp.wake.writeClipboard`.split(`.`));function co(e){return so.has(e)}const lo=new Map(Ze.map(e=>[e.name,e]));function uo(e){let t=new Set;for(let n of e){let e=fo(n);if(e===void 0)return;for(let n of e)t.add(n)}return Object.freeze([...t].sort())}function fo(e){let t=lo.get(e.command)?.platformExecution;if(t===void 0)return;if(t.kind!==`device-runtime`)return[];let n=(`uses`in t?t.selectUses?.(e)??t.uses:[t.use]).flatMap(e=>e.required);return n.every(co)?n:void 0}function po(e){if(e!==void 0&&e.remainingSteps.length!==0)return uo(e.remainingSteps)}function mo(e,t,n){return{requestId:e.meta?.requestId,logPath:t,traceLogPath:n,verbose:e.flags?.verbose,activity:e.flags?.activity,launchConsole:e.flags?.launchConsole,launchArgs:e.flags?.launchArgs,clearAppState:e.flags?.clearAppState,iosXctestrunFile:e.flags?.iosXctestrunFile,iosXctestDerivedDataPath:e.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:e.flags?.iosXctestEnvDir,runnerLeaseContext:hr(e),plannedOperations:po(e.internal?.executionPlan)}}function ho(e,t,n){let r=e.requireCurrent(t);e.recordAction(t,{command:`close`,positionals:n.positionals??[],flags:n.flags??{},result:{session:r.name,...R(`Closed: ${r.name}`)}})}function go(e,t,n){let r=e.requireCurrent(t);if(!wt(r))return{kind:`not-armed`};let i=r.actions.length;ho(e,t,n);let a=qt(r),o=e.writeSessionLog(t,{force:Yt(r,n.flags?.force)});return o.written?{kind:`committed`,path:o.path}:o.error?(r.actions.length=i,{kind:`failed`,error:o.error}):a?{kind:`committed`}:(Ct(r),{kind:`aborted`})}function _o(e,t){let n=m(t),r=Lt(e.scriptPublication??zt);return{ok:!1,error:{...n,details:{...n.details,session:e.name,...r?{savedScript:r}:{}},retriable:!0}}}function vo(e){let{req:t,ref:n,sessionStore:r,platformCloseError:i}=e,a=r.requireCurrent(n);i||ho(r,n,t);try{let e=r.writeSessionLog(n,{force:Yt(a,t.flags?.force)});e.written&&Ht(a,e.path);return}catch(e){return yo(e)}}function yo(e){let t={hint:`Remove the existing target (or pass --force/--overwrite), then re-record with open --save-script.`,retriable:!1};return e instanceof a?new a(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${e.message}`,{...e.details,...t},e.cause):new a(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${m(e).message}`,t)}async function bo(e){let t=e.clearRuntimeHints?ht:Ve,n=await Qr({...e,command:`close`,required:t.required});if(n.type===`response`)return n;if(!e.clearRuntimeHints)return{type:`runtime`,runtime:await n.bind(e.device,Ve)};let r=await n.bind(e.device,ht);return{type:`runtime`,runtime:r,clearRuntimeHints:r.operations.clearRuntimeHints}}async function xo(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a,clearRuntimeHints:o,cleanupFailures:s,repairArmed:c,dispatchTargetedPlatformClose:l,finalizeOrdinaryCloseScript:u}=e,{address:d}=n,f=i.requireCurrent(n),p=async(e,t)=>{try{return await t()}catch(t){s.push({step:e,error:t});return}},m=e.platformResourceCleanup.retainExecutionHostAfterClose({device:f.device,shutdownRequested:t.flags?.shutdown===!0,hasScreenRecording:!!f.screenRecording,hasLease:!!f.lease}),h=i.getRuntimeHints(d);await So(n,i,p,e.platformResourceCleanup),f=i.requireCurrent(n);let g=c?void 0:await l({req:t,session:f,logPath:r,lifecycle:a});o&&f.appBundleId&&Mr(h)&&await p(`runtime_hints`,async()=>{await o({appId:f.appBundleId,values:Nr(h)})});let _=await p(`application_lifecycle`,async()=>await a.operations.finalizeApplicationClose({appBundleId:f.appBundleId,surface:f.surface??`app`,retainRunner:m,stateDir:i.resolveDaemonStateDir(),shutdownTarget:t.flags?.shutdown===!0})??{}),v=c?void 0:u({req:t,ref:n,sessionStore:i,platformCloseError:g});return await p(`materialized_paths`,()=>vr(d)),{platformCloseError:g,saveScriptError:v,shutdownResult:_?.shutdown}}async function So(e,t,n,r){let i=t.resolveCurrent(e)??e.session;await n(`recording`,()=>jr({ref:e,sessionStore:t})),await n(`app_log`,()=>Tr({ref:e,sessionStore:t})),await n(`audio_probe`,()=>Cr({ref:e,sessionStore:t})),await n(`perf_capture`,()=>wr({ref:e,sessionStore:t})),await n(`platform_snapshot_helper`,()=>yr(i,r))}function Co(e,t){return Or({sessionName:e,phase:`session_close_cleanup_failed`,failures:t})}function wo(e){if(e instanceof a)return e;let t=e instanceof Error?e.message:String(e);return new a(`COMMAND_FAILED`,`The platform close failed: ${t}`,{hint:`The repair transaction was not committed because the platform close failed; fix the underlying issue and retry close --save-script.`})}const To=(e,t)=>(e.positionals?.length??0)>0||Lr(t);async function Eo(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a}=e,o=i.requireCurrent(n),s=wt(o),c=JSON.stringify(t.positionals??[]);if(s&&!bt(o,c)){let e=await Oo({req:t,session:o,logPath:r,lifecycle:a});if(e)return{response:_o(o,wo(e))};St(i.requireCurrent(n),c)}let l=go(i,n,t);return l.kind===`failed`?{response:_o(o,l.error)}:{repairArmed:s,...l.kind===`committed`&&l.path?{healedScriptPath:l.path}:{},...l.kind===`aborted`?{aborted:!0}:{}}}async function Do(e){try{let{endedLeaseId:t,providerData:n}=await dn(e);return t&&hn(e.req,t),{providerData:n}}catch(t){let n=m(t);return{response:{ok:!1,error:{...n,hint:`The provider device could not be released. Retry close after the provider is reachable.`,details:{...n.details,session:e.session.name},retriable:!0}}}}}async function Oo(e){let{req:t,session:n,logPath:r,lifecycle:i}=e;if(To(t,n))try{await i.operations.closeApplication({positionals:t.positionals??[],outPath:t.flags?.out,appBundleId:n.appBundleId,surface:n.surface??`app`,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:mo(t,r,n.trace?.outPath)});return}catch(e){return e}}function ko(e,t){if(!e.flags?.saveScript||Bt(t))return;let n=t.scriptPublication;if(n?.kind!==`repair`)throw n===void 0||n.kind===`none`?new a(`INVALID_ARGS`,`close --save-script cannot publish this session: recording was not armed before this journey began, so there is no recording-time target evidence to publish.`,{hint:`Retry with plain close (it tears down without writing). To capture a publishable recording, start a fresh session with open <app> --save-script[=<path>].`}):new a(`INVALID_ARGS`,`close --save-script cannot ${n.status===`published`?`re-publish`:`publish`} this terminal recording. Retry with plain close; it will tear down the session without writing.`)}async function Ao(e){let{session:t,app:n}=e;if(!t.device.hostApp||!n)return;let r=await H({command:`close`,device:t.device,use:je,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice,platformServices:e.platformServices});if(r.type===`response`)return r.response;await r.runtime.operations.resolveOpenTarget({target:n,surface:`app`,foreground:!1})}async function jo(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,c=i.lookup(n);if(!c)return await Fo({req:t,sessionName:n,logPath:r,env:e.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});let l=i.requireCurrent(c);ko(t,l);let u=t.positionals?.[0],d=await Ao({session:l,app:u,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice,platformServices:e.platformServices});if(d)return d;if(t.internal?.closeAppOnly===!0&&!u)return f(`INVALID_ARGS`,`App-only close requires an app target`);if(!e.platformResourceCleanup)throw new a(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let p=e.platformResourceCleanup,m=await bo({device:l.device,clearRuntimeHints:t.internal?.closeAppOnly!==!0&&!!l.appBundleId&&Mr(i.getRuntimeHints(n)),inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(m.type===`response`)return m.response;if(l=i.requireCurrent(c),B(l),t.internal?.closeAppOnly===!0&&u)return await Po({req:t,session:l,logPath:r,lifecycle:m.runtime,app:u});let h=await Eo({req:t,ref:c,logPath:r,sessionStore:i,lifecycle:m.runtime});if(`response`in h)return h.response;let g=await Mo({env:e.host.env,req:t,ref:c,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s,lifecycle:m.runtime,clearRuntimeHints:m.clearRuntimeHints,repairArmed:h.repairArmed,platformResourceCleanup:p});return g.kind===`response`?g.response:No({session:l,repair:h,requestedSaveScript:!!t.flags?.saveScript,shutdownResult:g.shutdownResult,providerData:g.providerData})}async function Mo(e){let{req:t,ref:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,lifecycle:s,clearRuntimeHints:c}=e,{address:l}=n,u=[],{platformCloseError:d,saveScriptError:f,shutdownResult:p}=await xo({req:t,ref:n,logPath:r,sessionStore:i,lifecycle:s,clearRuntimeHints:c,cleanupFailures:u,repairArmed:e.repairArmed,dispatchTargetedPlatformClose:Oo,finalizeOrdinaryCloseScript:vo,platformResourceCleanup:e.platformResourceCleanup}),m=i.requireCurrent(n),h=await Do({req:t,session:m,leaseRegistry:a,leaseLifecycleProvider:o});if(h.response)return{kind:`response`,response:h.response};m=i.resolveCurrent(n)??m;let g=Co(l,u),_=d??g;if(_?m.deviceClaim&&j({level:`warn`,phase:`device_claim_close_effects_unconfirmed`,data:{deviceKey:m.deviceClaim.deviceKey,session:l}}):await lr(m.deviceClaim,e.env),i.retire(n),_)throw _;if(f)throw f;return{kind:`closed`,providerData:h.providerData,shutdownResult:p}}function No(e){let{session:t,repair:n,requestedSaveScript:r,shutdownResult:i,providerData:a}=e;if(n.aborted&&r)return{ok:!1,error:{code:`COMMAND_FAILED`,message:`The repair was aborted and no script was written.`,hint:`Recovery: replay --from <n> --plan-digest <digest> before closing.`,details:{session:t.name}}};let o=n.healedScriptPath?{savedScript:n.healedScriptPath}:{},s=a?{provider:a}:{},c=`Closed: ${t.name}`;return i?{ok:!0,data:L({session:t.name,shutdown:i,...o,...s},c)}:{ok:!0,data:{session:t.name,...R(c),...o,...s}}}async function Po(e){let{req:t,session:n,logPath:r,lifecycle:i,app:a}=e,o=await Oo({req:t,session:n,logPath:r,lifecycle:i});if(o)throw o;return{ok:!0,data:{app:a,...R(`Closed: ${a}`)}}}async function Fo(e){let{req:t,sessionName:n,logPath:r,env:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,{requireNamedSessionHoldsDevice:c}=await import(`./explicit-session-resolution.js`);if(c({req:t,sessionAddress:n,session:void 0}),!t.positionals||t.positionals.length===0)return f(`SESSION_NOT_FOUND`,`No active session`);let l=await bo({device:await Y({session:void 0,flags:t.flags,env:i,platformServices:s}),clearRuntimeHints:!1,inspectFacts:a,bindDevice:o,platformServices:s});return l.type===`response`?l.response:(await l.runtime.operations.closeApplication({positionals:t.positionals,outPath:t.flags?.out,surface:`app`,ensureReady:!0,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:mo(t,r)}),{ok:!0,data:{app:t.positionals[0],...R(`Closed: ${t.positionals[0]}`)}})}function Io(e,t){return e.operations.ensureReady(t)}function Lo(e,t,n){return e.operations.listApps({device:t,filter:n})}async function Ro(e){let{req:t,sessionName:n,sessionStore:r}=e;switch(t.command){case`session_list`:return zo(t,r);case`devices`:return await Vo(t,e.host.env);case`capabilities`:return await Yo({req:t,sessionName:n,sessionStore:r,inspectFacts:e.inspectFacts,platformServices:e.platformServices});case`apps`:return await ts({env:e.host.env,req:t,sessionName:n,sessionStore:r,bindDevice:e.bindDevice,platformServices:e.platformServices,inspectFacts:e.inspectFacts,providerAppCatalog:e.providerAppCatalog});default:return null}}function zo(e,t){let n=cn(e);return{ok:!0,data:{sessions:t.listRefs().filter(e=>rn(e.session,n)).map(e=>Bo(e,t))}}}function Bo({address:e,session:t},n){let r=n.resolveSessionDir(e);return{name:t.name,address:e,sessionStateDir:r,runnerLogPath:Tn(r),platform:M(t.device),...P(t.device.platform)&&t.device.appleOs?{appleOs:t.device.appleOs}:{},target:t.device.target??`mobile`,surface:t.surface??`app`,device:t.device.name,id:t.device.id,device_id:t.device.id,createdAt:t.createdAt,...P(t.device.platform)&&!N(t.device)&&{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}}}async function Vo(e,t){try{let n=Ho(t);return{ok:!0,data:{devices:(await Wo(e,t)).map(e=>({...cs(e),...Uo(e,n)}))}}}catch(e){let t=s(e);return{ok:!1,error:{code:t.code,message:t.message,...t.details?{details:t.details}:{}}}}}function Ho(e){let t=new Map;for(let n of cr({},e)){let e=n.claim;!e||mr(n.classification)||t.set(e.deviceKey,{session:e.session,workspace:e.workspace})}return t}function Uo(e,t){let n=sr(e),r=fr({...n,id:Se(e.id)}),i=t.get(fr(n))??[...t].find(([e])=>e.startsWith(r))?.[1];return i?{claimedBy:i}:{}}async function Wo(e,t){let n=e.flags?.platform;return Jo(await Br(Go(e,n,t)),e.flags?.platform,e.flags?.target)}function Go(e,t,n){let r=e.flags;return{platform:t,target:r?.target,deviceName:r?.device,udid:r?.udid,serial:r?.serial,iosSimulatorSetPath:Ko(r?.iosSimulatorDeviceSet,t,r?.target,n),androidSerialAllowlist:qo(r?.androidDeviceAllowlist,n)}}function Ko(e,t,n,r){return ve({requestedSetPath:e,platform:t,target:n,env:r})}function qo(e,t){let n=V(e,t);return n?Array.from(n).sort():void 0}function Jo(e,t,n){let r=t?e.filter(e=>ls(e,t)):e;return n?r.filter(e=>(e.target??`mobile`)===n):r}async function Yo(e){let t=await ss({...e,androidAvdSelection:`include-stopped`});if(`response`in t)return t.response;let{device:n}=t,r=Xo(n,e.sessionStore.get(e.sessionName),e.req.flags),i=await is(n,e.inspectFacts);return{ok:!0,data:{device:cs(n),...n.platform===`android`&&$o(`press`,i)?{targetReadiness:{press:`bounded-geometry`}}:{},availableCommands:dt().filter(e=>e===`appstate`&&r?!0:$o(e,i))}}}function Xo(e,t,n){return!t||!F(e)&&!N(e)||!Yi(n,t)?!1:Zo(t)||Qo(e,t)}function Zo(e){return!!(e.appName||e.appBundleId)}function Qo(e,t){return!!(N(e)&&t.surface!==void 0&&t.surface!==`app`&&t.surface!==`frontmost-app`)}function $o(e,t){let n=$e(e);return!n||!t?!1:n.some(e=>e.length>0&&e.every(e=>es(t,e)))}function es(e,t){return Object.hasOwn(e.operations,t)?e.operations[t]?.available===!0:!1}async function ts(e){let{req:t,sessionName:n,sessionStore:r,bindDevice:i,inspectFacts:a,platformServices:o}=e,s=await ns(t,e.providerAppCatalog);if(s)return s;let c=await ss({req:t,sessionName:n,sessionStore:r,androidAvdSelection:`include-stopped`,platformServices:o});if(`response`in c)return c.response;let{device:l}=c,u=Sn(t.flags?.appsFilter),d=V(t.flags?.androidDeviceAllowlist,e.env),f=await as({device:l,inspectFacts:a,bindDevice:i,platformServices:o});if(`response`in f)return f.response;let p=f.runtime;return os(await Lo(p,await Io(p,{serial:t.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0}),u))}async function ns(e,t){let n=rs(e);if(!(!t||!n||!t.supports(n.provider)))return{ok:!0,data:{apps:[...await t.list(n,qr(e.meta?.requestId))]}}}function rs(e){let t=gr(e);if(t.leaseId)return;let n=t.leaseProvider;if(!n)return;let r=e.flags?.platform;if(r===`android`||r===`ios`)return{provider:n,platform:r,...e.internal?.publicNetworkOnly?{publicNetworkOnly:!0}:{}}}async function is(e,t){if(t)try{return await t(e)}catch{return}}async function as(e){let t=await G(e.inspectFacts)(e.device),n=[t.operations.ensureReady,t.operations.listApps].find(e=>!e.available);return n&&!n.available?{response:{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`apps is not supported on this device`,...n.hint?{hint:n.hint}:{}}}}:{runtime:await W(e.bindDevice)(e.device,et)}}function os(e){return{ok:!0,data:{apps:e.map(e=>e.name&&e.name!==e.id?`${e.name} (${e.id})`:e.id)}}}async function ss(e){let{req:t,sessionName:n,sessionStore:r,androidAvdSelection:i,platformServices:a}=e,o=r.get(n),s=t.flags??{},c=J(t.command,o,s);return c?{response:c}:{device:await Y({session:o,flags:s,env:r.host.env,platformServices:a,androidAvdSelection:i})}}function cs({simulatorSetPath:e,iosPhysicalDeviceBackend:t,appleOs:n,...r}){return{...r,platform:M({platform:r.platform,appleOs:n}),...P(r.platform)&&n?{appleOs:n}:{}}}function ls(e,t){return xe(e,t)}function us(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Date.now()+e:void 0}function ds(e){return f(`INVALID_ARGS`,e)}function fs(e,t,n,r,i){try{return e.resolveRequestedOpenSurface({device:t,surfaceFlag:n,openTarget:r,existingSurface:i})}catch(e){return f(e instanceof a?e.code:`INVALID_ARGS`,String(e.message),e instanceof a?e.details:void 0)}}async function ps(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i,platformServices:a}=e;if(!t)return null;let o=await a.validateOpenRelaunchTarget({target:n,platform:i.platform,surface:r});return o?ds(o):null}async function ms(e){let{shouldRelaunch:t,openTarget:n,platform:r,platformServices:i}=e;if(!t)return null;let a=await i.validateOpenRelaunchTarget({target:n,platform:r});return a?ds(a):null}function hs(e){let t=Sr(e);if(!t.ok)return{type:`response`,response:t};let{runtime:n,previousRuntime:r,replacedStoredRuntime:i}=t.data;return{type:`plan`,plan:{runtime:n,previousRuntime:r,replacedStoredRuntime:i,applyRuntimeHints:Mr(n),clearRemovedRuntimeHints:Dr({replacedStoredRuntime:i,previousRuntime:r,runtime:n,session:e.existingSession})}}}async function gs(e){let{req:t,logPath:n,surface:r,openTarget:i,existingSession:o,runtime:s,runtimeHintPlan:c,clearRuntimeHints:l,foreground:u}=e;await s.operations.prepareApplicationOpen({target:i,currentAppBundleId:o?.appBundleId,hasExistingSession:o!==void 0,surface:r,prewarmRunnerOnColdBoot:r===`app`&&!!i&&!y(i??``),execution:{startupDeadlineAtMs:vs(t),requestId:t.meta?.requestId,logPath:n,traceLogPath:o?.trace?.outPath,verbose:t.flags?.verbose,iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir,runnerLeaseContext:hr(t)}});let{appBundleId:d,appName:f}=await _s({runtime:s,surface:r,openTarget:i,existingAppBundleId:o?.appBundleId,foreground:u});if(c.clearRemovedRuntimeHints){if(!l)throw new a(`COMMAND_FAILED`,`Runtime hint clear operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await Er({replacedStoredRuntime:c.replacedStoredRuntime,previousRuntime:c.previousRuntime,runtime:c.runtime,session:o,clearRuntimeHints:l})}return{type:`details`,details:{appBundleId:d,appName:f,runtime:c.runtime}}}async function _s(e){let{runtime:t,surface:n,openTarget:r,existingAppBundleId:i,foreground:a}=e,o=await t.operations.resolveOpenTarget({target:r,currentAppBundleId:i,surface:n,foreground:a});return{appBundleId:o.appBundleId,appName:o.appName}}function vs(e){return us(e.flags?.timeoutMs)}async function ys(e){let{req:t,hasExistingSession:n}=e;return t.flags?.foreground===!0?t.positionals?.[0]?{type:`resolved`,req:t}:n?{type:`response`,response:f(`INVALID_ARGS`,`open --foreground only applies to a fresh session. Close the current session first, or omit --foreground.`)}:t.flags?.udid!==void 0||t.flags?.device!==void 0?{type:`response`,response:f(`INVALID_ARGS`,`open --foreground resolves the device itself; drop --udid/--device or open explicitly: agent-device open <app> --udid <udid>.`)}:t.flags?.platform!==void 0&&t.flags.platform!==`ios`?{type:`response`,response:f(`INVALID_ARGS`,`open --foreground only supports --platform ios; drop the flag or pass --platform ios.`)}:{type:`resolved`,req:nn(t)}:{type:`not-requested`}}async function bs(e){let{req:t,ref:n,logPath:r,sessionStore:i,openResponse:a}=e;if(!a.ok||t.flags?.foreground!==!0)return a;try{let o=await gi({createCommandSurface:e.createCommandSurface,req:{...t,command:`snapshot`,positionals:[],flags:{...t.flags,snapshotInteractiveOnly:!0,noRecord:!0}},sessionName:n.address,sessionRef:n,logPath:r,sessionStore:i,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return o.ok?{ok:!0,data:{...a.data,snapshot:o.data}}:xs(a.data,o.error)}catch(e){return xs(a.data,m(e))}}function xs(e,t){return{ok:!0,data:{...e,warnings:[...xn(e),`The session is open, but the initial interactive snapshot failed (${t.code}: ${t.message}). Run: agent-device snapshot -i`],initialSnapshotError:t}}}function Ss(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,appName:o,appBundleId:s,surface:c,startup:l,timing:u,device:d,runtime:f,runtimeHintCount:p,sessionReused:m,selection:h,launchConfirmation:g}=e,_={session:t,surface:c,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,sessionReused:m,...Cs(h)};return o&&(_.appName=o),s&&(_.appBundleId=s),l&&(_.startup=l),u&&(_.timing=u),Object.assign(_,g??{}),f&&p(f)>0&&(_.runtime=f),d&&(_.platform=M(d),_.target=d.target??`mobile`,_.device=d.name,_.id=d.id,_.kind=d.kind,_e(d.platform)&&(_.serial=d.id)),d&&F(d)&&(_.device_udid=d.id,_.ios_simulator_device_set=d.simulatorSetPath??null),{..._,...R(`Opened: ${o??s??t}`)}}function Cs(e){if(!e)return{};let{device:t,...n}=e;return{selection:n}}function X(e,t,n){n?(e.assertAdmissionOpen(n.address),e.requireCurrent(n)):e.assertPublishable(t)}function ws(e){let{req:t,sessionStore:n,sessionName:r,existingRef:i,device:a,surface:o,appBundleId:s,appName:c,deviceClaim:l}=e;if(X(n,r,i),i){let e=n.update(i,{device:a,surface:o,appBundleId:s,appName:c});return e.lease=$t({req:t,existingLease:e.lease}),l&&(e.deviceClaim=l),ti(e),n.refresh(i)}return n.publish(r,{name:ln(t),sessionScope:t.internal?.resolvedSessionScope??cn(t),device:a,surface:o,appBundleId:s,appName:c,createdAt:Date.now(),actions:[],lease:$t({req:t}),deviceClaim:l})}function Ts(e,t){e.warnings=[...xn(e),t]}function Es(e){let{session:t,existingSession:n,saveScriptRequested:r,responseData:i,hostCwd:a}=e;if(!n&&r){Gt(t,{},a);return}Bt(n)&&(Jt(t),Ts(i,`Script publication was aborted because this session completed a second open. Start a fresh session with open --save-script to author another script.`))}function Ds(e,t){return t.internal?.admittedLease?.backend===`macos-app`?`Took the device over: it rebooted after its previous claim was taken, so the previous app was already gone.`:`Took the device from session "${e.session}" in workspace "${e.workspace}": that device rebooted after its claim was taken, so its app and runner were already gone.`}function Os(e){switch(e.launchConfirmation){case`accepted`:return{launchConfirmation:`accepted`};case`unanswered`:return{launchConfirmation:`unanswered`,launchConfirmationReason:e.launchConfirmationReason};default:return e.launchConfirmationProbeFailure?{launchConfirmationProbeFailure:e.launchConfirmationProbeFailure}:{}}}function ks(){return"agent-device could not read whether iOS is asking to confirm the launch URL, so the launch URL may still be held by a prompt. Check with `alert get` before retrying."}function As(e){return e===`url-owner-unresolved`?"iOS is still holding the launch confirmation and the installed app that owns the launch URL's scheme could not be resolved, so this launch URL has not reached the app. Answer it with `alert accept`.":"iOS shows an alert this open did not recognize (alert-unrecognized), so it left the launch URL unconfirmed. Inspect the current alert with `alert get` before answering it with `alert accept`."}function js(e,t){if(e.platform!==`android`)return!1;let n=t.flags?.testIme;return n===void 0?e.kind===`emulator`:n}function Ms(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:`open-command-roundtrip`,appTarget:t,appBundleId:n}}async function Ns(e,t,n){if(!t)return;let r=await ur(t,n);if(r.status!==`renewed`)return r.conflict?sn(e,r.conflict):f(`DEVICE_IN_USE`,`${e.name} no longer holds the claim this open was made with.`,{reason:`claim-lost-during-open`,deviceKey:t.deviceKey,hint:`Close this session and open the device again to claim it.`})}async function Ps(e){let{req:t,sessionName:r,sessionStore:i,logPath:a,device:o,openTarget:s,openPositionals:c,appName:l,surface:u,appBundleId:d,runtimeHints:p,lifecycle:m,applyRuntimeHints:h,existingRef:g,deviceClaim:_,tookOverDeviceClaim:v,selection:y}=e;X(i,r,g);let b=g?i.requireCurrent(g):void 0,x=b?.snapshot,S=t.flags?.relaunch===!0,C=d,w=Date.now(),ee=await Fs({req:t,sessionName:r,sessionStore:i,device:o,surface:u,sessionAppBundleId:C,appName:l,existingRef:g});if(ee.type===`response`)return ee;let T=ee.ref;X(i,r,T);let E=T?i.requireCurrent(T):void 0,te=Date.now(),D=await m.operations.openApplication({target:s,positionals:c,outPath:t.flags?.out,runtimeLaunchUrl:p?.launchUrl,appBundleId:C,surface:u,hasExistingSession:b!==void 0,relaunch:S,prewarmRunnerBeforeOpen:t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,enableTestIme:js(o,t),stateDir:i.resolveDaemonStateDir(),runtimeHints:Nr(p),applyRuntimeHints:h,execution:mo(t,a,E?.trace?.outPath)});C=D.appBundleId??C;let O={...D.timing},ne=_i(y),re=s?Ms(te,s,C):void 0;if(Jr(t.meta?.requestId)){let e=n();return{type:`response`,response:f(e.code,e.message,e.details)}}X(i,r,T),g&&rr({session:i.requireCurrent(g),command:`open`,positionals:[],flags:void 0,androidFreshnessBaseline:x});let k=i.ensureSessionDir(r),ie=En(k,t.meta?.requestId??ge().requestId);O.totalDurationMs=Math.max(0,Date.now()-w),j({level:`info`,phase:`open_timing`,durationMs:O.totalDurationMs,data:O});let A=Ss({sessionName:E?.name??ln(t),sessionStateDir:k,runnerLogPath:Tn(k),requestLogPath:ie,eventLogPath:i.resolveEventLogPath(r),appName:l,appBundleId:C,surface:u,startup:re,timing:O,device:o,runtime:p,runtimeHintCount:kr,sessionReused:b!==void 0,selection:ne,launchConfirmation:Os(D)});v&&Ts(A,Ds(v,t)),D.launchConfirmation===`unanswered`&&Ts(A,As(D.launchConfirmationReason)),D.launchConfirmation===void 0&&D.launchConfirmationProbeFailure&&Ts(A,ks());let ae=ws({req:t,sessionStore:i,sessionName:r,existingRef:T,device:o,surface:u,appBundleId:C,appName:l,deviceClaim:_}),oe=i.requireCurrent(ae);return tr(oe,O.postOpenObservation),t.runtime!==void 0&&xr(i,r,p),Es({session:oe,existingSession:g?oe:void 0,saveScriptRequested:!!t.flags?.saveScript,responseData:A,hostCwd:i.host.cwd}),i.recordAction(ae,{command:`open`,positionals:c,flags:t.flags??{},runtime:t.runtime===void 0?void 0:p,result:A}),{type:`opened`,ref:ae,response:{ok:!0,data:A}}}async function Fs(e){let{req:t,sessionName:n,sessionStore:r,existingRef:i}=e,a=t.internal?.openLifecycle?.beforeDispatch;if(!a)return{type:`session`,ref:i};let o=ws({req:t,sessionName:n,sessionStore:r,existingRef:i,device:e.device,surface:e.surface,appBundleId:e.sessionAppBundleId,appName:e.appName}),s=await a();return s&&!s.ok?{type:`response`,response:s}:(X(r,n,o),{type:`session`,ref:r.refresh(o)})}function Is(e){let{req:t,device:n,sessionStore:r}=e,i=r.findByDevice(n.id);if(!i)return;let a=mn(t);return fn(t,i.session)?_n(i,n,a):an(i,n,a)}async function Ls(e){let{req:t,device:n,owner:r,sessionName:i,sessionStore:a,reconcileOrphanedDeviceClaim:o,platformServices:s}=e;switch(on(r)){case`none`:return{status:`not-required`};case`ordinary`:return await dr({device:n,session:i,workspace:t.meta?.cwd??e.host.cwd,stateDir:a.resolveDaemonStateDir(),env:e.host.env,reconcileOrphanedDeviceClaim:o,observeDeviceBoot:s.deviceBootObservation})}}async function Rs(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,device:a,surface:o,openTarget:s,lifecycle:c,runtimeHintPlan:l,applyRuntimeHints:u,clearRuntimeHints:d,reconcileOrphanedDeviceClaim:f,selection:p,platformServices:m}=e;X(i,n,void 0);let h=Is({req:t,device:a,sessionStore:i});if(h)return{type:`response`,response:h};let g=await Ls({host:e.host,req:t,device:a,owner:c.owner,sessionName:n,sessionStore:i,reconcileOrphanedDeviceClaim:f,platformServices:m});if(g.status===`conflict`)return{type:`response`,response:sn(a,g.conflict)};let _=g.status===`acquired`?g.ownership:void 0,v=g.status===`acquired`?g.tookOver:void 0,y={mayHaveStarted:!1},b=async()=>await zs({ownership:_,effects:y,sessionName:n,sessionStore:i,env:e.host.env});try{X(i,n,void 0);let f=await gs({req:t,logPath:r,surface:o,openTarget:s,runtime:c,runtimeHintPlan:l,clearRuntimeHints:d,foreground:t.flags?.foreground===!0&&s===void 0});if(f.type===`response`)return await b(),{type:`response`,response:f.response};let m=await Ns(a,_,e.host.env);if(m)return{type:`response`,response:m};y.mayHaveStarted=!0;let h=t.positionals??[],g=s??f.details.appBundleId,x=await Ps({req:t,sessionName:n,sessionStore:i,logPath:r,device:a,openTarget:g,openPositionals:h.length>0?h:g?[g]:[],appBundleId:f.details.appBundleId,appName:f.details.appName,runtimeHints:f.details.runtime,lifecycle:c,applyRuntimeHints:u,surface:o,deviceClaim:_,tookOverDeviceClaim:v,selection:p});return x.response.ok||await b(),x}catch(e){throw await b(),e}}async function zs(e){let{ownership:t,effects:n,sessionName:r,sessionStore:i,env:a}=e;if(!t)return;if(!n.mayHaveStarted){await lr(t,a);return}if(i.get(r)?.deviceClaim?.ownerToken===t.ownerToken)return;let o=await pr(t,a);j({level:`warn`,phase:`device_claim_open_effects_unconfirmed`,data:{deviceKey:t.deviceKey,outcome:o}})}const Bs=new WeakMap;function Vs(e){let t=Bs.get(e);return t||(t=new Map,Bs.set(e,t)),t}async function Hs(e){let t=Je({applyRuntimeHints:e.runtimeHintPlan.applyRuntimeHints,clearRemovedRuntimeHints:e.runtimeHintPlan.clearRemovedRuntimeHints}),n=await Qr({...e,command:`open`,required:t.use.required});if(n.type===`response`)return n;let r=n.bind;switch(t.kind){case`open`:return{type:`runtime`,runtime:await r(e.device,Ge)};case`open-apply-runtime-hints`:{let t=await r(e.device,ke);return{type:`runtime`,runtime:t,applyRuntimeHints:t.operations.applyRuntimeHints}}case`open-clear-runtime-hints`:{let t=await r(e.device,Me);return{type:`runtime`,runtime:t,clearRuntimeHints:t.operations.clearRuntimeHints}}case`open-apply-and-clear-runtime-hints`:{let t=await r(e.device,Ke);return{type:`runtime`,runtime:t,applyRuntimeHints:t.operations.applyRuntimeHints,clearRuntimeHints:t.operations.clearRuntimeHints}}}}async function Us(e){let t=hs(e);if(t.type===`response`)return t;let n=await Hs({device:e.device,runtimeHintPlan:t.plan,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return n.type===`response`?n:{type:`runtime`,runtimeHintPlan:t.plan,admission:n}}async function Ws(e){let{sessionName:t,logPath:n,sessionStore:r}=e,i=r.lookup(t),a=await ys({req:e.req,hasExistingSession:!!i});if(a.type===`response`)return{type:`response`,response:a.response};let o=a.type===`resolved`?a.req:e.req;if(X(r,t,i),i){let a=r.requireCurrent(i);if(o.flags?.saveScript)return{type:`response`,response:f(`INVALID_ARGS`,`open --save-script can only arm a fresh session. Use the current session without --save-script, or close it and start a fresh session.`)};let s=o.flags?.relaunch===!0,c=o.positionals?.[0],l=c??(s?a.appName:void 0),u=fs(e.platformServices,a.device,o.flags?.surface,l,a.surface);if(typeof u!=`string`)return{type:`response`,response:u};if(!l&&u===`app`)return{type:`response`,response:ds(s?`open --relaunch requires an app name or an active session app.`:`Session already active. Close it first or pass a new --session name.`)};let d=await ps({shouldRelaunch:s,openTarget:l,surface:u,device:a.device,platformServices:e.platformServices});if(d)return{type:`response`,response:d};let p=r.requireCurrent(i),m=await Ns(p.device,p.deviceClaim,e.host.env);if(m)return{type:`response`,response:m};let h=await Ji(a.device,e.platformServices,e.host.env),g=vi(h);await o.internal?.retainDeviceExecutionLock?.(h.id);let _=await Us({req:o,sessionStore:r,sessionName:t,device:h,existingSession:a,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(_.type===`response`)return{type:`response`,response:_.response};let{admission:v,runtimeHintPlan:y}=_;X(r,t,i);let b=r.requireCurrent(i);B(b);let x=await gs({req:o,logPath:n,surface:u,openTarget:l,existingSession:b,runtime:v.runtime,runtimeHintPlan:y,clearRuntimeHints:v.clearRuntimeHints,foreground:!1});if(x.type===`response`)return{type:`response`,response:x.response};X(r,t,i);let S=await Ns(h,r.requireCurrent(i).deviceClaim,e.host.env);return S?{type:`response`,response:S}:await Ps({req:o,sessionName:t,sessionStore:r,logPath:n,device:h,openTarget:l,openPositionals:c?o.positionals??[]:l?[l]:[],appBundleId:x.details.appBundleId,appName:x.details.appName,runtimeHints:x.details.runtime,lifecycle:v.runtime,applyRuntimeHints:v.applyRuntimeHints,surface:u,existingRef:i,selection:g})}let s=o.flags?.relaunch===!0,c=o.positionals?.[0];if(s&&!c)return{type:`response`,response:ds(`open --relaunch requires an app argument.`)};let l=await ms({shouldRelaunch:s,openTarget:c,platform:o.flags?.platform===`android`?`android`:void 0,platformServices:e.platformServices});if(l)return{type:`response`,response:l};let u=await Kn(o.flags??{},Xn(c,e.host.env,o.flags?.surface)),d=u.device;await o.internal?.retainDeviceExecutionLock?.(d.id);let p=fs(e.platformServices,d,o.flags?.surface,c);if(typeof p!=`string`)return{type:`response`,response:p};let m=await ps({shouldRelaunch:s,openTarget:c,surface:p,device:d,platformServices:e.platformServices});if(m)return{type:`response`,response:m};let h=await Us({req:o,sessionStore:r,sessionName:t,device:d,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(h.type===`response`)return{type:`response`,response:h.response};let{admission:g,runtimeHintPlan:_}=h;return await On(Vs(r),d.hostApp?.hostDeviceId??d.id,async()=>await Rs({host:e.host,req:o,sessionName:t,logPath:n,sessionStore:r,device:d,surface:p,openTarget:c,lifecycle:g.runtime,runtimeHintPlan:_,applyRuntimeHints:g.applyRuntimeHints,clearRuntimeHints:g.clearRuntimeHints,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim,platformServices:e.platformServices,selection:u}))}async function Gs(e){let t=await Ws(e),n=t.response;return t.type!==`opened`||e.req.flags?.foreground!==!0?n:await bs({...e,inspectFacts:G(e.inspectFacts),bindDevice:W(e.bindDevice),openResponse:n,ref:t.ref})}function Ks(e,t){return{ok:!0,data:{platform:M(e),target:e.target??`mobile`,device:e.name,id:e.id,kind:e.kind,...t,...P(e.platform)&&e.appleOs?{appleOs:e.appleOs}:{}}}}function qs(e){return t=>f(e?`INVALID_ARGS`:`UNSUPPORTED_OPERATION`,e?`boot --headless is supported only for Android emulators.`:`boot is not supported on this device`,void 0,t.hint?{hint:t.hint}:void 0)}function Js(e,t){return!!(e?.trim()||t?.platform===`android`&&t.kind===`emulator`)}async function Ys(e,t){let{sessionName:n,sessionStore:r,req:i,platformServices:a}=e,o=r.get(n),c=i.flags??{};try{let e=await qi({session:o,flags:c,env:r.host.env,platformServices:a});return c.target&&(e.target??`mobile`)!==c.target?{refusal:f(`DEVICE_NOT_FOUND`,`No ${e.platform} device found matching --target ${c.target}.`)}:e}catch(e){if(t&&!Js(c.device,o?.device)&&s(e).code===`DEVICE_NOT_FOUND`)return{refusal:f(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`)};throw e}}async function Xs(e){let t=e.req.flags??{},n=J(e.req.command,e.sessionStore.get(e.sessionName),t);if(n)return n;let r=V(t.androidDeviceAllowlist,e.host.env),i=r?[...r].sort():void 0,a=st({headless:t.headless===!0}),o=await Ys(e,a.kind===`boot-target-headless`);if(`refusal`in o)return o.refusal;let s=await Qr({command:`boot`,device:o,required:a.use.required,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,unavailableResponse:qs(a.kind===`boot-target-headless`)});if(s.type===`response`)return s.response;let c={serial:t.serial,androidSerialAllowlist:i,deadlineAtMs:us(t.timeoutMs)};return Ks(a.kind===`boot-target-headless`?await(await s.bind(o,a.use)).operations.bootTargetHeadless(c):await(await s.bind(o,a.use)).operations.bootTarget(c),{booted:!0})}function Zs(e){return e.available?null:f(`UNSUPPORTED_OPERATION`,`shutdown is supported only for Apple simulators and Android emulators.`,void 0,e.hint?{hint:e.hint}:void 0)}function Qs(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}async function $s(e){let t=e.sessionStore.get(e.sessionName),n=e.req.flags??{},r=J(e.req.command,t,n);if(r)return r;let i=await qi({flags:n,session:t,env:e.sessionStore.host.env,platformServices:e.platformServices}),a=Zs((await G(e.inspectFacts)(i)).operations.shutdownTarget);if(a)return a;if(t&&t.device.platform===i.platform&&t.device.id===i.id)return f(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${e.sessionName}`,session:e.sessionName,platform:M(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind});let o=await(await W(e.bindDevice)(i,ct)).operations.shutdownTarget();return o.success?Ks(i,{shutdown:o}):f(o.error?.code??`COMMAND_FAILED`,Qs(o),{platform:M(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind,shutdown:o})}function ec(t,n){return P(n)?f(`SESSION_NOT_FOUND`,`No active session "${t}". Run open with --session ${t} first.`,e(t)):f(`SESSION_NOT_FOUND`,`No active session "${t}". Run open with --session ${t} first, or omit --session to query by device selector.`,e(t))}function tc(e){return f(`SESSION_NOT_FOUND`,e===`macos`?`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`:`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`)}async function nc(e,t){if(!t.appBundleId)return;let n=await H({command:`appstate`,device:t.device,use:ut,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(n.type!==`response`)try{return(await n.runtime.operations.appState({appBundleId:t.appBundleId})).applicationState}catch(e){if(i(e))throw e;j({level:`warn`,phase:`apple_appstate_runner_read_failed`,data:{code:s(e).code,message:s(e).message}});return}}function rc(e){if(!(!N(e.device)||!e.surface)&&e.surface!==`app`&&e.surface!==`frontmost-app`)return{ok:!0,data:{platform:M(e.device),appName:e.surface,appBundleId:e.appBundleId,source:`session`,surface:e.surface}}}async function ic(e,t){if(!t.appName&&!t.appBundleId){let e=rc(t);if(e)return e;let n=N(t.device)?`macOS`:`iOS`;return f(`COMMAND_FAILED`,`No foreground app is tracked for this ${n} session. Open an app in the session, then retry appstate.`)}let n=await nc(e,t),r=t.appName??t.appBundleId;return{ok:!0,data:{platform:M(t.device),appName:r??`unknown`,appBundleId:t.appBundleId,source:n?`runner`:`session`,...n?{state:n}:{},surface:t.surface??`app`,...F(t.device)?{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}:{}}}}function ac(e,t){let n=V(e,t);return n?[...n].sort():void 0}async function oc(e,t,n){if(F(t)||N(t))return n?ec(e.sessionName,t.platform):tc(N(t)?`macos`:`ios`);let r=e.req.flags??{},i=await H({command:`appstate`,device:t,use:ut,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i.type===`response`)return i.response;let a=i.runtime;await a.operations.ensureReady({serial:r.serial,androidSerialAllowlist:ac(r.androidDeviceAllowlist,e.host.env)});let o=await a.operations.appState();return{ok:!0,data:{platform:M(t),package:o.package,activity:o.activity}}}function sc(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&c(t)&&(!en(a)||P(o)))return{refusal:ec(n,o)};let s=J(`appstate`,i,a);if(s)return{refusal:s};let l=P(i?.device.platform)&&Yi(a,i);return o===`ios`&&!l?{refusal:tc(`ios`)}:o===`macos`&&!l?{refusal:tc(`macos`)}:l&&i?{answeredBy:`apple-session`,session:i}:{answeredBy:`device-runtime`,session:i,namedSessionMissing:!i&&c(t)}}async function cc(e){let t=sc(e);return`refusal`in t?t.refusal:t.answeredBy===`apple-session`?await ic(e,t.session):await oc(e,await Y({session:t.session,flags:e.req.flags??{},env:e.sessionStore.host.env,platformServices:e.platformServices}),t.namedSessionMissing)}function lc(e){return Hn.createNextFence({admissionLedger:e.ledger,resourcePath:e.resourcePath,device:e.device})}async function uc(e){try{return await dc(e)}catch(e){return{ok:!1,error:m(e)}}}async function dc(e){let t=fc(e);if(!t.ok)return t;let n=t.ref,r=e.sessionStore.requireCurrent(n),i=Fe(e.req.positionals),a=await e.inspectFacts(r.device),o=a.operations.audioProbeStart,s=a.operations.audioProbeQuery,c=o.available?`capture`:s.available?`query`:void 0;if(c===void 0)return pc(o,s);let l=Re({probeAction:i.probeAction,mode:c});switch(l.kind){case`query`:return{ok:!0,data:await(await e.bindDevice(r.device,l.use)).operations.audioProbeQuery({action:l.action,durationMs:i.durationMs,bucketMs:i.bucketMs})};case`capture-start`:return await mc(e,n,i,l.use);case`capture-status`:return await hc(e,n);case`capture-stop`:return await gc(e,n)}}function fc(e){let t=e.sessionStore.lookup(e.sessionName);return t?{ok:!0,ref:t}:f(`SESSION_NOT_FOUND`,`audio requires an active session`)}function pc(e,t){let n=(e.available?void 0:e.hint)??(t.available?void 0:t.hint),r=e.available?void 0:e.reason;return f(`UNSUPPORTED_OPERATION`,n??`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`,r?{reason:r}:void 0)}async function mc(e,t,n,r){let i=e.sessionStore.requireCurrent(t),a=Zr(e.sessionStore,t);i.audioProbe&&(await Nn({intent:`disposal`,binding:a}),i=e.sessionStore.requireCurrent(t));let o=await e.bindDevice(i.device,r),s=Ln.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),c=Ln.createNextFence({admissionLedger:e.audioProbeAdmissionLedger,resourcePath:s,device:i.device}),l=q.join(e.sessionStore.ensureSessionDir(e.sessionName),`audio-probe.json`);a.assertAdoptable();let u=await o.operations.audioProbeStart({sessionId:e.sessionName,statusPath:l,durationMs:n.durationMs,bucketMs:n.bucketMs,fence:c});await Rn({admissionLedger:e.audioProbeAdmissionLedger,binding:a,device:i.device,owner:o.owner,fence:c,...u,throwIfCanceled:e.throwIfCanceled});let d=a.read();if(!d)throw TypeError(`Audio probe adoption did not publish a live handle`);return{ok:!0,data:await d.handle.status()}}async function hc(e,t){let n=Zr(e.sessionStore,t),r=n.read();if(!r)return{ok:!0,data:_c()};let i=await r.handle.status();return i.state===`stopped`&&await Nn({intent:`disposal`,binding:n}),{ok:!0,data:i}}async function gc(e,t){let n=Zr(e.sessionStore,t);return n.read()?{ok:!0,data:await Nn({intent:`capture`,binding:n})}:{ok:!0,data:_c()}}function _c(){return yi({state:`stopped`,source:`system-audio`,backend:`host-system-audio`,durationMs:0,bucketMs:0,sourceCount:0,reason:`not-started`,notes:[`No active host audio probe is running.`]})}async function vc(e){let t=e.sessionStore.lookup(e.sessionName);if(!t)return f(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let n=e.sessionStore.requireCurrent(t),r={...e,ref:t};try{if(yn(e.req.positionals?.[0]))throw new a(`INVALID_ARGS`,bn);Rc(e.req);let t=Bn({positionals:e.req.positionals,kind:Bc(e.req.flags?.kind),outPath:Bc(e.req.flags?.out)}),i=zn(t);if(i.kind===`capture-stop`)return yc(r,await Cc(r,n,i.request));let o=await ai({device:n.device,plan:i,inspectFacts:e.inspectFacts});return o.admitted?yc(r,await bc(r,n,o)):U(`perf`,o.fact)??f(`UNSUPPORTED_OPERATION`,`perf is not supported on this device`)}catch(e){return{ok:!1,error:m(e)}}}function yc(e,t){return t.ok&&I(e.sessionStore,e.ref,e.req,`perf`,C(t.data)?{...t.data}:{}),t}async function bc(e,t,n){let{device:r,plan:i}=ii(n),o=W(e.bindDevice);switch(i.kind){case`frames`:return{ok:!0,data:kc(t,await(await o(r,i.use)).operations.perfFrames({appId:t.appBundleId}))};case`memory-sample`:return{ok:!0,data:Pc(t,await(await o(r,i.use)).operations.perfMemorySample({appId:t.appBundleId}))};case`memory-snapshot`:return{ok:!0,data:Fc(t,await(await o(r,i.use)).operations.perfMemorySnapshot({appId:t.appBundleId,kind:i.request.kind,outPath:i.request.outPath?z(i.request.outPath,e.req.meta?.cwd??e.host.cwd):void 0,artifactsDir:q.join(e.sessionStore.ensureSessionDir(e.sessionName),`artifacts`)}))};case`capture-start`:return await xc(e,t,await o(r,i.use),i.request);case`profile-report`:{let n=await o(r,i.use),s=t.lastPerfProfile,c=i.request.tracePath??s?.outPath;if(!c)throw new a(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`);if(t.perfCapture)throw new a(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let l=Lc(e,i.request.outPath,`cpu-report.json`);return{ok:!0,data:{perf:`reported`,...await n.operations.perfProfileReport({appId:t.appBundleId,kind:i.request.kind,tracePath:z(c,e.req.meta?.cwd??e.host.cwd),outPath:l,template:i.request.template??(s?.kind===`xctrace`?s.template:void 0),profile:s})}}}}}async function xc(e,t,n,r){if(t.perfCapture)return f(`INVALID_ARGS`,`native perf capture already in progress`);if(!t.appBundleId)return f(`COMMAND_FAILED`,`No app is associated with this session.`,{hint:`Run open <app> first so perf can resolve the app process identity.`});let i=r.kind===`xctrace`?`perf-${r.area===`cpu`?`cpu-profile`:`trace`}.trace`:r.kind===`perfetto`?`app.perfetto-trace`:`cpu.perf.data`,a=Lc(e,r.outPath,i),o=In.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),s=In.createNextFence({admissionLedger:Sc(e),resourcePath:o,device:t.device}),c=Xr(e.sessionStore,e.ref);c.assertAdoptable();let l=await n.operations.perfNativeCaptureStart({sessionId:e.sessionName,appId:t.appBundleId,mode:r.area===`cpu`?`cpu-profile`:`trace`,kind:r.kind,template:r.template,outPath:a,fence:s});return await Vn({admissionLedger:Sc(e),binding:c,device:t.device,owner:n.owner,fence:s,pendingHandle:l.pendingHandle,envelope:l.envelope,throwIfCanceled:e.throwIfCanceled}),{ok:!0,data:l.response}}function Sc(e){if(e.perfCaptureAdmissionLedger)return e.perfCaptureAdmissionLedger;throw new a(`COMMAND_FAILED`,`Perf capture admission ledger is not configured`,{reason:`runtime-gateway-missing`})}async function Cc(e,t,n){let r=t.perfCapture;if(!r)return f(`INVALID_ARGS`,`no active native perf capture`);let i=Oc(r.handle.inspect(),n);if(i)return f(`INVALID_ARGS`,i);n.outPath&&r.handle.setOutputPath(z(n.outPath,e.req.meta?.cwd??e.host.cwd));let a=await Fn({intent:`capture`,binding:Xr(e.sessionStore,e.ref)});if(n.area===`cpu`){let t=wc(a);e.sessionStore.update(e.ref,{lastPerfProfile:t})}return{ok:!0,data:a}}function wc(e){if(Tc(e)||Ec(e))return e;throw new a(`COMMAND_FAILED`,`Stopped CPU profile metadata is malformed.`)}function Tc(e){return e.kind===`xctrace`&&e.mode===`cpu-profile`&&typeof e.outPath==`string`&&typeof e.template==`string`}function Ec(e){return e.kind===`simpleperf`&&e.mode===`cpu-profile`&&Dc(e,[`outPath`,`packageName`,`appPid`,`profilerPid`,`remotePath`])}function Dc(e,t){return t.every(t=>typeof e[t]==`string`)}function Oc(e,t){let n=t.area===`cpu`?`cpu-profile`:`trace`;if(e.kind!==t.kind||e.mode!==n)return`No ${t.kind} ${n} is active for this session.`}function kc(e,t){return{...Ic(e),metrics:{fps:Ac(t.metric,e)},sampling:{fps:t.sampling}}}function Ac(e,t){if(!C(e)||e.available!==!0)return e;let n=jc(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function jc(e,t){let n=Mc(t.windowStartedAt),r=Mc(t.windowEndedAt)??Mc(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(({ts:e})=>e>=n&&e<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:Nc(e)})).slice(-12)}function Mc(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Nc(e){for(let t of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=e.result?.[t];if(typeof n==`string`&&n.length>0)return n}}function Pc(e,t){return{...Ic(e),metrics:{memory:t.metric},sampling:{memory:t.sampling}}}function Fc(e,t){return{...Ic(e),artifact:t.artifact,sampling:{snapshot:t.sampling},support:t.support}}function Ic(e){return{session:e.name,platform:M(e.device),device:e.device.name,deviceId:e.device.id}}function Lc(e,t,n){return t?z(t,e.req.meta?.cwd??e.host.cwd):q.join(e.sessionStore.ensureSessionDir(e.sessionName),`${zc()}-${n}`)}function Rc(e){let t=e.positionals?.[0]?.toLowerCase(),n=e.positionals?.[1]?.toLowerCase();if(e.flags?.out&&t!==`cpu`&&t!==`trace`&&(t!==`memory`||n!==`snapshot`))throw new a(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}function zc(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function Bc(e){return typeof e==`string`&&e.length>0?e:void 0}const Vc=[`dump`,`log`],Hc=`network requires ${Vc.join(` or `)}`,Uc=`network include mode must be one of: ${u.join(`, `)}`,Wc=2048;async function Gc(e){let t=e.sessionStore.get(e.sessionName);if(!t)return f(`SESSION_NOT_FOUND`,`network requires an active session`);try{let n=Kc(e.bindDevice),r=(await n(t.device,we)).facts.networkDump;if(!r.available)return Zc(r.hint);let i=qc(e.req);if(!i.ok)return i;let a=nt({action:i.action,include:i.include}),o=await n(t.device,a.use),s=t.appLog?.handle.inspect();return Qc(await o.operations.networkDump({sessionId:e.sessionName,appBundleId:t.appBundleId,...s?{appLogSnapshot:{state:s.state,startedAt:s.startedAt}}:{},maxEntries:i.maxEntries,include:a.include,maxPayloadChars:Wc,maxScanLines:4e3}),i,!!t.appLog,s?.state)}catch(e){return{ok:!1,error:m(e)}}}function Kc(e){if(e)return e;throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`})}function qc(e){let t=Jc(e);if(!t.ok)return t;let n=Yc(e);if(!n.ok)return n;let r=Xc(e);return r.ok?{ok:!0,action:t.action,include:r.include,maxEntries:n.maxEntries}:r}function Jc(e){let t=(e.positionals?.[0]??`dump`).toLowerCase();return Vc.includes(t)?{ok:!0,action:t}:f(`INVALID_ARGS`,Hc)}function Yc(e){let t=e.positionals?.[1]?Number.parseInt(e.positionals[1],10):25;return!Number.isInteger(t)||t<1||t>200?f(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`):{ok:!0,maxEntries:t}}function Xc(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return f(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return u.includes(r)?{ok:!0,include:r}:f(`INVALID_ARGS`,Uc)}function Zc(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`network is not supported on this device`,hint:e}}}function Qc(e,t,n,r){return e.source===`app-log`?{ok:!0,data:{...e.dump,active:n,state:r??`inactive`,backend:e.backend,notes:e.notes}}:{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:Wc,maxScanLines:e.entries.length},notes:e.notes}}}function $c(e,t){let n=di(e);return{...n,backend:n.backend??t,notes:n.state===`failed`&&e.appLogFailure?[el(e.appLogFailure)]:tl(n.state)}}function el(e){return e.hint?`${e.message} ${e.hint}`:e.message}function tl(e){return e===`failed`?[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`]:e===`ended`?[`The app log stream process ended. Run logs clear --restart before the next capture window.`]:void 0}function nl(e,t){return pt([...e,...t.notes??[]])}async function rl(e){let{req:t}=e;return t.command===`perf`?await vc({...e,throwIfCanceled:e.throwIfCanceled??(()=>{})}):t.command===`logs`?al(e):t.command===`events`?await il(e):t.command===`network`?await Gc(e):t.command===`audio`?await uc(_l(e)):null}async function il(e){let{req:t,sessionName:n,sessionStore:r}=e;try{return await r.flushEvents(n),{ok:!0,data:r.readEvents(n,{limit:t.positionals?.[0],cursor:t.positionals?.[1]})}}catch(e){return{ok:!1,error:m(e)}}}async function al(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n);if(!i)return f(`SESSION_NOT_FOUND`,`logs requires an active session`);try{let n=r.requireCurrent(i),a=vl({...e,session:n,ref:i}),o=(await a.bindDevice(n.device,Oe)).facts.appLogInspect;if(!o.available)return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`logs is not supported on this device`,hint:o.hint}};let s=cl(Ae({action:t.positionals?.[0],restart:!!t.flags?.restart,marker:t.positionals?.slice(1).join(` `)}),n);return`ok`in s?s:await ol(a,s)}catch(e){return{ok:!1,error:m(e)}}}async function ol(e,t){switch(t.kind){case`path`:return ll(e,(await(await e.bindDevice(e.session.device,t.use)).operations.appLogInspect()).backend);case`doctor`:return ul(e,await(await e.bindDevice(e.session.device,t.use)).operations.appLogDoctor({appBundleId:e.session.appBundleId}));case`start`:case`clear-restart`:return await sl(e,t);case`stop`:return await e.bindDevice(e.session.device,t.use),await hl(e);case`mark`:return await e.bindDevice(e.session.device,t.use),dl(t.marker,e.sessionName,e.sessionStore,e.host.env);case`clear`:return await e.bindDevice(e.session.device,t.use),fl(e)}}async function sl(e,t){let n=await e.bindDevice(e.session.device,t.use);return t.kind===`start`?await ml(e,t.appBundleId,n.owner,n.operations.appLogStart):await pl(e,t.appBundleId,n.owner,n.operations.appLogStart)}function cl(e,t){return e.requiresAppSession?t.appBundleId?Object.freeze({...e,appBundleId:t.appBundleId}):f(`INVALID_ARGS`,`logs ${e.kind===`start`?`start`:`clear --restart`} requires an app session; run open <app> first`):e}function ll(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=ui(a),s=$c(n,t);return{ok:!0,data:{path:a,active:s.active,state:s.state,backend:s.backend,sizeBytes:o.sizeBytes,modifiedAt:o.modifiedAt,startedAt:s.startedAt?new Date(s.startedAt).toISOString():void 0,failureCode:s.failureCode,failureMessage:s.failureMessage,hint:s.hint??String.raw`Grep the file for token-efficient debugging, e.g. grep -n "Error\|Exception" <path>`,notes:s.notes}}}async function ul(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=$c(n,t.backend);return{ok:!0,data:{path:a,active:o.active,state:o.state,backend:o.backend,checks:t.checks,failureCode:o.failureCode,failureMessage:o.failureMessage,hint:o.hint,notes:nl(t.notes,o)}}}function dl(e,t,n,r){let i=n.resolveAppLogPath(t);return ci(i,e,r),{ok:!0,data:{path:i,marked:!0}}}function fl(e){return{ok:!0,data:li(e)}}async function pl(e,t,n,r){let{session:i,sessionStore:a}=e;i.appLog&&await si({intent:`disposal`,ref:e.ref,sessionStore:a});let o=li(e),s=await gl(e,t,r,n);return s.ok?{ok:!0,data:{...o,restarted:!0}}:s}async function ml(e,t,n,r){let{session:i}=e;return i.appLog?f(`INVALID_ARGS`,`app log already streaming; run logs stop first`):await gl(e,t,r,n)}async function hl(e){let{session:t,sessionName:n,sessionStore:r}=e;if(!t.appLog)return f(`INVALID_ARGS`,`no app log stream active`);let i=r.resolveAppLogPath(n);return await si({intent:`capture`,ref:e.ref,sessionStore:r}),{ok:!0,data:{path:i,stopped:!0}}}async function gl(e,t,n,r){let{session:i,sessionName:a,sessionStore:o}=e,s=o.resolveAppLogPath(a),c=Pn.resolvePath(o.resolveSessionDir(a));try{let l=lc({ledger:e.appLogAdmissionLedger,resourcePath:c,device:i.device});fi(o,e.ref).assertAdoptable();let u=await n({sessionId:a,appBundleId:t,outputPath:s,pidPath:o.resolveAppLogPidPath(a),fence:l});return await mi({admissionLedger:e.appLogAdmissionLedger,ref:e.ref,sessionStore:o,device:i.device,owner:r,fence:l,pendingHandle:u.pendingHandle,envelope:u.envelope,throwIfCanceled:e.throwIfCanceled??(()=>{})}),{ok:!0,data:{path:s,started:!0}}}catch(t){return{ok:!1,error:pi({ref:e.ref,sessionStore:o,error:t})}}}function _l(e){if(!e.bindDevice||!e.inspectFacts)throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.audioProbeAdmissionLedger)throw new a(`COMMAND_FAILED`,`Audio probe admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{req:e.req,sessionName:e.sessionName,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,audioProbeAdmissionLedger:e.audioProbeAdmissionLedger,throwIfCanceled:e.throwIfCanceled??(()=>{})}}function vl(e){if(!e.bindDevice)throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.appLogAdmissionLedger)throw new a(`COMMAND_FAILED`,`App-log admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{...e,bindDevice:e.bindDevice,platformServices:e.platformServices,appLogAdmissionLedger:e.appLogAdmissionLedger}}const yl=new WeakMap;function bl(e){return{store:t=>xl(e,t),finalize:(t,n)=>Sl({...e,evidence:t,projection:n})}}function xl(e,t){let{sessionStore:n,ref:r}=e;if(!r)throw Error(`Internal observation session is no longer available.`);let i=n.requireCurrent(r);ei(i,t);let a=i.snapshotGeneration;if(a===void 0)throw Error(`Internal observation did not establish a snapshot generation.`);let o={};return yl.set(o,{ref:r,snapshot:t,snapshotGeneration:a,runtimeRevision:or(i),refFrame:nr(i)}),{evidence:o,refsGeneration:a}}function Sl(e){let t=yl.get(e.evidence);yl.delete(e.evidence);let n=wl(e.projection.refs);if(n.size===0)return{published:!1,reason:`empty`};if(e.signal?.aborted===!0)return{published:!1,reason:`cancelled`};let r=t&&Cl(e,t);return!t||!r?{published:!1,reason:`stale-capture`}:e.projection.refsGeneration!==t.snapshotGeneration||!Tl(n,t.snapshot)?{published:!1,reason:`invalid-projection`}:($r(r,n),{published:!0,refsGeneration:t.snapshotGeneration,refCount:n.size})}function Cl(e,t){if(!e.ref||e.ref.lifetime!==t.ref.lifetime)return;let n=e.sessionStore.resolveCurrent(e.ref);return n&&n.snapshot===t.snapshot&&n.snapshotGeneration===t.snapshotGeneration&&or(n)===t.runtimeRevision&&nr(n)===t.refFrame?n:void 0}function wl(e){let t=new Set;for(let n of e){let e=n.startsWith(`@`)?n.slice(1):n,r=e.indexOf(`~`),i=r===-1?e:e.slice(0,r);i.length>0&&t.add(i)}return t}function Tl(e,t){let n=new Set(t.nodes.flatMap(e=>typeof e.ref==`string`?[e.ref]:[]));return[...e].every(e=>n.has(e))}function El(e){let t=Dl(e),n=Ue(t);return zi(`sha256`).update(n,`utf8`).digest(`hex`)}function Dl(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>Ol(e,n[t]??null,r?.[t]??null))}}function Ol(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,targetEvidences:e.targetEvidences??null,source:{path:n,line:t}}}function kl(e,t,n){let{from:r,digest:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e;if(r===void 0&&i===void 0)return{ok:!0,value:0};if(r===void 0||i===void 0)return{ok:!1,message:`replay --from requires --plan-digest (and --plan-digest requires --from).`};let s=Al({from:r,digest:i,planDigest:n,actionCount:t,pendingRecordAndHeal:a,sessionActionsLength:o});return s?{ok:!1,message:s}:{ok:!0,value:r-1}}function Al(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>jl({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>Ml({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>Nl(n,r)];for(let e of s){let t=e();if(t)return t}}function jl(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function Ml(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(n?.expectedFrom===t&&r===n.actionsCountAtDivergence)return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function Nl(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function Pl(e,t){let n=e.trimStart()[0];if(n===`{`||n===`[`)throw new a(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let r=O(e),i=re(e),o=El({actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:{platform:t?.platform??A(r.actions)??i.platform,target:t?.target??i.target}}),s=r.actions.length;return{actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:i,planDigest:o,resolveEntryIndex:e=>kl(e,s,o)}}function Fl(e){let{recorded:t,isSelectorWait:n}=e;return n?t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`deferred-landmark`,landmark:t}:{kind:`skip`}}function Il(e){let{recorded:t,token:n}=e;return n===void 0||!n.startsWith(`@`)&&Ie(`positional`,[n]).kind!==`expression`?{kind:`skip`}:t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`verify`,token:n}}function Ll(e,t){if(!(!e||!t)&&(e.documentOrder!==t.documentOrder||e.sibling!==t.sibling))return`position: recorded=doc${e.documentOrder}/sibling${e.sibling} observed=doc${t.documentOrder}/sibling${t.sibling}`}function Rl(e,t,n){let{observed:r,expectedStructural:i,observedStructural:a}=t,o=Ll(i,a);return{matchCount:n,observed:r,mismatches:[...r?Xe(e,r):[],...o?[o]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}}function zl(e,t){let{matchCount:n,observed:r,observedAncestry:i}=t;return{matchCount:n,observed:r,mismatches:r?[...Xe(e,r),...tt(e.ancestry,i)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}}async function Bl(e,t,n,r,i,a){if(n.targetEvidences)return Vl(e,t,n,r,i,a);let o=n.targetEvidence;if(!o)return Z(e,n,r,i,a);let s=e.beginTargetVerification(n,r,i);if(s.kind===`inactive`)return Z(e,n,r,i,a);if(s.kind===`post-resolution`){let c=Fl({recorded:o,isSelectorWait:s.isSelectorWait});switch(c.kind){case`skip`:return Z(e,n,r,i,a);case`recorded-unverifiable`:return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};case`deferred-landmark`:return Ul(e,t,n,r,i,a,{kind:`landmark`,landmark:c.landmark})}}let c=Il({recorded:o,token:s.token});if(c.kind===`skip`)return Z(e,n,r,i,a);if(c.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};let l=c.token,u=await e.observeTarget({action:n,index:i,token:l});if(u.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,Hl(u),a,t)};let{classification:d}=u;return d.verified?Ul(e,t,n,r,i,a,{kind:`target`,guard:d.guard}):{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,{kind:d.kind,matchCount:d.matchCount,observed:d.observed,candidateNodes:d.candidateNodes,mismatches:d.mismatches,causeCode:d.causeCode,causeMessage:d.causeMessage},a,t)}}async function Vl(e,t,n,r,i,a){let o=n.targetEvidences,s={};for(let c of[`source`,`destination`]){let l={...n,targetEvidence:o[c]},u=e.beginTargetVerification(l,r,i,c);if(u.kind!==`pre-dispatch`)return Z(e,n,r,i,a);let d=Il({recorded:o[c],token:u.token});if(d.kind===`skip`)return Z(e,n,r,i,a);if(d.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(l,i,a,t)};let f=await e.observeTarget({action:l,index:i,token:d.token});if(f.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,Hl(f),a,t)};let{classification:p}=f;if(!p.verified)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,{kind:p.kind,matchCount:p.matchCount,observed:p.observed,candidateNodes:p.candidateNodes,mismatches:p.mismatches,causeCode:p.causeCode,causeMessage:p.causeMessage},a,t)};s[c]=p.guard}return Ul(e,t,n,r,i,a,{kind:`targets`,guards:{source:s.source,destination:s.destination}})}function Hl(e){return{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${e.reason}).`,...e.hint===void 0?{}:{causeHint:e.hint}}}async function Z(e,t,n,r,i){let a=await e.dispatchStep(t,n,r,i,void 0);switch(a.status){case`ok`:return{status:`ok`,artifactPaths:a.artifactPaths};case`failed`:return{status:`failed`,failure:a.failure};case`guard-mismatch`:case`landmark-mismatch`:return{status:`failed`,failure:a.plainFailure}}}async function Ul(e,t,n,r,i,a,o){let s=await e.dispatchStep(n,r,i,a,o);if(s.status===`ok`)return{status:`ok`,artifactPaths:s.artifactPaths};if(s.status===`failed`)return{status:`failed`,failure:s.failure};let c=Wl(n,o,s);if(!c)return{status:`failed`,failure:s.plainFailure};let l=Gl(c.recorded,c.matchCount,s);return{status:`failed`,failure:await e.buildPostDispatchTargetBindingFailure(c.reportAction,i,{kind:`identity-mismatch`,matchCount:l.matchCount,observed:l.observed,candidateNodes:[],mismatches:l.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:l.causeMessage},a,t)}}function Wl(e,t,n){if(n.status!==`guard-mismatch`||t.kind!==`targets`)return e.targetEvidence?{recorded:e.targetEvidence,reportAction:e,matchCount:t.kind===`target`?t.guard.matchCount:0}:void 0;let r=n.evidence.targetRole??`source`,i=e.targetEvidences?.[r];return i?{recorded:i,reportAction:{...e,targetEvidence:i},matchCount:t.guards[r].matchCount}:void 0}function Gl(e,t,n){return n.status===`guard-mismatch`?Rl(e,n.evidence,t):zl(e,n.evidence)}async function Kl(e,t){let{actions:n,entryIndex:r,keepSession:i}=e,a=It(e.varSources),o=[],s=[],c=Xl(n),l=0;for(let u=r;u<n.length;u+=1){let r=n[u];if(!Yl(r)||(t.armStep(),u===c&&(i||t.isRepairArmed())))continue;if(l+=1,t.onStep){let e=t.describeStepValue(r);t.onStep(Zl(u,n.length,r,e))}let d=Ft(r,a,Jl(e,u)),f=Mt(a),p=t.diagnosticsMarker(),m=await Bl(t,f,r,d,u,o);if(s.push(...t.diagnosticsSince(p)),m.status===`ok`){o=m.artifactPaths;continue}let h=await t.handleActionFailure({action:r,index:u,artifactPaths:ql(o,m.failure.artifactPaths),snapshotDiagnosticSamples:s,scrubVars:f});return{status:`failed`,stepIndex:u,failure:h}}return{status:`completed`,replayed:l,artifactPaths:[...o],snapshotDiagnosticSamples:s}}function ql(e,t){return t.length===0?e:[...new Set([...e,...t])]}function Jl(e,t){return{file:e.actionSourcePaths?.[t]??e.resolvedPath,line:e.actionLines[t]??1}}function Yl(e){return!!(e&&e.command!==`replay`)}function Xl(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(Yl(n))return n.command===`close`?t:void 0}}function Zl(e,t,n,r){return{index:e+1,total:t,command:n.command,...r===void 0?{}:{value:r}}}async function Ql(e){return await $l({...e,snapshotDiagnostics:w(e.snapshotDiagnosticSamples)})}async function $l(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scrubVars:l,req:u,sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,planActions:h,planDigest:g}=e;if(t.ok)return t;let _=eu(t.error.details?.replaySource),v=bi(t.error),y=await xi({error:v,action:n,index:r,sourcePath:_?.path??a,sourceLine:_?.line??o,session:f.get(),sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,responseLevel:u.meta?.responseLevel,scrubVars:l,planActions:h,planDigest:g,signal:qr(u.meta?.requestId)});return Ai({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:l})}function eu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(n!==void 0||r!==void 0)return{path:n,line:r}}async function tu(e){let{req:t,sessionName:n,action:r,resolved:i,filePath:o,line:s,step:c,sourcePath:l,tracePath:u,invoke:d,resolvedSessionScope:f,dependencies:p}=e,h=Date.now();Di(u,{type:`replay_action_start`,ts:new Date(h).toISOString(),replayPath:o,...l?{sourcePath:l}:{},line:s,step:c,command:i.command,positionals:qn(i)??[]});let g;try{g=await ru({req:t,sessionName:n,resolved:i,sourceAction:r,invoke:d,resolvedSessionScope:f,dependencies:p})}catch(e){if(!(e instanceof a))throw e;g={ok:!1,error:m(e)}}let _=Date.now();return Di(u,{type:`replay_action_stop`,ts:new Date(_).toISOString(),replayPath:o,...l?{sourcePath:l}:{},line:s,step:c,command:i.command,ok:g.ok,durationMs:_-h,resultTiming:g.ok?au(g.data):void 0,errorCode:g.ok?void 0:g.error.code}),nu(g,l??o,s)}function nu(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function ru(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:o,resolvedSessionScope:s,dependencies:c}=e,l=E(r.command,r.positionals??[],r.flags??{},`after variable substitution`);if(l)throw new a(`INVALID_ARGS`,l);let u=S(t.flags,{...r.flags??{}}),d=i.command===`fill`?Rt(Ut(i)):void 0;return d&&(u.recordAs=d),await o(iu({token:t.token,session:n,flags:u,runtime:r.runtime,meta:t.meta,dispatch:{...t.dispatch,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:s??c.resolveSessionScope(t)}:{}}},r))}function iu(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:fe(n,{pointerCount:e.flags?.pointerCount,holdMs:e.flags?.holdMs,count:e.flags?.count,pauseMs:e.flags?.pauseMs})}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:se(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function au(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function ou(e){return pu(e.ok?cu(e.data):su(e.error.details?.artifactPaths))}function su(e){return Array.isArray(e)?e.filter(fu):[]}function cu(e){return e?[du(e.path),du(e.outPath),...lu(e.artifacts)].filter(fu):[]}function lu(e){return Array.isArray(e)?e.map(uu).filter(fu):[]}function uu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return du(t.localPath)??du(t.path)}function du(e){return typeof e==`string`?e:void 0}function fu(e){return typeof e==`string`}function pu(e){return[...new Set(e.filter(mu))]}function mu(e){try{return K.statSync(e).isFile()}catch{return!1}}function hu(e){let{recorded:t,token:n,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}=e,l=gu({token:n,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}),u=Xt(i),d=at(t),f=Zt(l.matchedNodes,u,d,t.ancestry),p=f.filter(e=>Dt(i,e)===t.sibling),m=f.filter(e=>Et(e,u,t.scrollRegion)),h=Tt(m)[t.viewportOrder]?.ref,g=Ot({winnerRef:l.winnerRef,matchedRefs:r(l.matchedNodes),identitySetRefs:r(f),siblingMatchRefs:r(p),regionMemberRefs:r(m),viewportCandidateRef:h}),_=l.matchedNodes.find(e=>e.ref===l.winnerRef);return g.outcome===`verified`&&_?{verified:!0,winnerNode:_,matchCount:l.matchedNodes.length}:g.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:l.matchedNodes.length,observedNode:void 0,candidateNodes:f.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,...yu({classification:g,matchCount:l.matchedNodes.length,winnerNode:_,identitySet:f,byIndex:u,recorded:t})}}function gu(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?_u(n,t,i,a):vu(n,t,r,a,o)}function _u(e,t,n,r){let i=e=>e!==null&&(!r||!!e.rect),a=l(t),s=a?o(e,a):null;if(i(s)&&s.ref!==void 0)return{matchedNodes:[s],winnerRef:s.ref};let c=n?ri(e,n):null;return i(c)&&h(c)?{matchedNodes:[c],winnerRef:c.ref}:{matchedNodes:[],winnerRef:``}}function vu(e,t,n,r,i){let a=ze(t,e,{platform:n,requireRect:r,allowDisambiguation:i});if(a.kind===`resolved`&&a.winner.ref!==void 0)return{matchedNodes:[...a.matchedNodes],winnerRef:a.winner.ref};let o=Ur(e,a.matchedNodes);return{matchedNodes:[...a.matchedNodes],winnerRef:o?.ref??``}}function yu(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?bu(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?bu(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?bu(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function bu(e,t,n){let r=kt(t),i=Qt(t,n,Math.max(e.ancestry.length,1)).chain;return[...Xe(e,r),...tt(e.ancestry,i)].slice(0,5)}function xu(e,t){let n=e.positionals??[];if(e.command===`gesture`){let e=ce(n);return e?e[t??`source`]:void 0}if(e.command===`get`)return n[1];if(e.command===`is`){let e=Ie(`is`,n);return e.kind===`expression`?e.expression:void 0}if(!oe(e.command)&&e.command!==`fill`)return;let r=n[0];if(r!==void 0&&!(Cu(r)&&Cu(n[1])))return r}function Su(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function Cu(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function wu(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionStore:l,resumeStamper:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=An(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:Pu(at(n),h),...t.observed?{observed:Pu(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>Fu(e,h))},_=Ei({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=wi({failedIndex:i,actions:p,planDigest:m,repairHint:_,resumeStamper:u}),y={version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(ne(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},b=ki({sessionStore:l,observationStore:e.observationStore,divergence:y,responseLevel:d,evidence:t.publicationEvidence,...e.signal?{signal:e.signal}:{}}),x={code:t.causeCode,message:t.causeMessage};return Ai({error:x,action:r,step:i,replayPath:s,artifactPaths:c,divergence:b,scrubVars:f})}function Tu(e,t,n){let r=An(e.scrubVars);return wu(e,{kind:t.kind,matchCount:t.matchCount,observed:t.observed,candidateNodes:t.candidateNodes,mismatches:t.mismatches,causeCode:t.causeCode,causeMessage:t.causeMessage,...t.causeHint===void 0?{}:{causeHint:t.causeHint},screen:Oi(n,r),publicationEvidence:ku(n),repairCapture:Si(n)})}async function Eu(e){let{session:t,observationStore:n,logPath:r,action:i,unavailableHint:a,signal:o}=e;return t?await Ti({session:t,observationStore:n,logPath:r,action:i,signal:o}):{state:`unavailable`,reason:`no-session`,hint:a}}async function Du(e,t){return Tu(e,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`},await Eu({...t,signal:e.signal,unavailableHint:`The session closed before a screen could be captured to verify the recorded target evidence.`}))}async function Ou(e,t,n){return Tu(e,t,await Eu({...n,signal:e.signal,unavailableHint:`The session closed before a post-failure screen could be captured.`}))}function ku(e){return e.state===`available`?e.evidence:void 0}function Au(e){let{action:t,resolvedAction:n,sessionStore:r,targetRole:i}=e,a=r.get();return a?We(t.command)===`post-resolution`?{kind:`post-resolution`,isSelectorWait:He(n.positionals??[])?.kind===`selector`}:{kind:`pre-dispatch`,token:xu(n,i),platform:a.device.platform}:{kind:`inactive`}}function ju(e){let{recorded:t,token:n,action:r,nodes:i,platform:a}=e,o=Mi(r),s=hu({recorded:t,token:n,nodes:i,platform:a,refLabel:Su(r),requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});return s.verified?{verified:!0,guard:{expected:{identity:kt(s.winnerNode),structural:Qe(s.winnerNode,i)},matchCount:s.matchCount}}:{verified:!1,kind:s.kind,matchCount:s.matchCount,observed:s.observedNode?kt(s.observedNode):void 0,candidateNodes:s.candidateNodes,mismatches:s.mismatches,causeCode:s.causeCode,causeMessage:s.causeMessage}}function Mu(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}function Nu(e){return!e.ok&&e.error.details?.reason===Ni}function Pu(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function Fu(e,n){let r=t(e.type??`Element`),i=de(e,r);return{...e.ref?{ref:e.ref}:{},role:n(r),...i?{label:n(i)}:{}}}function Iu(e,t){let n=t?.kind===`target`?{replayTargetGuard:t.guard.expected}:t?.kind===`targets`?{replayTargetGuards:{source:t.guards.source.expected,destination:t.guards.destination.expected}}:t?.kind===`landmark`?{replayLandmarkGuard:t.landmark}:void 0;return n?{...e,dispatch:{...e.dispatch,...n}}:e}function Lu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function Ru(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function zu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.documentOrder==`number`&&typeof t.sibling==`number`)return{documentOrder:t.documentOrder,sibling:t.sibling}}function Bu(e){return{...e?.targetRole===`source`||e?.targetRole===`destination`?{targetRole:e.targetRole}:{},observed:Lu(e?.observed),expectedStructural:zu(e?.expectedStructural),observedStructural:zu(e?.observedStructural)}}function Vu(e){return{matchCount:typeof e?.matchCount==`number`?e.matchCount:void 0,observed:Lu(e?.observed),observedAncestry:Ru(e?.observedAncestry)}}function Hu(e,t){return{kind:e.error.code,message:e.error.message,artifactPaths:t}}function Uu(e,t,n){let r=Hu(e,n);return(t?.kind===`target`||t?.kind===`targets`)&&Mu(e)?{status:`guard-mismatch`,evidence:Bu(e.error.details),plainFailure:r,artifactPaths:n}:t?.kind===`landmark`&&Nu(e)?{status:`landmark-mismatch`,evidence:Vu(e.error.details),plainFailure:r,artifactPaths:n}:{status:`failed`,failure:r}}function Wu(e){let{ctx:t,req:n,artifactPaths:r,onStep:i,armSaveScript:a}=e,o,s,c=(e,n,r,i)=>({recorded:e.targetEvidence,action:e,step:n+1,sourcePath:t.actionSourcePaths?.[n]??t.resolved,sourceLine:t.actionLines[n]??1,replayPath:t.resolved,artifactPaths:[...r],sessionStore:t.sessionStore,observationStore:t.observationStore,resumeStamper:t.coordinator.resumeStamper,responseLevel:t.responseLevel,scrubVars:i,planActions:t.actions,planDigest:t.planDigest,signal:t.signal}),l=e=>(o=e,Hu(Gu(e),ou(e))),u=async e=>{let n=t.observationStore.get();return n?await Ti({session:n,observationStore:t.observationStore,logPath:t.logPath,action:e,retryLaunchRace:!0,signal:t.signal}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a screen could be captured to verify the recorded target.`}};return{runtime:{beginTargetVerification(e,n,r,i){return Au({action:e,resolvedAction:n,sessionStore:t.sessionStore,targetRole:i})},async observeTarget({action:e,token:n}){let r=await u(e);if(s=r,r.state!==`available`)return{state:`unavailable`,reason:r.reason,hint:r.hint};let i=t.sessionStore.get();return{state:`classified`,classification:ju({recorded:e.targetEvidence,token:n,action:e,nodes:[...r.nodes],platform:i.device.platform})}},async dispatchStep(e,n,i,a,s){let c=t.actionLines[i]??1,l=await tu({req:Iu(t.replayReq,s),sessionName:t.sessionName,action:e,resolved:n,filePath:t.resolved,line:c,sourcePath:t.actionSourcePaths?.[i],step:i+1,tracePath:t.actionTracePath,invoke:t.invoke,resolvedSessionScope:t.resolvedSessionScope,dependencies:t.dependencies});o=l,ou(l).forEach(e=>r.add(e));let u=[...r];return l.ok?{status:`ok`,artifactPaths:u}:Uu(l,s,u)},async buildRecordedUnverifiableFailure(e,n,r,i){let a=await Du(c(e,n,r,i),{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(a)},async buildTargetBindingFailure(e,t,n,r,i){let a=s??{state:`unavailable`,reason:`observation-missing`,hint:`No capture was recorded before this target-binding failure.`},o=Tu(c(e,t,r,i),n,a);return l(o)},async buildPostDispatchTargetBindingFailure(e,n,r,i,a){let o=await Ou(c(e,n,i,a),r,{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(o)},async handleActionFailure({action:e,index:r,artifactPaths:i,snapshotDiagnosticSamples:a,scrubVars:s}){let c=Gu(o),u=await Ku(t,n,e,r,c,[...i],[...a],s);return l(u)},armStep:()=>{s=void 0,a()},isRepairArmed:()=>t.coordinator.view()?.repairBoundary!==void 0,describeStepValue:e=>qu(e),onStep:i,diagnosticsMarker:()=>Yu(t.sessionStore),diagnosticsSince:e=>Xu(t.sessionStore,e)},readLastResponse:()=>o}}function Gu(e){return e&&!e.ok?e:f(`COMMAND_FAILED`,`replay step reported failure with no recorded response`)}async function Ku(e,t,n,r,i,a,o,s){let c=t=>e.coordinator.markSessionHeldIfArmed(t);return Ju(i)?c(i):c(await Ql({response:i,action:n,index:r,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[r]??e.resolved,sourceLine:e.actionLines[r]??1,artifactPaths:a,snapshotDiagnosticSamples:o,scrubVars:s,req:t,sessionStore:e.sessionStore,observationStore:e.observationStore,resumeStamper:e.coordinator.resumeStamper,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function qu(e){let t=e.positionals??[],n=Pe(t[0]);if(n)return n;if(t.length!==0)return t.join(` `)}function Ju(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function Yu(e){return e.get()?.snapshotDiagnostics?.samples.length??0}function Xu(e,t){return e.get()?.snapshotDiagnostics?.samples.slice(t)??[]}async function Zu(e){let{resolved:t,keepSession:n,coordinator:r,command:i}=e,{request:a}=i,o=k(t,a.flags?.replayBackend);if(o!==`ad`)return n?f(`INVALID_ARGS`,`--keep-session is supported only for native .ad replay; Maestro YAML owns its lifecycle.`):r.view()?.repairBoundary===void 0?await(await Pi(o)).runReplay(i):f(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function Qu(e){let{req:t,host:n,sessionName:r,sessionStore:i,tracePath:a,resolved:o,script:s,coordinator:c,dispatch:l}=e,u=$u(t);if(u)return{ok:!1,response:u};let{manifest:d,replayReq:f}=ed(t,s,l),{metadata:p,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_}=d,v=i.get(),y=td({req:t,coordinator:c,manifest:d,preEntrySession:v});return y.ok?{ok:!0,value:{replayReq:f,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,preEntrySession:v,entryIndex:y.value,varSources:rd({req:t,host:n,replayReq:f,sessionName:r,resolved:o,metadata:p}),actionTracePath:a??v?.trace?.outPath}}:{ok:!1,response:y.response}}function $u(e){let t=e.flags?.replayBackend;if(t&&!te(t))return f(`INVALID_ARGS`,ie(t))}function ed(e,t,n){let r=Pl(t,{platform:e.flags?.platform,target:e.flags?.target});return{manifest:r,replayReq:nd({...e,flags:Yn(e.flags,r.actions),...n?{dispatch:n}:{}},r.metadata)}}function td(e){let{req:t,coordinator:n,manifest:r,preEntrySession:i}=e,a=r.resolveEntryIndex({from:t.flags?.replayFrom,digest:t.flags?.replayPlanDigest,pendingRecordAndHeal:n.view()?.pendingRecordAndHeal,sessionActionsLength:i?.actions.length??0});return a.ok?{ok:!0,value:a.value}:{ok:!1,response:f(`INVALID_ARGS`,a.message)}}function nd(e,t){return!t.platform&&!t.target?e:{...e,flags:id(e.flags,t)}}function rd(e){let{req:t,host:n,replayReq:r,sessionName:i,resolved:a,metadata:o}=e;return{builtins:ji({req:r,sessionName:i,metadata:o,resolvedPath:a,hostCwd:n.cwd}),fileEnv:o.env,shellEnv:Pt(Nt(t.flags?.replayShellEnv,n.env)),cliEnv:jt(At(t.flags?.replayEnv))}}function id(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}const ad={kind:`none`,status:void 0,targetPath:void 0,targetForce:!1};function od(e){let{req:t,entryIndex:n,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}=e,s=sd({entryIndex:n,sessionStore:i,coordinator:o});return s?{ok:!1,response:s}:(ud({req:t,coordinator:o}),ld({req:t,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}))}function sd(e){let t=dd(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get())return d()}function cd(e){let{saveScript:t,force:n,hostCwd:r,preRunState:i,sourcePath:a}=e;return t&&i.kind===`authoring`?f(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${i.status}. Close this session and use a fresh one for repair authoring.`):fd({saveScript:t,liveForce:n,persistedForce:i.targetForce||void 0,hostCwd:r,sourcePath:a,existingSaveScriptPath:i.targetPath})}function ld(e){let{req:t,hostCwd:n,sourcePath:r,coordinator:i}=e,{saveScript:a,force:o}=t.flags??{},s=cd({saveScript:a,force:o,hostCwd:n,preRunState:i.view()?.scriptPublication??ad,sourcePath:r});return s?{ok:!1,response:s}:(i.demoteForRerunIfArmed(),{ok:!0,armSaveScript:pd({saveScript:a,force:o,coordinator:i,sourcePath:r})})}function ud(e){let{req:t,coordinator:n}=e;n.clearCorrectiveWatermarkIfExpected(t.flags?.replayFrom),t.flags?.saveScript&&n.clearTombstone()}function dd(e){let{entryIndex:t,coordinator:n}=e;if(!(t>0)&&n.view()?.repairBoundary!==void 0)return f(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function fd(e){let{saveScript:t,liveForce:n,persistedForce:r,hostCwd:i,sourcePath:a,existingSaveScriptPath:o}=e;if(!t)return;let s=typeof t==`string`?z(t,i):o??Ci(a);if(!(n||r&&s===o)&&K.existsSync(s))return f(`COMMAND_FAILED`,`A file already exists at ${s}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function pd(e){let{saveScript:t,force:n,coordinator:r,sourcePath:i}=e;if(!t)return()=>{};let a=!0;return()=>{r.armStep({saveScript:t,force:n,sourcePath:i,firstArm:a}),a=!1}}async function md(e){let{request:t,host:n,session:{name:r,logPath:i,store:a,observationStore:o,coordinator:s},tracePath:c,onStep:l,invoke:u}=e,d=t.flags?.replayScriptSource;if(!d)return f(`INVALID_ARGS`,Wn);let p=Date.now(),h=t.flags?.replayKeepSession===!0,g=``,_=new Set;try{if(g=d.entry,ue(g)&&t.flags?.replayBackend!==`maestro`)return f(`INVALID_ARGS`,le(`replay`,g));let m=await Zu({resolved:g,keepSession:h,coordinator:s,command:e});if(m)return m;let v=Qu({req:t,host:n,sessionName:r,sessionStore:a,tracePath:c,resolved:g,script:Jn(d,g),coordinator:s,dispatch:e.dispatch});if(!v.ok)return v.response;let{replayReq:y,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,entryIndex:w,varSources:ee,actionTracePath:T}=v.value,E=od({req:t,entryIndex:w,hostCwd:n.cwd,sessionStore:a,sourcePath:g,coordinator:s});if(!E.ok)return E.response;let{runtime:te,readLastResponse:D}=Wu({ctx:{replayReq:y,sessionName:r,sessionStore:a,observationStore:o,logPath:i,resolved:g,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,actionTracePath:T,responseLevel:t.meta?.responseLevel,invoke:u,signal:qr(t.meta?.requestId),coordinator:s,resolvedSessionScope:e.resolvedSessionScope,dependencies:e.dependencies},req:t,artifactPaths:_,onStep:l,armSaveScript:E.armSaveScript}),O=await Kl({actions:b,entryIndex:w,keepSession:h,actionLines:x,actionSourcePaths:S,resolvedPath:g,varSources:ee},te);return O.status===`failed`?D()??f(`COMMAND_FAILED`,`replay step failed with no recorded response`):hd({startedAt:p,sessionName:r,sessionStore:a,replayed:O.replayed,artifactPaths:O.artifactPaths,snapshotDiagnosticSamples:O.snapshotDiagnosticSamples,armSaveScript:E.armSaveScript,coordinator:s,keepSession:h})}catch(e){let t=m(e);return _.size===0?{ok:!1,error:t}:{ok:!1,error:{...t,details:{...t.details,artifactPaths:[..._]}}}}}function hd(e){let{startedAt:t,sessionName:n,sessionStore:r,replayed:i,artifactPaths:a,snapshotDiagnosticSamples:o,armSaveScript:s,coordinator:c,keepSession:l}=e;s(),c.markCompleteIfArmed();let u=r.get(),d=_d({keepSession:l,sessionName:n,completedSession:u,artifactPaths:a});if(d)return d;let f=w([...o]);return{ok:!0,data:{replayed:i,healed:0,session:n,sessionActive:u!==void 0,artifactPaths:[...a],...f?{snapshotDiagnostics:f}:{},message:gd(i,Date.now()-t)}}}function gd(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function _d(e){let{keepSession:t,sessionName:n,completedSession:r,artifactPaths:i}=e;if(!(!t||r))return f(`COMMAND_FAILED`,`Replay completed but --keep-session could not preserve session "${n}". Run the script again after checking which action closed the session.`,i.length>0?{artifactPaths:[...i]}:void 0)}function vd(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=q.resolve(n??`.`,t??`.agent-device/test-artifacts`);return q.join(i,r)}function yd(e,t){let n=t?q.relative(t,e):q.basename(e),r=n.length===0||n.startsWith(`..`)?q.basename(e):n;return De(r.toLowerCase().replaceAll(/[\\/]+/g,`__`).replaceAll(/[^a-z0-9._-]+/g,`-`))||`test`}function bd(e,t){K.mkdirSync(t,{recursive:!0}),Cd(e,t)}function xd(e){let{outcome:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=t.status===`passed`,c=new Set(t.artifactPaths);t.status===`failed`&&typeof t.error.logPath==`string`&&c.add(t.error.logPath);let l=q.join(o,`result.txt`),u=q.join(o,`failure.txt`),d=Sd([...c],o,[l,u]),f=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${s?`passed`:`failed`}`];t.status===`passed`?f.push(`replayed: ${t.replayed}`,`healed: ${t.healed}`):(f.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&f.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&f.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&f.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&f.push(`timeoutMode: cooperative`)),d.length>0&&f.push(`copiedArtifacts: ${d.map(e=>q.basename(e)).join(`, `)}`);let p=`${f.join(`
2
+ `)}\n`;K.writeFileSync(l,p),s||K.writeFileSync(u,p)}function Sd(e,t,n){let r=[],i=new Set(n.map(e=>q.basename(e).toLowerCase()));for(let n of e){if(!Td(n))continue;let e=q.basename(n);if(q.resolve(n)===q.resolve(t,e)&&!i.has(e.toLowerCase())){r.push(n);continue}let a=wd(e,t,i),o=q.join(t,a);K.copyFileSync(n,o),r.push(o)}return r}function Cd(e,t){let n=q.join(t,`replay.ad`);if(K.copyFileSync(e,n),q.extname(e).toLowerCase()===`.ad`)return;let r=q.join(t,q.basename(e));q.resolve(r)!==q.resolve(n)&&K.copyFileSync(e,r)}function wd(e,t,n){let r=q.extname(e),i=r?e.slice(0,-r.length):e,a=e,o=2;for(;n.has(a.toLowerCase())||K.existsSync(q.join(t,a));)a=`${i}-${o++}${r}`;return a}function Td(e){try{return K.statSync(e).isFile()}catch{return!1}}function Ed(e){let{platformFilter:t,discoverSources:n}=e,r=n(),i=[],o={undeclared:0,declaredOther:0};for(let e of r){let{path:n,manifest:r}=e,a={kind:`run`,path:n,title:r.title,manifest:r};if(!t){i.push(a);continue}let s=r.device.platform;if(s.kind===`caller-bound`){i.push(a);continue}if(s.kind===`unspecified`){o.undeclared+=1,i.push({kind:`skip`,path:n,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${t}`});continue}if(!Id(t,s.value)){o.declaredOther+=1;continue}i.push(a)}if(i.filter(e=>e.kind===`run`).length===0)throw new a(`INVALID_ARGS`,kd({platformFilter:t,...o}));return i}const Dd={web:!0};function Od(e){return!Object.hasOwn(Dd,e)}function kd(e){let{platformFilter:t,undeclared:n,declaredOther:r}=e,i=t?` for --platform ${t}`:``;return t===void 0||n===0&&r===0?`No replay tests matched${i}.`:`No replay tests matched${i}: ${[...n>0?[`${n} without a platform declaration`]:[],...r>0?[`${r} declaring another platform`]:[]].join(`, `)}. ${Ad(t,n)}`}function Ad(e,t){return Od(e)?t>0?`Add "context platform=${e}" to the first line of a script that has none, or drop --platform when the device is already selected.`:`Run a source that declares ${e}, or drop --platform.`:`No script can declare ${e} as its platform; run this suite without --platform.`}function jd(e,t,n,r,i=0){let a=q.basename(n,q.extname(n)),o=De(a.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`));return`${e}:test:${t}:${r+1}${o?`-${o}`:``}:attempt-${i+1}`}function Md(e){let t=e?.trim()||`${process.pid}-${Date.now().toString(36)}`;return De(t.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`))||`suite`}function Nd(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e;return[t??n,...o===void 0?[]:[`shard`,o+1],`test`,i+1,q.basename(r),`attempt`,a+1].join(`:`)}function Pd(e,t){return typeof e==`number`?e:t}function Fd(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function Id(e,t){return e===`apple`?P(t):t===e}function Ld(e){return{status:`failed`,error:e.error,artifactPaths:e.artifactPaths??[],warnings:e.warnings??[],infrastructure:e.infrastructure??!1,...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}const Rd=2e3;async function zd(e){let{filePath:t,sessionName:n,requestId:r,parentRequestId:i,timeoutMs:a,platform:o,target:s,artifactsDir:c,shard:l,onStep:u,runReplay:d,cleanupSession:f,finalizeAttempt:p,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=g({attemptId:r,parentAttemptId:i}),v=new Set,y,b=!1,x,S=Date.now(),C=Kd({artifactsDir:c,artifactPaths:v,filePath:t,sessionName:n,requestId:r,timeoutMs:a,platform:o,target:s}),w=d({filePath:t,sessionName:n,platform:o,target:s,requestId:r,artifactsDir:c,artifactPaths:v,tracePath:C,appendTimingEvent:e=>Q(C,e),shard:l,onStep:u}).catch(e=>Ld({error:m(e)})).finally(()=>{_.release()});try{x=typeof a==`number`?await Promise.race([w,new Promise(e=>{y=setTimeout(()=>{b=!0,_.cancel(),e(qd(a,[...v]))},a)})]):await w,Q(C,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:n,ok:x.status===`passed`,timedOut:b,durationMs:Date.now()-S,errorCode:x.status===`passed`?void 0:x.error.code})}finally{y&&clearTimeout(y),b&&(await Vd(w)||(x=Wd(x),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:n,requestId:r,graceMs:Rd}}),Hd({replayPromise:w,cleanupSession:f,sessionName:n,requestId:r,emitDiagnostic:h})));let e=await Ud({finalizeAttempt:p,sessionName:n,artifactPaths:v,artifactsDir:c,tracePath:C,emitDiagnostic:h});x?.status===`passed`&&e&&(x=Gd(x,`Replay test finalization failed: ${e.error.message}`));let t=Date.now();try{Q(C,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:n}),await f(n),Q(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!0,durationMs:Date.now()-t})}catch(e){let r=m(e);Q(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-t,errorCode:r.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:n,error:r.message}}),x=Bd(x,r,v)}}return x??Ld({error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}})}function Bd(e,t,n){return e?.status===`failed`?{...e,infrastructure:!0}:Ld({error:t,artifactPaths:[...n],infrastructure:!0})}async function Vd(e){return await Promise.race([e.then(()=>!0),Vi(Rd).then(()=>!1)])}async function Hd(e){let{replayPromise:t,cleanupSession:n,sessionName:r,requestId:i,emitDiagnostic:a}=e;try{await t}finally{try{await n(r)}catch(e){a({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:r,requestId:i,error:m(e).message}})}}}async function Ud(e){let{finalizeAttempt:t,sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,emitDiagnostic:o}=e;if(!t)return;let s=Date.now();Q(a,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:n});try{let e=await t({sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,appendTimingEvent:e=>Q(a,e)});return Q(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:e===void 0,durationMs:Date.now()-s,errorCode:e?.error.code}),e}catch(e){let t=m(e);return Q(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-s,errorCode:t.code}),o({level:`warn`,phase:`test_finalize_failed`,data:{session:n,error:t.message}}),Ld({error:t})}}function Wd(e){return!e||e.status===`passed`?e:{...e,infrastructure:!0,error:{...e.error,details:{...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0}}}}function Gd(e,t){return{...e,warnings:[...e.warnings,t]}}function Kd(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=q.join(t,`replay-timing.ndjson`);return K.mkdirSync(q.dirname(l),{recursive:!0}),K.writeFileSync(l,``),n.add(l),Q(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function Q(e,t){e&&K.appendFileSync(e,`${JSON.stringify(t)}\n`)}function qd(e,t=[]){return Ld({artifactPaths:t,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}})}async function Jd(e){let t=Yd(e),n=await Xd(e,t);return{result:nf(e,t,n),infrastructure:n.finalOutcome?.status===`failed`&&n.finalOutcome.infrastructure}}function Yd(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:q.join(i,...a?[`shard-${a.shardIndex+1}`]:[],yd(t.path,n)),maxAttempts:r+1}}async function Xd(e,t){Qd(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!e.isCanceled();r+=1){let i=await Zd(e,t,r);if($d(n,i),ef(e,i.outcome,r))break;tf(e,t,i)}return n}async function Zd(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=jd(i,a,r.path,o,n),h=q.join(t.testArtifactsDir,`attempt-${f}`);bd(r.path,h);let g=Nd({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_={file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...cf(d)},v=await zd({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.manifest.device.platform.kind===`declared`?r.manifest.device.platform.value:void 0,target:r.manifest.device.target,artifactsDir:h,shard:d,onStep:t=>{e.emitProgress({type:`replay-test`,..._,status:`progress`,stepIndex:t.index,stepTotal:t.total,...t.command===void 0?{}:{stepCommand:t.command},...t.value===void 0?{}:{stepValue:t.value}})},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt,emitDiagnostic:e.emitDiagnostic,bindAttemptCancellation:e.bindAttemptCancellation}),y=Date.now()-p;return xd({outcome:v,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{outcome:v,sessionName:m,attempt:f,durationMs:y}}function Qd(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;e.emitProgress({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:jd(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...cf(c)})}function $d(e,t){e.finalOutcome=t.outcome,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,t.outcome.status!==`passed`&&e.attemptFailures.push({attempt:t.attempt,message:t.outcome.error.message,durationMs:t.durationMs})}function ef(e,t,n){return t.status===`passed`||e.isCanceled()||t.infrastructure||n>=e.retries}function tf(e,t,n){n.outcome.status!==`passed`&&e.emitProgress({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.outcome.error.message,hint:n.outcome.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...cf(e.shard)})}function nf(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalOutcome?.status===`passed`?rf(e,t,n,r):af(e,t,n,r)}function rf(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome;if(c?.status!==`passed`)throw Error(`Expected passing replay test outcome.`);return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...cf(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,replayed:c.replayed,healed:c.healed,...c.warnings.length>0?{warnings:[...c.warnings]}:{},...c.snapshotDiagnostics?{snapshotDiagnostics:c.snapshotDiagnostics}:{},...sf(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function af(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome,l=c?.status===`failed`?c.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`};return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:l.message,hint:l.hint,...cf(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:l,...of(c),...sf(s)}}function of(e){let t=e?.status===`failed`?e:void 0;return{...t&&t.warnings.length>0?{warnings:[...t.warnings]}:{},...t?.infrastructure?{infrastructure:!0}:{},...e?.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}function sf(e){return cf(e)}function cf(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function lf(e,t,n,r){if(!e||t.length===0)return;let i=await r(e.count);return{mode:e.kind,shardCount:e.count,total:n+(e.kind===`all`?t.length*e.count:t.length),shards:i.map((n,r)=>({shardIndex:r,shardCount:e.count,device:n,entries:e.kind===`all`?t:t.filter((t,n)=>n%e.count===r)}))}}async function uf(e){let{request:t,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l,discoverSources:u,resolveShardTargets:d}=e,f=t.sessionName;if(t.inputs.length===0)return{status:`failed`,error:{code:`INVALID_ARGS`,message:`test requires at least one path or glob`}};try{let e=Date.now(),s=await df(t,u,d);hf(s,a);let p=s.shardPlan?gf({entries:s.entries,total:s.total,emitProgress:a}):[];return s.shardPlan?p.push(...await _f({shards:s.shardPlan.shards,sessionName:f,suiteInvocationId:s.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:s.suiteArtifactsDir,suiteTotal:s.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l})):p.push(...await xf({discoveryEntries:s.entries,sessionName:f,suiteInvocationId:s.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:s.suiteArtifactsDir,suiteTotal:s.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l})),{status:`completed`,data:wf(s.total,p,Date.now()-e,s.suiteArtifactsDir)}}catch(e){let t=s(e);return{status:`failed`,error:{code:t.code,message:t.message}}}}async function df(e,t,n){let r=ff(e,t),i=pf(r),a=r.length-i.length,o=Md(e.requestId),s=await lf(e.shard?{kind:e.shard.mode,count:e.shard.count}:void 0,i,a,n);return{entries:r,runnable:i,shardPlan:s,suiteInvocationId:o,suiteArtifactsDir:mf(e,o),total:s?.total??r.length}}function ff(e,t){return Ed({platformFilter:e.platformFilter,discoverSources:t})}function pf(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function mf(e,t){return vd({artifactsDir:typeof e.artifactsDir==`string`?e.artifactsDir:void 0,cwd:e.cwd,suiteInvocationId:t})}function hf(e,t){t({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function gf(e){let{entries:t,total:n}=e,r=[];for(let[i,a]of t.entries())a.kind===`skip`&&(e.emitProgress({type:`replay-test`,file:a.path,status:`skip`,index:i+1,total:n,message:a.message}),r.push({file:a.path,status:`skipped`,durationMs:0,reason:a.reason,message:a.message}));return r}async function _f(e){return(await Promise.allSettled(e.shards.map(async t=>await yf({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[vf(r,e.sessionName,t.reason)]:[]})}function vf(e,t,n){let r=m(n);return{file:e.entries[0]?.entry.path??`shard-${e.shardIndex+1}`,session:bf(t,e),status:`failed`,durationMs:0,attempts:1,error:{code:r.code,message:r.message,hint:r.hint,diagnosticId:r.diagnosticId,logPath:r.logPath,details:r.details},shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}}async function yf(e){let{shard:t,sessionName:n}=e;return await Sf({...e,entries:t.entries,sessionName:bf(n,t),shard:t})}function bf(e,t){return`${e}:shard-${t.shardIndex+1}`}async function xf(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h}=e,g=[],_=0;for(let[e,v]of t.entries()){if(p())break;if(v.kind===`skip`){f({type:`replay-test`,file:v.path,status:`skip`,index:e+1,total:c,message:v.message}),g.push({file:v.path,status:`skipped`,durationMs:0,reason:v.reason,message:v.message});continue}_+=1;let t=await Jd({entry:v,sessionName:n,suiteInvocationId:r,caseIndex:_-1,cwd:i,requestId:a,retries:Fd(o.retries,v.manifest.attemptDefaults?.retries),timeoutMs:Pd(o.timeoutMs,v.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h});if(g.push(t.result),Cf(t,o,p))break}return g}async function Sf(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=[];for(let[e,v]of t.entries()){if(m())break;let{entry:t,suiteIndex:y}=v,b=await Jd({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:Fd(o.retries,t.manifest.attemptDefaults?.retries),timeoutMs:Pd(o.timeoutMs,t.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:y,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g});if(_.push(b.result),Cf(b,o,m))break}return _}function Cf(e,t,n){return n()||t.failFast===!0&&e.result.status===`failed`||e.infrastructure}function wf(e,t,n,r){let i=t.filter(e=>e.status===`passed`).length,a=t.filter(e=>e.status===`failed`),o=a.length,s=t.filter(e=>e.status===`skipped`).length,c=i+o,l=T(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:c,passed:i,failed:o,skipped:s,notRun:Math.max(0,e-c-s),durationMs:n,failures:a,tests:t,artifactsDir:r,...l?{snapshotDiagnostics:l}:{}}}async function Tf(e,t){let n=te(t)&&e.some(e=>k(e.entry,t)!==`ad`)?await Pi(t):void 0;return()=>e.map(e=>Ef(e,t,n))}function Ef(e,t,n){let r=e.entry,i=Jn(e,r),a=k(r,t)!==`ad`,o=re(i);return{path:r,manifest:{...a?{title:n?.inspectSource(i,r).title}:{},device:{platform:o.platform?{kind:`declared`,value:o.platform}:a?{kind:`caller-bound`}:{kind:`unspecified`},...o.target===void 0?{}:{target:o.target}},...o.timeoutMs!==void 0||o.retries!==void 0?{attemptDefaults:{...o.timeoutMs===void 0?{}:{timeoutMs:o.timeoutMs},...o.retries===void 0?{}:{retries:o.retries}}}:{}}}}function Df(e,t){return async n=>(await Af(e,n,t)).map(Of)}function Of(e){if(e.platform===`web`||!ye(e))throw new a(`INVALID_ARGS`,`test sharding requires a mobile device; ${e.id} is ${e.platform}`);return{id:e.id,name:e.name,platform:e.platform,...e.target===void 0?{}:{target:e.target}}}function kf(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}async function Af(e,t,n){let r=Pf(e),i=Mf(await Br(jf(e,n)),r,e);if(i.length<t)throw new a(`DEVICE_NOT_FOUND`,`test sharding requires ${Nf(t)}, but only ${i.length} matched`);return i.slice(0,t)}function jf(e,t){let n=V(e?.androidDeviceAllowlist,t);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:ve({requestedSetPath:e?.iosSimulatorDeviceSet,platform:e?.platform,target:e?.target,env:t}),androidSerialAllowlist:n?Array.from(n).sort():void 0}}function Mf(e,t,n){return t.length>0?Ff(e,t,n):e.filter(e=>If(e,n)).sort(zf)}function Nf(e){return`${e} device${e===1?``:`s`}`}function Pf(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Ff(e,t,n){return t.map(t=>{let r=Rf(t),i=e.find(e=>Lf(e,n)&&(e.id===t||Rf(e.name)===r));if(!i)throw new a(`DEVICE_NOT_FOUND`,`No shard device matched ${t}`);return i})}function If(e,t){return!Lf(e,t)||!ye(e)?!1:e.booted!==!1}function Lf(e,t){return!(!xe(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Rf(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function zf(e,t){return e.id.localeCompare(t.id)}function Bf(e){let t=Vf(e?.shardAll,`--shard-all`),n=Vf(e?.shardSplit,`--shard-split`);if(t!==void 0&&n!==void 0)throw new a(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(t!==void 0)return{mode:`all`,count:t};if(n!==void 0)return{mode:`split`,count:n}}function Vf(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new a(`INVALID_ARGS`,`${t} requires a positive integer`);return e}}const Hf=new Set([`IOS_BOOT_TIMEOUT`,`IOS_RUNNER_CONNECT_TIMEOUT`,`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,`IOS_TOOL_MISSING`,`ANDROID_BOOT_TIMEOUT`,`ADB_TRANSPORT_UNAVAILABLE`,`CI_RESOURCE_STARVATION_SUSPECTED`]);function Uf(e){return Hf.has(e.toUpperCase())}const Wf=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function Gf(e){if(!(`ok`in e)&&e.status===`failed`&&e.infrastructure===!0)return!0;let t=Kf(e);return t?qf(t.details)||Jf(t.code,t.message):!1}function Kf(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function qf(e){if(e?.recovery===`runner_recycle_budget_exhausted`)return!0;let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`||g(t)?!0:t?Uf(t):!1}function Jf(e,t){let n=`${e}\n${t}`.toLowerCase();return Wf.some(e=>n.includes(e))}function Yf(e){if(!e.ok)return{status:`failed`,error:e.error,artifactPaths:Qf(e.error.details?.artifactPaths),warnings:xn(e.error.details),infrastructure:Gf(e),...$f(e.error.details?.snapshotDiagnostics)};let t=e.data;return{status:`passed`,replayed:typeof t?.replayed==`number`?t.replayed:0,healed:typeof t?.healed==`number`?t.healed:0,warnings:xn(t),artifactPaths:Qf(t?.artifactPaths),...$f(t?.snapshotDiagnostics)}}function Xf(e){if(!e||e.ok)return;let t=Yf(e);return t.status===`failed`?t:void 0}function Zf(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Qf(e){return[...new Set(Zf(e))]}function $f(e){let t=ee(e);return t?{snapshotDiagnostics:t}:{}}const ep=1e3,tp=3e3;function np(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await rp(e)}}async function rp(e){let{req:t,sessionName:n,sessionStore:r,artifactsDir:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0)return;let o=r.get();if(!o||o.screenRecording)return;let s=wn(o.device.platform),c=i?q.join(i,`recording${s}`):Cn(o.device.platform);ap(a,{type:`video_recording_start`,session:n,videoPath:c}),j({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:c}}),e.video.throwIfCanceled();let l=await e.video.record(op({req:t,sessionName:n,phase:`start`,outputPath:c}));if(!l.ok)return ap(a,{type:`video_recording_start_failed`,session:n,videoPath:c,errorCode:l.error.code}),l;let u=Date.now();return await pe(ep),ap(a,{type:`video_preroll_done`,session:n,durationMs:Date.now()-u,requestedDurationMs:ep}),j({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-u,data:{session:n,requestedDurationMs:ep}}),l}async function ip(e){let{req:t,sessionName:n,sessionStore:r,artifactPaths:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0||!r.get()?.screenRecording)return;ap(a,{type:`video_tail_start`,session:n,requestedDurationMs:tp});let o=Date.now();await pe(tp);let s=Date.now(),c=await e.video.record(op({req:t,sessionName:n,phase:`stop`}));return ou(c).forEach(e=>i.add(e)),ap(a,{type:`video_recording_stop`,session:n,ok:c.ok,durationMs:Date.now()-s,tailDurationMs:s-o,errorCode:c.ok?void 0:c.error.code}),j({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-s,data:{session:n,ok:c.ok,tailDurationMs:s-o}}),c}function ap(e,t){e({...t,ts:new Date().toISOString()})}function op(e){let t={token:e.req.token,meta:e.req.meta};return e.phase===`start`?{request:t,sessionName:e.sessionName,phase:`start`,outputPath:e.outputPath}:{request:t,sessionName:e.sessionName,phase:`stop`}}const sp=[{keys:[`replayKeepSession`],requested:e=>e.replayKeepSession===!0,message:`test does not support --keep-session; suite attempts own their cleanup. Run one native .ad script directly with replay --keep-session.`},{keys:[`replayFrom`,`replayPlanDigest`],requested:e=>e.replayFrom!==void 0||e.replayPlanDigest!==void 0,message:`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`},{keys:[`saveScript`,`force`],requested:e=>!!e.saveScript||e.force===!0,message:`test does not support --save-script/--force; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`}],cp=({attemptId:e,parentAttemptId:t})=>{let n=lp(Kr(e,t)?.controller,t);return{cancel:()=>Gr(e),release:()=>{n(),Wr(e)}}};function lp(e,t){if(!t||!e)return()=>{};let n=qr(t);if(!n||n===e.signal)return()=>{};let r=()=>{e.abort(n.reason)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}function up(e){let{platform:t,target:n,artifactsDir:r,shard:i,sourceBundle:a}=e,o=dp(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0&&a===void 0?o:kf({...o??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r},...a===void 0?{}:{replayScriptSource:a}},i)}function dp(e){if(!e||e.recordVideo!==!0&&e.replayScriptSources===void 0)return e;let t={...e};return delete t.recordVideo,delete t.replayScriptSources,Object.keys(t).length>0?t:void 0}async function fp(e){let{request:t,session:{name:n,logPath:r},createSession:i,invoke:a,cleanupSession:o,video:c}=e;if(t.flags?.recordVideo===!0&&c===void 0)return f(`COMMAND_FAILED`,`Screen-recording runtime is not configured for replay video capture`);let l=t.flags??{};for(let e of sp)if(e.requested(l))return f(`INVALID_ARGS`,e.message);let u,d;try{u=hp(t,n,e.host.cwd),d=mp(t)}catch(e){let t=s(e);return f(t.code,t.message)}let p=new Map(d.map(e=>[e.entry,e])),m=await uf({request:u,emitProgress:Yr,isCanceled:()=>Jr(t.meta?.requestId),emitDiagnostic:j,bindAttemptCancellation:cp,runReplay:async({filePath:n,sessionName:o,platform:s,target:l,requestId:u,artifactsDir:d,artifactPaths:f,tracePath:m,appendTimingEvent:h,shard:g,onStep:_})=>{let v=e=>(f&&ou(e).forEach(e=>f.add(e)),e),y=up({parentFlags:t.flags,platform:s,target:l,artifactsDir:d,shard:g,sourceBundle:p.get(n)}),b=i(o,r),x=c?{req:t,sessionName:o,sessionStore:b.store,artifactsDir:d,appendTimingEvent:h,video:c}:void 0,S=x?np(x):void 0;return Yf(await md({...gp(e,{request:{...t,command:`replay`,session:o,positionals:[n],flags:y,meta:{...t.meta??{},...u?{requestId:u}:{}}},openLifecycle:S}),session:b,tracePath:m,onStep:_,publicNetworkOnly:e.publicNetworkOnly,invoke:async e=>{let t=x?await rp(x):void 0;return t&&!t.ok?t:v(await a(e))}}))},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,appendTimingEvent:o})=>{if(c)return Xf(await ip({req:t,sessionName:e,sessionStore:i(e,r).store,artifactsDir:a,appendTimingEvent:o,artifactPaths:n,video:c}))},discoverSources:await Tf(d,t.flags?.replayBackend),resolveShardTargets:Df(t.flags,e.host.env),cleanupSession:o});return m.status===`completed`?{ok:!0,data:pp(m.data,t)}:f(m.error.code,m.error.message)}function pp(e,t){let n=t.meta?.clientArtifactPaths?.artifactsDir,r=e.artifactsDir;if(!n||!r)return e;let i=q.join(n,q.basename(r)),a=e=>e===r||e.startsWith(r+q.sep)?i+e.slice(r.length):e,o={...e,artifactsDir:i,tests:e.tests.map(e=>`artifactsDir`in e&&e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e),failures:e.failures.map(e=>e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e)};return K.existsSync(r)?{...o,artifacts:[{field:`artifactsDir`,artifactType:`test-artifacts`,path:r,localPath:n,fileName:q.basename(r)}]}:o}function mp(e){let t=e.flags?.replayScriptSources;if(!t)throw new a(`INVALID_ARGS`,Wn);return t}function hp(e,t,n){let r=e.flags??{},i=e.meta?.cwd,a=vp(r.artifactsDir);return{inputs:e.positionals??[],sessionName:t,cwd:i,requestId:e.meta?.requestId,platformFilter:r.platform,artifactsDir:a===void 0?void 0:z(a,i??n),failFast:r.failFast===!0,retries:_p(r.retries),timeoutMs:_p(r.timeoutMs),shard:Bf(r)}}function gp(e,t){let{host:n,publicNetworkOnly:r,resolvedSessionScope:i,dispatch:a,dependencies:o}=e,s=a||t.openLifecycle?{...a,...t.openLifecycle?{openLifecycle:t.openLifecycle}:{}}:void 0;return{request:t.request,host:n,...r?{publicNetworkOnly:r}:{},...i?{resolvedSessionScope:i}:{},...s?{dispatch:s}:{},dependencies:o}}function _p(e){return typeof e==`number`?e:void 0}function vp(e){return typeof e==`string`?e:void 0}function yp(e,t,n,r){return{name:e,logPath:t,store:{...n,assertSelectorMatches:r.assertSelectorMatches,resolveOpenRuntimeHints:r.resolveOpenRuntimeHints},observationStore:{get:n.get,bindAuthority:r.bindAuthority},coordinator:r.createCoordinator()}}function bp(e){let{internal:t,...n}=e;return{request:n,...t?.publicNetworkOnly?{publicNetworkOnly:!0}:{},...t?.resolvedSessionScope?{resolvedSessionScope:t.resolvedSessionScope}:{}}}function xp(e,t){let n=b({...e,...t});return Object.keys(n).length>0?n:void 0}function Sp(e,t){return async({dispatch:n,...r})=>{let i=xp(t.internal,n);return await e(i?{...r,internal:i}:r)}}function Cp(e){let{sessionStore:t,mutationStore:n,hostCwd:r}=e,i=()=>t.get();return{view(){let e=i();if(e)return{repairBoundary:xt(e),pendingRecordAndHeal:e.pendingRecordAndHeal,scriptPublication:wp(e.scriptPublication??zt)}},armStep(e){n.update(t=>{gt(t,{saveScript:e.saveScript,force:e.force,sourcePath:e.sourcePath,healedSiblingPath:Ci(e.sourcePath),firstArm:e.firstArm},r)})},demoteForRerunIfArmed(){xt(i())!==void 0&&n.update(yt)},markCompleteIfArmed(){xt(i())!==void 0&&n.update(vt)},markSessionHeldIfArmed(e){if(e.ok||!_t(i()))return e;let t=kn(e.error.details?.divergence);return t&&(t.repairSessionHeld=!0),e},clearTombstone(){n.clearRepairTombstone()},clearCorrectiveWatermarkIfExpected(e){i()?.pendingRecordAndHeal?.expectedFrom===e&&n.update(t=>{t.pendingRecordAndHeal?.expectedFrom===e&&Ep(t)})},resumeStamper:{sessionExists:()=>i()!==void 0,stampCorrectiveWatermark(e){n.update(t=>{Tp({session:t,...e})})}}}}function wp(e){return{kind:e.kind,status:e.kind===`none`?void 0:e.status,targetPath:Lt(e),targetForce:Wt(e)}}function Tp(e){let{session:t,resume:n,repairHint:r,failedIndex:i,actions:a}=e;t.pendingRecordAndHeal=Dp({resume:n,repairHint:r,failedIndex:i,actions:a,actionsCountAtDivergence:t.actions.length})}function Ep(e){e.pendingRecordAndHeal=void 0}function Dp(e){let{resume:t,repairHint:n,failedIndex:r,actions:i,actionsCountAtDivergence:a}=e;if(n===`record-and-heal`)return t.allowed?{expectedFrom:t.from,actionsCountAtDivergence:a}:void 0;if((n===`caution`||n===`manual`)&&r===i.length)return{expectedFrom:r+1,actionsCountAtDivergence:a}}function Op(e){let{sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,screenRecordingAdmissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c}=e;return!n||!i||!a||!o||!s||!c?void 0:{throwIfCanceled:c,record:async e=>await hi({req:kp(e),sessionName:e.sessionName,sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,admissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c})}}function kp(e){return{token:e.request.token,session:e.sessionName,command:`record`,positionals:e.phase===`start`?[`start`,e.outputPath]:[`stop`],flags:{},meta:e.request.meta}}const Ap={resolveSessionScope:cn},jp=async({req:e,host:t,sessionName:n,logPath:r,sessionStore:i,invoke:a,invokeReplayAction:o})=>await md({...bp(e),host:t,session:Np(n,r,i),invoke:Sp(o??a,e),dependencies:Ap}),Mp=async({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,invoke:s,invokeReplayAction:c,bindDevice:l,platformServices:u,inspectFacts:d,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g,platformResourceCleanup:_})=>{if(!_)throw new a(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let v=Op({sessionStore:i,bindDevice:l,platformServices:u,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g});return await fp({...bp(t),host:e,session:Np(n,r,i),createSession:(e,t)=>Np(e,t,i),invoke:Sp(c??s,t),dependencies:Ap,cleanupSession:async n=>await Pp({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,inspectFacts:d,bindDevice:l,platformServices:u,platformResourceCleanup:_}),...v?{video:v}:{}})};function Np(e,t,n){let r=t=>{let r=n.get(e);return r?(t(r),!0):!1},i={get:()=>n.get(e),lookup:()=>n.lookup(e),getRuntimeHints:()=>n.getRuntimeHints(e),ensureSessionDir:()=>n.ensureSessionDir(e)};return yp(e,t,i,{createCoordinator:()=>Cp({sessionStore:i,mutationStore:{update:r,clearRepairTombstone:()=>n.clearRepairTombstone(e)},hostCwd:n.host.cwd}),assertSelectorMatches:t=>{let r=n.lookup(e);r&&gn(r,t)},resolveOpenRuntimeHints:({request:t,device:r,platform:i})=>Ar({req:t,sessionStore:{getRuntimeHints:t=>t===e?n.getRuntimeHints(e):void 0},sessionName:e,device:r,platform:i}),bindAuthority:t=>{let r=n.lookup(e);return{...bl({sessionStore:n,ref:r,signal:t}),capture:async({flags:i,logPath:o})=>{let s=r?n.requireCurrent(r):void 0;if(!s)throw new a(`NO_ACTIVE_SESSION`,`Session "${e}" is no longer active.`);return await ni({device:s.device,session:s,flags:i,logPath:o,signal:t})}}}})}async function Pp(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e;if(!i.get(n))return;let o=await jo({host:e.host,req:pn({token:t.token,session:n,command:`close`,positionals:[],flags:{},meta:t.meta,internal:{cleanupIntent:`suite-owned-test-session`}},t),sessionName:n,logPath:r,sessionStore:i,leaseRegistry:e.leaseRegistry,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup});if(!o.ok)throw new a(o.error.code,o.error.message,{...o.error.details??{},...o.error.hint?{hint:o.error.hint}:{}})}function Fp(e){let{req:t,sessionName:n,sessionStore:r}=e;if(t.command!==ae.sessionSaveScript)return null;if((t.positionals?.length??0)>1)return zp(new a(`INVALID_ARGS`,`session save-script accepts at most one output path.`));let i=r.lookup(n);if(!i)return zp(new a(`SESSION_NOT_FOUND`,`No active session "${n}".`,{hint:`Start a fresh journey with open <app> --save-script[=<path>], then retry.`}));let o=r.requireCurrent(i),s=Rp(o);if(s)return zp(s);let c=t.positionals?.[0]?.trim();if(t.positionals?.[0]!==void 0&&!c)return zp(new a(`INVALID_ARGS`,`session save-script path cannot be empty.`));Vt(o,{explicitPath:c,liveForce:t.flags?.force},r.host.cwd);let l=r.writeSessionLog(i,{force:Yt(o,t.flags?.force),publication:`active`});return l.written?(Kt(o,l.path),{ok:!0,data:{session:o.name,savedScript:l.path,actionCount:l.actionCount,...R(`Published script: ${l.path}`)}}):zp(l.error??new a(`COMMAND_FAILED`,`The active session script was not published.`,{retriable:!0,hint:`The session remains armed; retry session save-script.`}))}function Ip(e){if(wt(e))return`repair`;let t=e.scriptPublication;return t?.kind===`authoring`&&t.status!==`armed`?t.status:Bt(e)?void 0:`not-armed`}const Lp={repair:()=>new a(`COMMAND_FAILED`,`This session has an active .ad repair transaction and cannot use ordinary active-session publication.`,{hint:`Finish or abort the repair through replay --from and its existing close/teardown protocol.`}),aborted:()=>new a(`COMMAND_FAILED`,`This script recording was aborted by a second successful open and cannot be published.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`}),published:()=>new a(`COMMAND_FAILED`,`This script recording has already been published.`,{hint:`Continue using the live session, or close it and start a fresh authoring session.`}),"not-armed":()=>new a(`COMMAND_FAILED`,`Script recording was not armed before this journey began; session history cannot be published without recording-time target evidence.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`})};function Rp(e){let t=Ip(e);return t?Lp[t]():void 0}function zp(e){return{ok:!1,error:m(e)}}function Bp(e){let t=(e[0]??``).toLowerCase();return t===`read`||t===`write`?t:void 0}function Vp(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:ir(e)}}async function Hp(e,t,n){if(n.length!==1)throw new a(`INVALID_ARGS`,`clipboard read does not accept additional arguments`);return{action:`read`,text:await e.operations.readClipboard(Vp(t))}}async function Up(e,t,n){if(n.length<2)throw new a(`INVALID_ARGS`,`clipboard write requires text (use "" to clear clipboard)`);let r=n.slice(1).join(` `),i={...Vp(t),text:r};return await e.operations.writeClipboard(i),{action:`write`,textLength:Array.from(r).length,...R(`Clipboard updated`)}}async function Wp(e){let{device:t,action:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o}=e;if(n===`read`){let e=await H({command:`clipboard`,device:t,use:ft,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(e.type===`response`)return{ok:!1,response:e.response};let n=e.runtime;return{ok:!0,execute:e=>Hp(n,e,r)}}let s=await H({command:`clipboard`,device:t,use:mt,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(s.type===`response`)return{ok:!1,response:s.response};let c=s.runtime;return{ok:!0,execute:e=>Up(c,e,r)}}async function Gp(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=i.lookup(n),l=c?.session,u=t.flags??{},d=J(D.clipboard,l,u);if(d)return d;let p=t.positionals??[],m=Bp(p);if(!m)return f(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let h=await Y({session:l,flags:u,env:i.host.env,platformServices:s});c&&i.requireCurrent(c);let g=await Wp({device:h,action:m,positionals:p,inspectFacts:a,bindDevice:o,platformServices:s});if(!g.ok)return g.response;let _=c?i.requireCurrent(c):void 0,v=await g.execute(ar(r,t.flags,_?.appBundleId,_?.trace?.outPath));return I(i,c,t,t.command,v),{ok:!0,data:{platform:M(h),...v}}}function Kp(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function qp(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function Jp(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function Yp(e,t,...n){for(let r of n)$(e,r,t)}function $(e,t,n){e.push(t),Yr({type:`command`,status:`progress`,message:Xp(t,n)})}function Xp(e,t){return[Li(e,{useColor:t}),...Ii(e)].join(`
3
+ `)}async function Zp(e,t){let{device:n,targetApp:r,session:i,listInstalledApps:a,useColor:o}=t;if(r)try{let t=a?Qp(r,await a(`all`))?.id:void 0;if(!t){$(e,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${M(n)}.`,evidence:{requested:r,platform:M(n)}},o);return}$(e,{id:`target-app`,status:`pass`,summary:`Target app is launchable: ${t}`,evidence:{requested:r,resolved:t,sessionApp:i?.appBundleId}},o)}catch(t){let r=m(t);$(e,{id:`target-app`,status:`fail`,summary:`Target app check failed: ${r.message}`,hint:r.hint??`Install the app or pass an exact package/bundle id or app name.`,command:`agent-device apps --platform ${M(n)} --all`,evidence:{code:r.code,message:r.message}},o)}}function Qp(e,t){let n=e.trim().toLowerCase(),r=t.find(e=>e.id.toLowerCase()===n||e.name.toLowerCase()===n);if(r)return r;let i=t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n));if(i.length===1)return i[0];throw i.length>1?new a(`AMBIGUOUS_MATCH`,`Multiple launchable apps matched "${e}"`,{matches:i.map(e=>e.id),hint:`Pass an exact package/bundle id from agent-device apps --all.`}):new a(`APP_NOT_INSTALLED`,`No launchable installed app matched "${e}"`)}async function $p(e,t,n,r,i){let a=tm(t,n,r);try{let t=await rm(a),n=nm(t.devices,a);return $(e,{id:`device`,status:n.length===0?`fail`:`pass`,summary:cm(n,a,t.failures),hint:n.length===0?dm(t.failures):void 0,command:n.length===0?gm(a):void 0,evidence:_m(n,t.failures)},i),n.length>0&&am(e,t.failures,i),{devices:n,hostDevices:n.filter(e=>t.hostDevices.includes(e)),platform:a.platform,target:a.target}}catch(t){let n=m(t);return $(e,{id:`device`,status:`fail`,summary:n.message,hint:n.hint,command:`agent-device devices`,evidence:{code:n.code,details:n.details}},i),{devices:[],hostDevices:[],platform:a.platform,target:a.target}}}function em(e,t,n,r){if(!n||!t)return;let i=t.devices.filter(e=>e.booted===!0);if(i.length===1)return i[0];$(e,{id:`target-app-device`,status:`fail`,summary:i.length===0?`Target app check needs one booted device; none matched.`:`Target app check needs one booted device; ${i.length} matched.`,hint:i.length===0?`Boot a device, or adjust --platform/--target/--device/--udid/--serial.`:`Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.`,command:t.platform?`agent-device devices --platform ${t.platform}`:`agent-device devices`,evidence:{targetApp:n,booted:i.map(e=>({platform:M(e),id:e.id,name:e.name}))}},r)}function tm(e,t,n){let r=e.flags??{};return Gn({platform:r.platform??t?.device.platform,target:r.target??t?.device.target,device:r.device,udid:r.udid,serial:r.serial,iosSimulatorDeviceSet:r.iosSimulatorDeviceSet,androidDeviceAllowlist:r.androidDeviceAllowlist},n)}function nm(e,t){return e.filter(e=>be(e,t,{includeExplicitSelectors:!0}))}async function rm(e){if(e.platform)return{...im([await zr(e)]),failures:[]};let t=[],n=[];for(let r of v)try{t.push(await zr({...e,platform:r}))}catch(e){n.push(sm(r,e))}return{...im(t),failures:n}}function im(e){return{devices:e.flatMap(e=>e.devices),hostDevices:e.flatMap(e=>e.source===`local`?e.devices:[])}}function am(e,t,n){for(let r of t)$(e,om(r),n)}function om(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${mm(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${mm(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function sm(e,t){let n=m(t);return{platform:e,message:n.message,hint:n.hint,code:n.code}}function cm(e,t,n){if(e.length===0)return n.length>0?`No ${lm(t)} devices found; ${um(n)}.`:`No ${lm(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${lm(t)} ${hm(e.length,`device`)} available; ${r} booted`,a=fm(e,t);return a?`${i} (${a}).`:`${i}.`}function lm(e){let t=e.platform?mm(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function um(e){return e.slice(0,2).map(e=>`${mm(e.platform)} inventory failed: ${e.message}`).join(`; `)}function dm(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function fm(e,t){if(t.platform||t.target)return;let n=_(e),r=pm();return[`android`,`harmonyos`,`apple`,`vega`,`linux`,`web`].flatMap(e=>{let t=n[e];return t.available>0?[`${r[e]} ${t.available} available, ${t.booted} booted`]:[]}).join(`; `)}function pm(){return{android:`Android`,harmonyos:`HarmonyOS`,apple:`Apple`,vega:`Vega`,linux:`Linux`,web:`web`}}function mm(e){return e===`ios`?`iOS`:e===`macos`?`macOS`:e===`android`?`Android`:e===`harmonyos`?`HarmonyOS`:e===`vega`?`Vega`:e===`linux`?`Linux`:e===`web`?`web`:`Apple`}function hm(e,t){return e===1?t:`${t}s`}function gm(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function _m(e,t){let n=new Map;for(let t of e){let e=M(t),r=n.get(e)??{available:0,booted:0};r.available+=1,t.booted===!0&&(r.booted+=1),n.set(e,r)}return{available:e.length,booted:e.filter(e=>e.booted===!0).length,byPlatform:Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}const vm=1500;async function ym(e,t,n,r={}){let i=`http://${e}:${t}/status`;try{let a=await fetch(i,{signal:AbortSignal.timeout(1500)}),o=await a.text(),s=a.ok&&o.toLowerCase().includes(`packager-status:running`),c=s?await bm(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?xm(i,c):`React Native dev server responded at ${i}, but did not report packager-status:running.`,hint:s?void 0:`Verify this is the Metro/Re.Pack instance for the target app, or restart the dev server.`,evidence:{url:i,statusCode:a.status,body:o.slice(0,120),kind:n,...c?{process:c}:{}}}}catch(e){return{id:`metro`,status:n===`auto`?`warn`:`fail`,summary:`React Native dev server is not reachable at ${i}.`,hint:`Start Metro or Re.Pack for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.`,command:`curl -fsS ${i}`,evidence:{url:i,error:e instanceof Error?e.message:String(e),kind:n}}}}async function bm(e,t,n){try{return await(n.resolveProcessInfo??Sm)(e,t)}catch{return}}function xm(e,t){return t?.cwd?`React Native dev server is reachable at ${e} (cwd: ${t.cwd}).`:`React Native dev server is reachable at ${e}.`}async function Sm(e,t){if(!Cm(e))return;let n=await wm(t);if(n!==void 0)return{pid:n,cwd:await Tm(n)}}function Cm(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function wm(e){let t=await me(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:vm});if(t.exitCode===0)return t.stdout.split(`
4
+ `).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function Tm(e){let t=await me(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:vm});if(t.exitCode===0)return t.stdout.split(`
5
+ `).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const Em=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],Dm=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerDeviceType`,`providerProject`,`providerBuild`,`providerSessionName`,`providerDeviceOrientation`,`providerGeoLocation`,`providerTimezone`,`providerAppiumVersion`,`providerLanguage`,`providerLocale`,`providerNetworkProfile`,`providerCustomNetwork`,`providerNoResignApp`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function Om(e,t){let n=Ri(e.meta?.cwd);return{targetApp:Nm(e.flags?.targetApp)??t?.appBundleId,metroHost:Nm(e.runtime?.metroHost)??`127.0.0.1`,metroPort:Pm(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:jm(e,n)}}function km(e,t={}){let n=Mm(e);return n?[{id:`remote-connection`,status:t.required?`pass`:`info`,summary:`Remote daemon/session or provider scope is configured.`,evidence:n}]:t.required?[{id:`remote-connection`,status:`fail`,summary:`No remote daemon/session or provider scope is configured.`,hint:`Use connect, --remote-config <path>, or direct remote/provider flags for the command.`}]:[]}function Am(e,t,n,r={}){let i=n?e.listRefs().filter(e=>e.address!==t&&e.session.device.platform===n.device.platform&&e.session.device.id===n.device.id).map(e=>e.address):[];return n?[{id:`session`,status:i.length>0?`warn`:`pass`,summary:i.length>0?`Other active sessions target the same device: ${i.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:i.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:i.length>0?`agent-device close --session ${i[0]} --platform ${M(n.device)}`:void 0,evidence:{session:t,sameDeviceSessions:i,sessionStateDir:e.resolveSessionDir(t)}}]:[{id:`session`,status:`info`,summary:r.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:`This is expected before a run. Use open when app foreground state matters.`}]}function jm(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function Mm(e){let t={...Object.fromEntries([...Em,...Dm].flatMap(t=>typeof e.flags?.[t]==`string`?[[t,`<configured>`]]:[])),...e.flags?.sessionIsolation===`tenant`?{sessionIsolation:`tenant`}:{}};return Object.keys(t).length>0?t:void 0}function Nm(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Pm(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}async function Fm(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,inspectFacts:a,bindDevice:o}=e;if(t.command!==D.doctor)return null;let s=Im(e.hostDiagnostics),c=r.get(n),l=Om(t,c),u=zm(r,n),d=Fi(e.host.env,!!process.stderr.isTTY),f=[];if(Yp(f,d,{id:`agent-device`,status:`pass`,summary:`agent-device ${Dn()} using ${u}`,evidence:{version:Dn(),stateDir:u}},...km(t,{required:l.remote}),...Am(r,n,c,{remote:l.remote})),l.remote)return Wm(f,l);let p=Lm(l,u,i),m=await $p(f,t,c,e.host.env,d),h=await s.toolchainCheck(c?.device.platform??m?.platform,p);h&&$(f,h,d);let g=await Bm({checks:f,context:p,hostDiagnostics:s,inventory:m,options:l,session:c,inspectFacts:a,bindDevice:o,req:t,env:e.host.env,useColor:d}),_=c?.device??Rm(m,g);if(_){let e=await s.warmupCheck(_,p);e&&$(f,e,d)}return Wm(f,l,{device:g,includeMetro:!0,inventory:m})}function Im(e){if(!e)throw new a(`COMMAND_FAILED`,`Host diagnostics gateway is not configured`,{reason:`runtime-gateway-missing`});return e}function Lm(e,t,n){return Object.freeze({stateDir:t,metroPort:e.metroPort,shouldProbeMetro:e.shouldProbeMetro,isProviderDevice:e=>er(e),emitProgress:e=>Yr({type:`command`,status:`progress`,message:e}),listLocalDeviceInventory:async e=>await Hr(e),shouldPropagateInventoryProbeError:Vr,transportOverrides:Object.freeze({androidAdb:n})})}function Rm(e,t){let n=e?.hostDevices??[];if(t)return n.includes(t)?t:void 0;let r=n.filter(e=>F(e)&&e.kind===`simulator`);return r.find(e=>e.booted===!0)??r[0]}function zm(e,t){let n=q.dirname(e.resolveSessionDir(t));return q.basename(n)===`sessions`?q.dirname(n):n}async function Bm(e){let{checks:t,context:n,hostDiagnostics:r,inventory:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=e,f=o?.device??em(t,i,a.targetApp,d);return f&&await Vm(t,{context:n,hostDiagnostics:r,device:f,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}),a.shouldProbeMetro&&$(t,await ym(a.metroHost,a.metroPort,a.kind),d),Yp(t,d,...await r.ambientChecks(n)),f}async function Vm(e,t){let{context:n,hostDiagnostics:r,device:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=t,f;try{f=await Hm({device:i,req:l,targetApp:a.targetApp,inspectFacts:s,bindDevice:c,env:u})}catch(e){f=async()=>{throw e}}await Zp(e,{device:i,session:o,targetApp:a.targetApp,listInstalledApps:f,useColor:d}),Yp(e,d,...await r.deviceChecks(i,n))}async function Hm(e){if(e.device.platform!==`harmonyos`)return Um(e)}async function Um(e){let{device:t,req:n,targetApp:r,inspectFacts:i,bindDevice:a,env:o}=e;if(!r||!i||!a)return;let s=await i(t),c=s.operations.listApps,l=s.operations.ensureReady;if(!c.available||!l.available)return;let u=await a(t,et),d=V(n.flags?.androidDeviceAllowlist,o),f=await Io(u,{serial:n.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0});return async e=>await Lo(u,f,e)}function Wm(e,t,n={}){let r=Kp(e);return{ok:!0,data:{status:r,summary:qp(r),kind:t.kind,platform:n.device?M(n.device):n.inventory?.platform,target:n.device?.target??n.inventory?.target,targetApp:t.targetApp,metro:n.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:Jp(e)}}}async function Gm(e){return await H({...e,command:`prepare`,use:ot})}async function Km(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]??``;if(a!==`ios-runner`)return f(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let o=i.get(n),s=t.flags??{},c=J(D.prepare,o,s);if(c)return c;let l=await he(`prepare_resolve_device`,()=>Y({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),void 0,`start`),u=await he(`prepare_admit_runtime`,()=>Gm({device:l,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}),void 0,`start`);if(u.type===`response`)return u.response;let d=Date.now(),p=await u.runtime.operations.prepareAppleRunner({timeoutMs:qm(t),execution:{requestId:t.meta?.requestId,logPath:r,traceLogPath:o?.trace?.outPath,verbose:t.flags?.verbose,iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir,runnerLeaseContext:hr(t)}});return{ok:!0,data:Jm(a,l,Math.max(0,Date.now()-d),p)}}function qm(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:lt}function Jm(e,t,n,r){return{action:e,platform:M(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:Ym(n,r),message:`Prepared Apple runner: ${t.name}`}}function Ym(e,t){let n=Xm(t.buildMs),r=Zm(t.connectMs),i=Zm(t.healthCheckMs);return{totalMs:e,additiveParts:{...n===void 0?{}:{buildMs:n},connectAfterBuildMs:Math.max(0,r-(n??0)),healthCheckMs:i},containment:n===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},note:`Top-level prepare timing fields are diagnostic and may overlap; use timing.additiveParts for additive wall-clock phases.`}}function Xm(e){return e===void 0?void 0:Zm(e)}function Zm(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}const Qm=e=>Ro(e),$m=e=>Gs({host:e.host,req:e.req,createCommandSurface:e.createCommandSurface,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim}),eh=e=>jo({host:e.host,req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,leaseRegistry:e.leaseRegistry,leaseLifecycleProvider:e.leaseLifecycleProvider,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup}),th=async({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u})=>await rl({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u}),nh={session_list:Qm,devices:Qm,capabilities:Qm,apps:Qm,doctor:async({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s})=>await Fm({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s}),boot:Xs,shutdown:$s,appstate:cc,session_save_script:async({req:e,sessionName:t,sessionStore:n})=>Fp({req:e,sessionName:t,sessionStore:n}),runtime:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await pa({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),clipboard:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await Gp({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),keyboard:Wa,perf:th,logs:th,events:th,network:th,audio:th,prepare:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await Km({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),install:ao,reinstall:ao,uninstall:ao,install_source:ao,release_materialized_paths:async({req:e})=>await Zi({req:e}),push:ao,"trigger-app-event":Ga,open:$m,replay:jp,test:Mp,batch:async({req:e,sessionName:t,invoke:n})=>await oo(e,t,n),close:eh};async function rh(e){let{host:t,req:n,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o=new un,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}=e,T=nh[n.command];return T?await T({host:t,req:n,createCommandSurface:e.createCommandSurface,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}):null}export{rh as handleSessionCommands};