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 +1 @@
1
- import{R as e,Z as t}from"./sdk-contracts.js";import{S as n,nt as r,p as i}from"./apple-runner-platform.js";import{_ as a,b as o,g as s}from"./runner-client.js";import{a as c,c as l,i as u,n as d,t as f}from"./runner-startup-transport.js";import{A as p,M as m,O as h,R as g,S as _,T as v,b as y,c as b,p as x,s as S,u as C,x as w,y as T}from"./runner-error-classification.js";import E from"node:fs/promises";const D=2e3;async function ee(e,t={}){if(e){try{await l(e,{timeoutMs:Math.min(D,t.timeoutMs??D),signal:t.signal})}catch{return}try{return{logPath:e,byteOffset:(await E.stat(e)).size}}catch{return{logPath:e,byteOffset:0}}}}async function te(t){let n=await O(t.logSince)??A(t.error);return n?new e(n.code??t.error.code,t.error.message,{...t.error.details??{},hint:typeof t.error.details?.hint==`string`?`${t.error.details.hint} ${n.hint}`:n.hint,runnerFailureReason:n.reason},t.error):t.error}async function O(e){if(!e)return;let t=await P(e,65536);if(t)return k(t)}function k(e){let t=e.toLowerCase();if(j(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(M(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function A(e){if(N(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function j(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function M(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function N(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function P(e,t){let n;try{let r=await E.stat(e.logPath),i=Math.max(e.byteOffset,r.size-t),a=r.size-i;if(a<=0)return;n=await E.open(e.logPath,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}async function F(e,t,n,r,i,a,o){try{return await I(e,t,n,r,i,a,o)}catch(e){let n=x(e);throw n&&(t.lastHealthyMutation=void 0,await a(n)),e}}async function I(e,t,n,r,a,o,s){let c=await ee(r,{timeoutMs:a,signal:s}),l=g(n),u=y(l),d=i.fromTimeoutMs(a),f=X(t,l);f.action===`run`?await G({device:e,session:t,runnerCommand:l,logAttempt:c,deadline:d,signal:s,decision:f}):K(l,t,f);let p;try{p=await V({device:e,session:t,runnerCommand:l,logPath:r,deadline:d,timeoutMs:a,signal:s,readOnlyCommand:u})}catch(e){throw B(e,t,f)}try{let e=await q(p,t,c);return await L(t,l,e,o),e}catch(e){let n=R(t,l,e);throw x(e)||n?e:B(e,t,f)}}async function L(e,t,n,r){e.commandCharges.settleAnswered(t.commandId);let i=z(n);i!==void 0&&(e.runnerMainThreadBusy=i);let a=Y(n);a?(e.lastHealthyMutation=void 0,await r(a)):T(t)&&(e.lastHealthyMutation={atMs:Date.now(),appBundleId:t.appBundleId})}function R(e,t,n){let r=C(n);return r?e.commandCharges.settleAnswered(t.commandId):e.commandCharges.markAbandoned(t.commandId),b(n)?e.runnerMainThreadBusy=!0:r&&(e.runnerMainThreadBusy=!1),r}function z(e){return typeof e.runnerMainThreadBusy==`boolean`?e.runnerMainThreadBusy:void 0}function B(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,Q(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function V(t){let{device:n,session:i,runnerCommand:a,logPath:o,deadline:s,timeoutMs:l,signal:f,readOnlyCommand:p}=t,m=s.remainingMs();if(m<=0)throw new e(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:l});let h=p?{command:a.command,commandId:a.commandId,readOnly:!0,sessionReady:i.state===`ready`,timeoutMs:m}:{command:a.command,commandId:a.commandId};c(f);let g=!_(a);g&&i.commandCharges.charge(a.commandId);try{return await r(`ios_runner_command_send`,async()=>p?await d(n,i.endpoint,a,o,m,i,f):await u(n,i.endpoint,a,m,f),h)}catch(e){throw g&&await H({device:n,session:i,runnerCommand:a,deadline:s,signal:f,error:e}),e}}async function H(e){let{session:n,runnerCommand:r,signal:i,error:a}=e;if(S(a)){n.commandCharges.withdrawUnsent(r.commandId);return}n.commandCharges.markAbandoned(r.commandId),!(!t(i?.reason)||n.state!==`ready`)&&await U(e)}async function U(e){let{device:t,session:r,runnerCommand:i,deadline:a}=e,c=Date.now(),l=`deadline_exceeded`,u,d=0;for(;a.remainingMs()>0;){d+=1;try{u=await W(t,r,i,Math.min(1e3,a.remainingMs()))}catch{l=`status_unavailable`;break}if(o(r,i,u)!==void 0){l=`terminal`;break}if(!s.has(u)){l=`not_in_flight`;break}let e=Math.min(100,a.remainingMs());await new Promise(t=>setTimeout(t,e))}n({level:l===`terminal`?`debug`:`warn`,phase:`ios_runner_canceled_command_drain`,durationMs:Date.now()-c,data:{command:i.command,commandId:i.commandId,outcome:l,lifecycleState:u,polls:d}})}async function W(e,t,n,r){let i=await q(await u(e,t.endpoint,{command:`status`,statusCommandId:n.commandId},r),t);return typeof i.lifecycleState==`string`?i.lifecycleState:``}async function G(e){let{device:t,session:n,runnerCommand:i,logAttempt:a,deadline:o,signal:s,decision:c}=e,l=a?.logPath,u=n.state===`ready`?Math.min(1e3,o.remainingMs()):Math.min($(n),o.remainingMs());try{let e=z(await q(await r(`ios_runner_readiness_preflight`,async()=>await d(t,n.endpoint,g({command:`uptime`}),l,u,n,s),{command:i.command,commandId:i.commandId,reason:c.reason,lastHealthyMutationAgeMs:c.lastHealthyMutationAgeMs,sessionReady:n.state===`ready`,timeoutMs:u}),n,a));e!==void 0&&(n.runnerMainThreadBusy=e)}catch(e){throw Z(e)}}function K(e,t,r){n({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:r.reason,lastHealthyMutationAgeMs:r.reason===`recent_healthy_mutation`?r.lastHealthyMutationAgeMs:void 0,sessionReady:t.state===`ready`}})}async function q(e,t,n){let r=h(await e.text());if(!p(r))throw await te({error:v(r,n?.logPath),logSince:n});a(t,`ready`);let i=m(r);return J(i),i}function J(e){let t=e.gestureFallback;typeof t==`string`&&t.length!==0&&n({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function Y(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function X(e,t){let n=y(t);if(e.state!==`ready`)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(w(t))return{action:`skip`,reason:`preflight_exempt_command`};if(_(t))return{action:`skip`,reason:`readiness_probe_command`};if(!T(t))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function Z(e){return Q(e,{runnerReadinessPreflightFailed:!0})}function Q(t,n){let r=t instanceof e?t:new e(`COMMAND_FAILED`,t instanceof Error?t.message:String(t),void 0,t);return new e(r.code,r.message,{...r.details??{},...n},r.cause??t)}function $(e){let t=e.launchDeadline;return t?Math.max(0,Math.floor(t.remainingMs())):f}export{F as executeRunnerExchange,$ as readRunnerStartupTimeoutMs};
1
+ import{Q as e,R as t}from"./sdk-contracts.js";import{G as n,t as r,u as i}from"./host2.js";import{_ as a,b as o,g as s}from"./runner-client.js";import{a as c,c as l,i as u,n as d,t as f}from"./runner-startup-transport.js";import{A as p,M as m,O as h,R as g,S as _,T as v,b as y,c as b,p as x,s as S,u as C,x as w,y as T}from"./runner-error-classification.js";import E from"node:fs/promises";const D=2e3;async function ee(e,t={}){if(e){try{await l(e,{timeoutMs:Math.min(D,t.timeoutMs??D),signal:t.signal})}catch{return}try{return{logPath:e,byteOffset:(await E.stat(e)).size}}catch{return{logPath:e,byteOffset:0}}}}async function te(e){let n=await O(e.logSince)??A(e.error);return n?new t(n.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${n.hint}`:n.hint,runnerFailureReason:n.reason},e.error):e.error}async function O(e){if(!e)return;let t=await P(e,65536);if(t)return k(t)}function k(e){let t=e.toLowerCase();if(j(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(M(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function A(e){if(N(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function j(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function M(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function N(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function P(e,t){let n;try{let r=await E.stat(e.logPath),i=Math.max(e.byteOffset,r.size-t),a=r.size-i;if(a<=0)return;n=await E.open(e.logPath,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}async function F(e,t,n,r,i,a,o){try{return await I(e,t,n,r,i,a,o)}catch(e){let n=x(e);throw n&&(t.lastHealthyMutation=void 0,await a(n)),e}}async function I(e,t,n,i,a,o,s){let c=await ee(i,{timeoutMs:a,signal:s}),l=g(n),u=y(l),d=r.fromTimeoutMs(a),f=X(t,l);f.action===`run`?await G({device:e,session:t,runnerCommand:l,logAttempt:c,deadline:d,signal:s,decision:f}):K(l,t,f);let p;try{p=await V({device:e,session:t,runnerCommand:l,logPath:i,deadline:d,timeoutMs:a,signal:s,readOnlyCommand:u})}catch(e){throw B(e,t,f)}try{let e=await q(p,t,c);return await L(t,l,e,o),e}catch(e){let n=R(t,l,e);throw x(e)||n?e:B(e,t,f)}}async function L(e,t,n,r){e.commandCharges.settleAnswered(t.commandId);let i=z(n);i!==void 0&&(e.runnerMainThreadBusy=i);let a=Y(n);a?(e.lastHealthyMutation=void 0,await r(a)):T(t)&&(e.lastHealthyMutation={atMs:Date.now(),appBundleId:t.appBundleId})}function R(e,t,n){let r=C(n);return r?e.commandCharges.settleAnswered(t.commandId):e.commandCharges.markAbandoned(t.commandId),b(n)?e.runnerMainThreadBusy=!0:r&&(e.runnerMainThreadBusy=!1),r}function z(e){return typeof e.runnerMainThreadBusy==`boolean`?e.runnerMainThreadBusy:void 0}function B(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,Q(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function V(e){let{device:r,session:i,runnerCommand:a,logPath:o,deadline:s,timeoutMs:l,signal:f,readOnlyCommand:p}=e,m=s.remainingMs();if(m<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:l});let h=p?{command:a.command,commandId:a.commandId,readOnly:!0,sessionReady:i.state===`ready`,timeoutMs:m}:{command:a.command,commandId:a.commandId};c(f);let g=!_(a);g&&i.commandCharges.charge(a.commandId);try{return await n(`ios_runner_command_send`,async()=>p?await d(r,i.endpoint,a,o,m,i,f):await u(r,i.endpoint,a,m,f),h)}catch(e){throw g&&await H({device:r,session:i,runnerCommand:a,deadline:s,signal:f,error:e}),e}}async function H(t){let{session:n,runnerCommand:r,signal:i,error:a}=t;if(S(a)){n.commandCharges.withdrawUnsent(r.commandId);return}n.commandCharges.markAbandoned(r.commandId),!(!e(i?.reason)||n.state!==`ready`)&&await U(t)}async function U(e){let{device:t,session:n,runnerCommand:r,deadline:a}=e,c=Date.now(),l=`deadline_exceeded`,u,d=0;for(;a.remainingMs()>0;){d+=1;try{u=await W(t,n,r,Math.min(1e3,a.remainingMs()))}catch{l=`status_unavailable`;break}if(o(n,r,u)!==void 0){l=`terminal`;break}if(!s.has(u)){l=`not_in_flight`;break}let e=Math.min(100,a.remainingMs());await new Promise(t=>setTimeout(t,e))}i({level:l===`terminal`?`debug`:`warn`,phase:`ios_runner_canceled_command_drain`,durationMs:Date.now()-c,data:{command:r.command,commandId:r.commandId,outcome:l,lifecycleState:u,polls:d}})}async function W(e,t,n,r){let i=await q(await u(e,t.endpoint,{command:`status`,statusCommandId:n.commandId},r),t);return typeof i.lifecycleState==`string`?i.lifecycleState:``}async function G(e){let{device:t,session:r,runnerCommand:i,logAttempt:a,deadline:o,signal:s,decision:c}=e,l=a?.logPath,u=r.state===`ready`?Math.min(1e3,o.remainingMs()):Math.min($(r),o.remainingMs());try{let e=z(await q(await n(`ios_runner_readiness_preflight`,async()=>await d(t,r.endpoint,g({command:`uptime`}),l,u,r,s),{command:i.command,commandId:i.commandId,reason:c.reason,lastHealthyMutationAgeMs:c.lastHealthyMutationAgeMs,sessionReady:r.state===`ready`,timeoutMs:u}),r,a));e!==void 0&&(r.runnerMainThreadBusy=e)}catch(e){throw Z(e)}}function K(e,t,n){i({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:n.reason,lastHealthyMutationAgeMs:n.reason===`recent_healthy_mutation`?n.lastHealthyMutationAgeMs:void 0,sessionReady:t.state===`ready`}})}async function q(e,t,n){let r=h(await e.text());if(!p(r))throw await te({error:v(r,n?.logPath),logSince:n});a(t,`ready`);let i=m(r);return J(i),i}function J(e){let t=e.gestureFallback;typeof t==`string`&&t.length!==0&&i({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function Y(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function X(e,t){let n=y(t);if(e.state!==`ready`)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(w(t))return{action:`skip`,reason:`preflight_exempt_command`};if(_(t))return{action:`skip`,reason:`readiness_probe_command`};if(!T(t))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function Z(e){return Q(e,{runnerReadinessPreflightFailed:!0})}function Q(e,n){let r=e instanceof t?e:new t(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new t(r.code,r.message,{...r.details??{},...n},r.cause??e)}function $(e){let t=e.launchDeadline;return t?Math.max(0,Math.floor(t.remainingMs())):f}export{F as executeRunnerExchange,$ as readRunnerStartupTimeoutMs};
@@ -1 +1 @@
1
- import{R as e}from"./sdk-contracts.js";import{i as t,n,r,y as i}from"./runner.js";import{A as a,B as o,E as ee,F as te,L as ne,O as s,S as c,X as re,Z as l,it as u,j as d,m as f,w as p,y as m,z as h}from"./apple-runner-platform.js";import"./runner-toolchain-probe.js";import{i as g}from"./runner-device-set.js";import ie from"node:crypto";import _ from"node:fs";import ae from"node:os";import v from"node:path";const oe=Symbol(`apple-runner-bad-artifacts`),y=()=>re(oe,()=>new Set);function b(e){return v.join(e,n)}function se(e,t){_.mkdirSync(e,{recursive:!0}),_.writeFileSync(b(e),`${JSON.stringify(t,null,2)}\n`)}async function ce(e,t){if(e.cache===`external`){O(`preserve`,`external_bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t});return}y().add(e.derived),await u({acquire:()=>x(e.derived),task:async()=>{O(`clean`,`bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t}),D(e.derived),T(e.derived)}})}async function x(e,t=6e5){return await f({lockDirPath:le(e),owner:{pid:process.pid,startTime:o(process.pid),acquiredAtMs:Date.now()},timeoutMs:t,pollMs:100,description:`iOS runner cache lock`})}function le(e){return v.join(v.dirname(e),`${v.basename(e)}.lock`)}function S(e,t){!pe()&&!t&&!y().has(e)||(O(`clean`,t?`forced_rebuild`:`forced_clean`,{derived:e}),D(e),T(e),y().delete(e))}async function C(e,t,n,r){let{buildRunnerCacheArtifactManifest:i}=await import(`./runner-artifact-manifest.js`),a=i(e,n,r);return se(e,a.ok?{...t,artifacts:a.artifacts}:t),a.ok?null:(O(`preserve`,`uncertifiable_products`,{derived:e,xctestrunPath:n,...a.refusal?{refusal:a.refusal}:{}}),a.refusal)}function w(t,n){if(t)throw new e(`COMMAND_FAILED`,`The Apple runner products cannot be certified for cache reuse`,{reason:`runner_cache_uncertifiable`,refusalReason:t.reason,refusingPath:t.path??n,...t.reason===`root_unusable`?{}:{resolvesTo:t.target},derived:n,hint:`Inspect ${t.path??n} under ${n}. A symlinked or unreadable product tree must be replaced; run pnpm build:xcuitest with a clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH.`})}function T(e){try{if(!_.existsSync(e))return;if(v.basename(e)!==`derived`){_.rmSync(e,{recursive:!0,force:!0});return}for(let t of _.readdirSync(e,{withFileTypes:!0}))ue(t.name)&&_.rmSync(v.join(e,t.name),{recursive:!0,force:!0})}catch{}}const E=new Set([n,`Build`,`BuildCache.noindex`,`Index.noindex`,`Logs`,`ModuleCache.noindex`,`SDKStatCaches.noindex`,`SourcePackages`,`TextBasedInstallAPI`,`info.plist`]);function ue(e){return E.has(e)}function de(e){try{let t=JSON.parse(_.readFileSync(b(e),`utf8`));return!t||typeof t!=`object`||Array.isArray(t)?null:t}catch{return null}}function fe(e,n){let a=de(e);return a?i(r(a))===i(r(n))?{ok:!0,metadata:a}:{ok:!1,reason:`cache_metadata_mismatch`,differences:t(n,a)}:{ok:!1,reason:`cache_metadata_missing`}}function pe(){return a(s().env.AGENT_DEVICE_IOS_CLEAN_DERIVED)}function D(t,n=s().env){if(n.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!me(t))throw new e(`COMMAND_FAILED`,`Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically`,{derivedPath:t,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${v.join(p(),`.tmp`)}.`})}function me(e){let t=v.resolve(p(),`.tmp`),n=v.relative(t,v.resolve(e));return n!==``&&!n.startsWith(`..`)&&!v.isAbsolute(n)}async function he(e){let t=fe(e.derived,e.expectedCacheMetadata);if(!t.ok)return t.reason===`cache_metadata_mismatch`?{reason:t.reason,xctestrunPath:null,productPaths:[],metadataDifferences:t.differences}:{reason:t.reason,xctestrunPath:null,productPaths:[]};let{validateRunnerCacheArtifactManifest:n}=await import(`./runner-artifact-manifest.js`),r=n(e.derived,t.metadata);return r.ok?{reason:`reuse_ready`,xctestrunPath:r.xctestrunPath,productPaths:r.productPaths}:r.mismatch?{reason:`artifact_content_mismatch`,xctestrunPath:null,productPaths:[],mismatch:r.mismatch}:{reason:`artifact_manifest_missing`,xctestrunPath:null,productPaths:[]}}function ge(e,t){O(`rebuild`,e.reason,{derived:t,...e.reason===`cache_metadata_mismatch`?{metadataDifferences:e.metadataDifferences}:{},...e.reason===`artifact_content_mismatch`?{mismatch:e.mismatch}:{}})}function O(e,t,n){c({level:e===`rebuild`||e===`preserve`?`warn`:`info`,phase:`runner_xctestrun_cache`,data:{action:e,reason:t,...n}})}const k=process.pid;let A;function j(){return A??={value:o(process.pid)},A.value}function M(){return Ue(k,j())}function N(e){return e.deviceClaimProtocol===1}function P(e){let t=q(e.runnerLogPath);return{schemaVersion:1,deviceId:e.device.id,ownerToken:M(),ownerPid:k,ownerStartTime:j(),ownerStateDir:R(),sessionId:e.sessionId,runnerPid:e.runnerPid??null,runnerStartTime:e.runnerPid?o(e.runnerPid):null,port:e.endpoint.port,runnerToken:e.endpoint.token,xctestrunPath:e.xctestrunPath,cacheKey:e.cacheKey,jsonPath:e.jsonPath,...t?{runnerLogPath:t}:{},...J(g(e.device)),createdAtMs:Date.now(),deviceClaimProtocol:1}}async function F(e,t){return await u({acquire:()=>f({lockDirPath:`${H(e)}.lock`,owner:{pid:k,startTime:j(),acquiredAtMs:Date.now()},timeoutMs:3e4,pollMs:100,description:`iOS runner lease for ${e}`}),task:t})}function I(e){try{return G(JSON.parse(_.readFileSync(H(e),`utf8`)),e)}catch{return null}}function L(e){if(!e)return{type:`empty`};if(e.ownerToken===M())return{type:`owned`,lease:e};let t=m({owner:{pid:e.ownerPid,startTime:e.ownerStartTime},...e.ownerStateDir?{stateDir:e.ownerStateDir}:{}});return t!==`live`&&t!==`unknown`?{type:`stale`,lease:e,staleReason:t}:{type:`busy`,lease:e}}async function _e(t,n,r){let i=t.id,a=L(I(i));if(a.type!==`empty`){if(a.type===`busy`){if(ve(a.lease)){await Z(a.lease,`same-state-dir`,n);return}if(ye(a.lease,t)){await Z(a.lease,`device-claim-takeover`,n);return}if(be(a.lease,r)){await Z(a.lease,`logical-lease-takeover`,n);return}throw new e(`COMMAND_FAILED`,r?`iOS runner for ${i} is busy after device lease admission`:`iOS runner for ${i} is already owned by another agent-device daemon`,{reason:`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,deviceId:i,logicalLeaseContext:r,ownerPid:a.lease.ownerPid,ownerStartTime:a.lease.ownerStartTime,ownerStateDir:a.lease.ownerStateDir,ownerToken:a.lease.ownerToken,sessionId:a.lease.sessionId,hint:Se(a.lease,r)})}await Z(a.lease,a.type,n)}}function ve(e){let t=R();return!t||!e.ownerStateDir?!1:v.resolve(t)===v.resolve(e.ownerStateDir)}function ye(e,t){return N(e)&&e.deviceId===t.id&&ee(t)}function be(e,t){return!t||t.leaseProvider!==`proxy`||!t.leaseId||!t.clientId?!1:xe(t.deviceKey,e.deviceId)}function xe(e,t){if(!e)return!1;if(e===t)return!0;let[,,n]=e.split(`:`,3);return n===t}function R(){return te()||s().env.AGENT_DEVICE_STATE_DIR?.trim()||void 0}function Se(e,t){let n=Ce(e),r=we(e);return t?[r,n,`The device is busy because another active device lease owns it, or the runner is owned by another daemon/process after lease admission.`,`Retry after the owning session closes or after the five-minute inactivity lease expires.`].join(` `):[r,n,`If the runner is still active, wait for it to finish. Do not run prepare ios-runner from another daemon/client to recover this.`].join(` `)}function Ce(e){let t=`Runner owner: PID ${e.ownerPid}`;return e.ownerStateDir?`${t} with AGENT_DEVICE_STATE_DIR=${e.ownerStateDir}`:`${t}.`}function we(e){return e.ownerStateDir?`If it is stuck, stop the owning agent-device daemon for ${Te(`AGENT_DEVICE_STATE_DIR`,e.ownerStateDir)} and retry.`:`If it is stuck, stop the owning agent-device daemon and retry.`}function Te(e,t){return`${e}=${l(t)}`}function z(e){return e.runnerToken?{port:e.port,token:e.runnerToken}:null}function B(e){let t=L(I(e));switch(t.type){case`empty`:return{type:`absent`};case`owned`:return{type:`refused`,reason:`lease_owned_by_this_daemon`,lease:t.lease};case`busy`:return{type:`refused`,reason:`lease_owner_live`,lease:t.lease};case`stale`:return t.staleReason===`owner-state-dir-gone`?{type:`refused`,reason:`lease_owner_state_dir_gone`,lease:t.lease}:{type:`adoptable`,lease:t.lease}}}function Ee(e){let t=B(e);return t.type===`adoptable`?t.lease:null}function De(e){return{...e,ownerToken:`detached-${e.ownerToken}`}}async function Oe(e,t){let n=L(I(e));n.type===`owned`&&await Z(n.lease,`owned`,t)}async function ke(e,t){if(!Number.isInteger(e.pid)||e.pid<=0)return;let n=Ne(e);await Promise.all(n.map(async e=>{await Z(e,`owned`,t)}))}function Ae(e){return I(e)?.ownerToken??null}function V(e){e&&Me({deviceId:e.deviceId,ownerToken:e.ownerToken,sessionId:e.sessionId})}function je(e){let t=H(e.deviceId);_.mkdirSync(v.dirname(t),{recursive:!0}),ne({destination:t,contents:JSON.stringify(e,null,2),mode:384})}function Me(e){let t=I(e.deviceId);if(t&&!(e.ownerToken&&t.ownerToken!==e.ownerToken)&&!(e.sessionId&&t.sessionId!==e.sessionId))try{_.unlinkSync(H(e.deviceId))}catch{}}function H(e){return v.join(U(),`${We(e)}.json`)}function U(){let e=s().env.AGENT_DEVICE_IOS_RUNNER_LEASE_DIR?.trim();return e?v.resolve(e):v.join(ae.homedir(),`.agent-device`,`apple-runner`,`leases`)}function Ne(e){return W({strict:!1}).filter(t=>t.ownerPid===e.pid&&(e.startTime===void 0||t.ownerStartTime===e.startTime))}function W(e){let t=e.strict?Fe:Pe,n=U(),r=t(()=>_.readdirSync(n,{withFileTypes:!0}))??[],i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.json`))continue;let r=t(()=>_.readFileSync(v.join(n,e.name),`utf8`)),a=r===null?null:Re(r);a&&i.push(a)}return i}function Pe(e){try{return e()}catch{return null}}function Fe(e){try{return e()}catch(e){if(e.code===`ENOENT`)return null;throw e}}function Ie(){return W({strict:!0}).filter(e=>!Le(e)).map(({xctestrunPath:e,cacheKey:t})=>({xctestrunPath:e,cacheKey:t}))}function Le(e){let t=L(e);if(t.type!==`stale`||t.staleReason===`owner-state-dir-gone`)return!1;if(e.runnerPid===null)return!0;let n=m({owner:{pid:e.runnerPid,startTime:e.runnerStartTime}});return n===`owner-process-dead`||n===`owner-process-reused`}function Re(e){try{let t=JSON.parse(e),n=K(t.deviceId);return n?G(t,n):null}catch{return null}}function G(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.schemaVersion!==1||n.deviceId!==t)return null;let r=ze(n);return r?{schemaVersion:1,deviceId:t,...r,ownerStartTime:Y(n.ownerStartTime),ownerStateDir:Y(n.ownerStateDir)??void 0,runnerPid:X(n.runnerPid),runnerStartTime:Y(n.runnerStartTime),runnerLogPath:q(n.runnerLogPath),runnerToken:q(n.runnerToken),cacheKey:q(n.cacheKey),...J(n.simulatorSetPath),...n.deviceClaimProtocol===1?{deviceClaimProtocol:1}:{}}:null}function ze(e){let t={ownerToken:K(e.ownerToken),ownerPid:X(e.ownerPid),sessionId:K(e.sessionId),port:X(e.port),xctestrunPath:K(e.xctestrunPath),jsonPath:K(e.jsonPath),createdAtMs:Be(e.createdAtMs)};return Object.values(t).some(e=>e===null)?null:t}function K(e){return typeof e==`string`&&e.length>0?e:null}function q(e){return K(e)??void 0}function J(e){let t=K(e);return t?{simulatorSetPath:t}:{}}function Y(e){return typeof e==`string`?e:null}function X(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Be(e){return typeof e==`number`&&Number.isFinite(e)?e:null}async function Z(e,t,n){c({level:t===`owned`?`debug`:`warn`,phase:`ios_runner_lease_cleanup`,data:{deviceId:e.deviceId,ownerPid:e.ownerPid,ownerStateDir:e.ownerStateDir,ownerToken:e.ownerToken,runnerPid:e.runnerPid,sessionId:e.sessionId,reason:t}}),await n.cleanupRunnerProcessTree(Q(e),`SIGTERM`),await n.cleanupRunnerXcodebuildProcesses({deviceId:e.deviceId,xctestrunPath:e.xctestrunPath}),await n.cleanupRunnerProcessTree(Q(e),`SIGKILL`),n.cleanupTempFile(e.xctestrunPath),n.cleanupTempFile(e.jsonPath),V(e)}function Ve(e,t){return d(t)&&$(e,t)}function Q(e){let t=e.runnerPid??void 0;if(!(!t||!d(t))){if($(e,t))return t;c({level:`warn`,phase:`ios_runner_lease_recycled_pid_skipped`,data:{deviceId:e.deviceId,runnerPid:t,runnerStartTime:e.runnerStartTime,sessionId:e.sessionId}})}}function $(e,t){return e.runnerStartTime?o(t)===e.runnerStartTime:He(h(t))}function He(e){return!!e&&e.includes(`xcodebuild`)&&e.includes(`AgentDeviceRunner`)}function Ue(e,t){let n=ie.createHash(`sha256`);return n.update(String(e)),n.update(`\0`),n.update(t??`unknown-start`),`owner-${e}-${n.digest(`hex`).slice(0,8)}`}function We(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,`-`)||`unknown-device`}export{he as C,C as D,b as E,ge as S,w as T,x as _,Ae as a,S as b,Ie as c,Ee as d,V as f,je as g,F as h,ke as i,_e as l,$ as m,P as n,Ve as o,M as p,Oe as r,z as s,De as t,B as u,D as v,ce as w,O as x,T as y};
1
+ import{R as e}from"./sdk-contracts.js";import{b as t,i as n,n as r,r as i}from"./runner.js";import{B as a,C as o,O as s,T as ee,f as c,g as l,k as u,m as te,n as d,q as f,s as p,u as m,v as ne,y as h,z as re}from"./host2.js";import{s as ie}from"./apple-runner-platform.js";import"./runner-toolchain-probe.js";import{i as ae}from"./runner-device-set.js";import oe from"node:crypto";import g from"node:fs";import _ from"node:os";import v from"node:path";const y=Symbol(`apple-runner-bad-artifacts`),b=()=>re(y,()=>new Set);function x(e){return v.join(e,r)}function se(e,t){g.mkdirSync(e,{recursive:!0}),g.writeFileSync(x(e),`${JSON.stringify(t,null,2)}\n`)}async function ce(e,t){if(e.cache===`external`){O(`preserve`,`external_bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t});return}b().add(e.derived),await f({acquire:()=>S(e.derived),task:async()=>{O(`clean`,`bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t}),E(e.derived),T(e.derived)}})}async function S(e,t=6e5){return await d({lockDirPath:C(e),owner:{pid:process.pid,startTime:u(process.pid),acquiredAtMs:Date.now()},timeoutMs:t,pollMs:100,description:`iOS runner cache lock`})}function C(e){return v.join(v.dirname(e),`${v.basename(e)}.lock`)}function w(e,t){!he()&&!t&&!b().has(e)||(O(`clean`,t?`forced_rebuild`:`forced_clean`,{derived:e}),E(e),T(e),b().delete(e))}async function le(e,t,n,r){let{buildRunnerCacheArtifactManifest:i}=await import(`./runner-artifact-manifest.js`),a=i(e,n,r);return se(e,a.ok?{...t,artifacts:a.artifacts}:t),a.ok?null:(O(`preserve`,`uncertifiable_products`,{derived:e,xctestrunPath:n,...a.refusal?{refusal:a.refusal}:{}}),a.refusal)}function ue(t,n){if(t)throw new e(`COMMAND_FAILED`,`The Apple runner products cannot be certified for cache reuse`,{reason:`runner_cache_uncertifiable`,refusalReason:t.reason,refusingPath:t.path??n,...t.reason===`root_unusable`?{}:{resolvesTo:t.target},derived:n,hint:`Inspect ${t.path??n} under ${n}. A symlinked or unreadable product tree must be replaced; run pnpm build:xcuitest with a clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH.`})}function T(e){try{if(!g.existsSync(e))return;if(v.basename(e)!==`derived`){g.rmSync(e,{recursive:!0,force:!0});return}for(let t of g.readdirSync(e,{withFileTypes:!0}))fe(t.name)&&g.rmSync(v.join(e,t.name),{recursive:!0,force:!0})}catch{}}const de=new Set([r,`Build`,`BuildCache.noindex`,`Index.noindex`,`Logs`,`ModuleCache.noindex`,`SDKStatCaches.noindex`,`SourcePackages`,`TextBasedInstallAPI`,`info.plist`]);function fe(e){return de.has(e)}function pe(e){try{let t=JSON.parse(g.readFileSync(x(e),`utf8`));return!t||typeof t!=`object`||Array.isArray(t)?null:t}catch{return null}}function me(e,r){let a=pe(e);return a?t(i(a))===t(i(r))?{ok:!0,metadata:a}:{ok:!1,reason:`cache_metadata_mismatch`,differences:n(r,a)}:{ok:!1,reason:`cache_metadata_missing`}}function he(){return ne(l().env.AGENT_DEVICE_IOS_CLEAN_DERIVED)}function E(t,n=l().env){if(ie(n)&&!ge(t))throw new e(`COMMAND_FAILED`,`Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically`,{derivedPath:t,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${v.join(c(),`.tmp`)}.`})}function ge(e){let t=v.resolve(c(),`.tmp`),n=v.relative(t,v.resolve(e));return n!==``&&!n.startsWith(`..`)&&!v.isAbsolute(n)}async function _e(e){let t=me(e.derived,e.expectedCacheMetadata);if(!t.ok)return t.reason===`cache_metadata_mismatch`?{reason:t.reason,xctestrunPath:null,productPaths:[],metadataDifferences:t.differences}:{reason:t.reason,xctestrunPath:null,productPaths:[]};let{validateRunnerCacheArtifactManifest:n}=await import(`./runner-artifact-manifest.js`),r=n(e.derived,t.metadata);return r.ok?{reason:`reuse_ready`,xctestrunPath:r.xctestrunPath,productPaths:r.productPaths}:r.mismatch?{reason:`artifact_content_mismatch`,xctestrunPath:null,productPaths:[],mismatch:r.mismatch}:{reason:`artifact_manifest_missing`,xctestrunPath:null,productPaths:[]}}function D(e,t){O(`rebuild`,e.reason,{derived:t,...e.reason===`cache_metadata_mismatch`?{metadataDifferences:e.metadataDifferences}:{},...e.reason===`artifact_content_mismatch`?{mismatch:e.mismatch}:{}})}function O(e,t,n){m({level:e===`rebuild`||e===`preserve`?`warn`:`info`,phase:`runner_xctestrun_cache`,data:{action:e,reason:t,...n}})}const k=process.pid;let A;function j(){return A??={value:u(process.pid)},A.value}function M(){return We(k,j())}function N(e){return e.deviceClaimProtocol===1}function P(e){let t=q(e.runnerLogPath);return{schemaVersion:1,deviceId:e.device.id,ownerToken:M(),ownerPid:k,ownerStartTime:j(),ownerStateDir:R(),sessionId:e.sessionId,runnerPid:e.runnerPid??null,runnerStartTime:e.runnerPid?u(e.runnerPid):null,port:e.endpoint.port,runnerToken:e.endpoint.token,xctestrunPath:e.xctestrunPath,cacheKey:e.cacheKey,jsonPath:e.jsonPath,...t?{runnerLogPath:t}:{},...J(ae(e.device)),createdAtMs:Date.now(),deviceClaimProtocol:1}}async function F(e,t){return await f({acquire:()=>d({lockDirPath:`${H(e)}.lock`,owner:{pid:k,startTime:j(),acquiredAtMs:Date.now()},timeoutMs:3e4,pollMs:100,description:`iOS runner lease for ${e}`}),task:t})}function I(e){try{return G(JSON.parse(g.readFileSync(H(e),`utf8`)),e)}catch{return null}}function L(e){if(!e)return{type:`empty`};if(e.ownerToken===M())return{type:`owned`,lease:e};let t=p({owner:{pid:e.ownerPid,startTime:e.ownerStartTime},...e.ownerStateDir?{stateDir:e.ownerStateDir}:{}});return t!==`live`&&t!==`unknown`?{type:`stale`,lease:e,staleReason:t}:{type:`busy`,lease:e}}async function ve(t,n,r){let i=t.id,a=L(I(i));if(a.type!==`empty`){if(a.type===`busy`){if(ye(a.lease)){await Z(a.lease,`same-state-dir`,n);return}if(be(a.lease,t)){await Z(a.lease,`device-claim-takeover`,n);return}if(xe(a.lease,r)){await Z(a.lease,`logical-lease-takeover`,n);return}throw new e(`COMMAND_FAILED`,r?`iOS runner for ${i} is busy after device lease admission`:`iOS runner for ${i} is already owned by another agent-device daemon`,{reason:`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,deviceId:i,logicalLeaseContext:r,ownerPid:a.lease.ownerPid,ownerStartTime:a.lease.ownerStartTime,ownerStateDir:a.lease.ownerStateDir,ownerToken:a.lease.ownerToken,sessionId:a.lease.sessionId,hint:Ce(a.lease,r)})}await Z(a.lease,a.type,n)}}function ye(e){let t=R();return!t||!e.ownerStateDir?!1:v.resolve(t)===v.resolve(e.ownerStateDir)}function be(e,t){return N(e)&&e.deviceId===t.id&&te(t)}function xe(e,t){return!t||t.leaseProvider!==`proxy`||!t.leaseId||!t.clientId?!1:Se(t.deviceKey,e.deviceId)}function Se(e,t){if(!e)return!1;if(e===t)return!0;let[,,n]=e.split(`:`,3);return n===t}function R(){return o()||l().env.AGENT_DEVICE_STATE_DIR?.trim()||void 0}function Ce(e,t){let n=we(e),r=Te(e);return t?[r,n,`The device is busy because another active device lease owns it, or the runner is owned by another daemon/process after lease admission.`,`Retry after the owning session closes or after the five-minute inactivity lease expires.`].join(` `):[r,n,`If the runner is still active, wait for it to finish. Do not run prepare ios-runner from another daemon/client to recover this.`].join(` `)}function we(e){let t=`Runner owner: PID ${e.ownerPid}`;return e.ownerStateDir?`${t} with AGENT_DEVICE_STATE_DIR=${e.ownerStateDir}`:`${t}.`}function Te(e){return e.ownerStateDir?`If it is stuck, stop the owning agent-device daemon for ${Ee(`AGENT_DEVICE_STATE_DIR`,e.ownerStateDir)} and retry.`:`If it is stuck, stop the owning agent-device daemon and retry.`}function Ee(e,t){return`${e}=${a(t)}`}function De(e){return e.runnerToken?{port:e.port,token:e.runnerToken}:null}function z(e){let t=L(I(e));switch(t.type){case`empty`:return{type:`absent`};case`owned`:return{type:`refused`,reason:`lease_owned_by_this_daemon`,lease:t.lease};case`busy`:return{type:`refused`,reason:`lease_owner_live`,lease:t.lease};case`stale`:return t.staleReason===`owner-state-dir-gone`?{type:`refused`,reason:`lease_owner_state_dir_gone`,lease:t.lease}:{type:`adoptable`,lease:t.lease}}}function B(e){let t=z(e);return t.type===`adoptable`?t.lease:null}function Oe(e){return{...e,ownerToken:`detached-${e.ownerToken}`}}async function ke(e,t){let n=L(I(e));n.type===`owned`&&await Z(n.lease,`owned`,t)}async function Ae(e,t){if(!Number.isInteger(e.pid)||e.pid<=0)return;let n=Pe(e);await Promise.all(n.map(async e=>{await Z(e,`owned`,t)}))}function je(e){return I(e)?.ownerToken??null}function V(e){e&&Ne({deviceId:e.deviceId,ownerToken:e.ownerToken,sessionId:e.sessionId})}function Me(e){let t=H(e.deviceId);g.mkdirSync(v.dirname(t),{recursive:!0}),ee({destination:t,contents:JSON.stringify(e,null,2),mode:384})}function Ne(e){let t=I(e.deviceId);if(t&&!(e.ownerToken&&t.ownerToken!==e.ownerToken)&&!(e.sessionId&&t.sessionId!==e.sessionId))try{g.unlinkSync(H(e.deviceId))}catch{}}function H(e){return v.join(U(),`${Ge(e)}.json`)}function U(){let e=l().env.AGENT_DEVICE_IOS_RUNNER_LEASE_DIR?.trim();return e?v.resolve(e):v.join(_.homedir(),`.agent-device`,`apple-runner`,`leases`)}function Pe(e){return W({strict:!1}).filter(t=>t.ownerPid===e.pid&&(e.startTime===void 0||t.ownerStartTime===e.startTime))}function W(e){let t=e.strict?Ie:Fe,n=U(),r=t(()=>g.readdirSync(n,{withFileTypes:!0}))??[],i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.json`))continue;let r=t(()=>g.readFileSync(v.join(n,e.name),`utf8`)),a=r===null?null:ze(r);a&&i.push(a)}return i}function Fe(e){try{return e()}catch{return null}}function Ie(e){try{return e()}catch(e){if(e.code===`ENOENT`)return null;throw e}}function Le(){return W({strict:!0}).filter(e=>!Re(e)).map(({xctestrunPath:e,cacheKey:t})=>({xctestrunPath:e,cacheKey:t}))}function Re(e){let t=L(e);if(t.type!==`stale`||t.staleReason===`owner-state-dir-gone`)return!1;if(e.runnerPid===null)return!0;let n=p({owner:{pid:e.runnerPid,startTime:e.runnerStartTime}});return n===`owner-process-dead`||n===`owner-process-reused`}function ze(e){try{let t=JSON.parse(e),n=K(t.deviceId);return n?G(t,n):null}catch{return null}}function G(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.schemaVersion!==1||n.deviceId!==t)return null;let r=Be(n);return r?{schemaVersion:1,deviceId:t,...r,ownerStartTime:Y(n.ownerStartTime),ownerStateDir:Y(n.ownerStateDir)??void 0,runnerPid:X(n.runnerPid),runnerStartTime:Y(n.runnerStartTime),runnerLogPath:q(n.runnerLogPath),runnerToken:q(n.runnerToken),cacheKey:q(n.cacheKey),...J(n.simulatorSetPath),...n.deviceClaimProtocol===1?{deviceClaimProtocol:1}:{}}:null}function Be(e){let t={ownerToken:K(e.ownerToken),ownerPid:X(e.ownerPid),sessionId:K(e.sessionId),port:X(e.port),xctestrunPath:K(e.xctestrunPath),jsonPath:K(e.jsonPath),createdAtMs:Ve(e.createdAtMs)};return Object.values(t).some(e=>e===null)?null:t}function K(e){return typeof e==`string`&&e.length>0?e:null}function q(e){return K(e)??void 0}function J(e){let t=K(e);return t?{simulatorSetPath:t}:{}}function Y(e){return typeof e==`string`?e:null}function X(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Ve(e){return typeof e==`number`&&Number.isFinite(e)?e:null}async function Z(e,t,n){m({level:t===`owned`?`debug`:`warn`,phase:`ios_runner_lease_cleanup`,data:{deviceId:e.deviceId,ownerPid:e.ownerPid,ownerStateDir:e.ownerStateDir,ownerToken:e.ownerToken,runnerPid:e.runnerPid,sessionId:e.sessionId,reason:t}}),await n.cleanupRunnerProcessTree(Q(e),`SIGTERM`),await n.cleanupRunnerXcodebuildProcesses({deviceId:e.deviceId,xctestrunPath:e.xctestrunPath}),await n.cleanupRunnerProcessTree(Q(e),`SIGKILL`),n.cleanupTempFile(e.xctestrunPath),n.cleanupTempFile(e.jsonPath),V(e)}function He(e,t){return h(t)&&$(e,t)}function Q(e){let t=e.runnerPid??void 0;if(!(!t||!h(t))){if($(e,t))return t;m({level:`warn`,phase:`ios_runner_lease_recycled_pid_skipped`,data:{deviceId:e.deviceId,runnerPid:t,runnerStartTime:e.runnerStartTime,sessionId:e.sessionId}})}}function $(e,t){return e.runnerStartTime?u(t)===e.runnerStartTime:Ue(s(t))}function Ue(e){return!!e&&e.includes(`xcodebuild`)&&e.includes(`AgentDeviceRunner`)}function We(e,t){let n=oe.createHash(`sha256`);return n.update(String(e)),n.update(`\0`),n.update(t??`unknown-start`),`owner-${e}-${n.digest(`hex`).slice(0,8)}`}function Ge(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,`-`)||`unknown-device`}export{_e as C,le as D,x as E,D as S,ue as T,S as _,je as a,w as b,Le as c,B as d,V as f,Me as g,F as h,Ae as i,ve as l,$ as m,P as n,He as o,M as p,ke as r,De as s,Oe as t,z as u,E as v,ce as w,O as x,T as y};
@@ -1 +1 @@
1
- import{_ as e,a as t,c as n,g as r,o as i,s as a,u as o,v as s}from"./runner.js";import{r as c,u as l}from"./apple-runner-platform.js";import{C as u,D as d,O as f,a as p,c as m,d as h,f as g,i as _,l as v,n as y,o as b,p as x,r as S,s as C,u as w}from"./runner-client.js";import{D as T,T as E,d as D,m as O}from"./runner-lease.js";async function k(e){let{cleanupRunnerLeasesForOwner:t}=await import(`./runner-client.js`).then(e=>e.t),{runnerLeaseCleanupAdapter:n}=await import(`./runner-client.js`).then(e=>e.m);await t(e,n)}export{d as applyXctestRunnerAppIconFromDerivedPath,k as cleanupRunnerLeasesForOwner,v as detachIosRunnerSessionsForShutdown,u as findRunnerXctestrun,y as hasLiveIosRunnerSession,c as isRunnerXcuitestScriptPlatform,S as notifyIosRunnerAppRelaunched,_ as prepareIosRunner,p as prewarmAppleRunnerCache,b as prewarmIosRunnerSession,w as readRunnerSessionLiveness,D as readStaleRunnerLease,h as releaseIosRunnerOnClose,C as releaseSpeculativeIosRunnerSessionFor,E as requireCertifiedRunnerCacheArtifacts,t as requireRunnerBuildSettingsMatchBuildLog,f as resolveExistingRunnerProductPaths,i as resolveExpectedRunnerCacheMetadata,a as resolveRunnerAppBundleId,n as resolveRunnerArchBuildSettings,o as resolveRunnerBundleBuildSettings,r as resolveRunnerPerformanceBuildSettings,e as resolveRunnerSandboxBuildArgs,l as resolveRunnerScriptDevice,s as resolveRunnerSigningBuildSettings,m as runAppleRunnerCommand,g as stopAllIosRunnerSessions,x as stopIosRunnerSession,O as verifyLeaseRunnerPidIdentity,T as writeRunnerCacheMetadataForArtifacts};
1
+ import{_ as e,a as t,c as n,g as r,o as i,s as a,u as o,v as s,y as c}from"./runner.js";import{d as l,r as u,s as d}from"./apple-runner-platform.js";import{C as f,D as p,O as m,a as h,c as g,d as _,f as v,i as y,l as b,n as x,o as S,p as C,r as w,s as T,u as E}from"./runner-client.js";import{D,T as O,d as k,m as A}from"./runner-lease.js";async function j(e){let{cleanupRunnerLeasesForOwner:t}=await import(`./runner-client.js`).then(e=>e.t),{runnerLeaseCleanupAdapter:n}=await import(`./runner-client.js`).then(e=>e.m);await t(e,n)}export{p as applyXctestRunnerAppIconFromDerivedPath,j as cleanupRunnerLeasesForOwner,b as detachIosRunnerSessionsForShutdown,f as findRunnerXctestrun,x as hasLiveIosRunnerSession,u as isRunnerXcuitestScriptPlatform,w as notifyIosRunnerAppRelaunched,y as prepareIosRunner,h as prewarmAppleRunnerCache,S as prewarmIosRunnerSession,E as readRunnerSessionLiveness,k as readStaleRunnerLease,_ as releaseIosRunnerOnClose,T as releaseSpeculativeIosRunnerSessionFor,O as requireCertifiedRunnerCacheArtifacts,t as requireRunnerBuildSettingsMatchBuildLog,m as resolveExistingRunnerProductPaths,i as resolveExpectedRunnerCacheMetadata,a as resolveRunnerAppBundleId,n as resolveRunnerArchBuildSettings,o as resolveRunnerBundleBuildSettings,d as resolveRunnerDerivedOverride,r as resolveRunnerPerformanceBuildSettings,e as resolveRunnerSandboxBuildArgs,s as resolveRunnerScriptDefaultDerivedPath,l as resolveRunnerScriptDevice,c as resolveRunnerSigningBuildSettings,g as runAppleRunnerCommand,v as stopAllIosRunnerSessions,C as stopIosRunnerSession,A as verifyLeaseRunnerPidIdentity,D as writeRunnerCacheMetadataForArtifacts};
@@ -1 +1 @@
1
- import{_ as e}from"./sdk-device.js";import{O as t,S as n}from"./apple-runner-platform.js";import{v as r}from"./runner-client.js";import i from"node:net";function a(e,t){if(e.state!==`ready`||!s(e)||e.listenerWatch)return;let r=i.connect(e.endpoint.port,`127.0.0.1`);r.unref();let a,o=new Promise(e=>{a=e}),c=setTimeout(()=>r.destroy(),500);c.unref();let l={lost:!1,ready:o,close(){clearTimeout(c),l.lost=!0,a(!1),r.removeAllListeners(),r.on(`error`,()=>{}),r.destroy()}};e.listenerWatch=l,r.on(`connect`,()=>{clearTimeout(c),a(!0)}),r.on(`error`,()=>{}),r.on(`close`,()=>{clearTimeout(c),l.lost=!0,a(!1),t()?.catch(t=>{n({level:`warn`,phase:`ios_runner_warm_stop_failed`,data:{deviceId:e.deviceId,sessionId:e.sessionId,error:String(t)}})})})}async function o(e,t){if(e.state!==`ready`||r(e)||e.commandCharges.hasOutstandingCharges)return!1;if(s(e)){let t=e.listenerWatch;if(!t||!await t.ready||t.lost)return!1}if(e.state!==`ready`||r(e)||e.commandCharges.hasOutstandingCharges)return!1;e.retention?.cancel();let i,a={cancel(){clearTimeout(i),e.retention===a&&(e.retention=void 0)}};e.retention=a;let o=c();return o>0&&(i=setTimeout(()=>{t(a,`idle_timeout`).catch(t=>{n({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e.deviceId,sessionId:e.sessionId,error:String(t)}})})},o),i.unref(),n({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e.deviceId,sessionId:e.sessionId,idleMs:o}})),!0}function s(t){return t.device.kind===`simulator`&&e(t.device)}function c(e=t().env){let n=e.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS?.trim();if(n){let e=Number(n);if(Number.isFinite(e)&&e>=0)return Math.min(Math.floor(e),2**31-1)}return 3e5}export{a as observeRunnerListener,o as retainRunnerSession};
1
+ import{w as e}from"./sdk-device.js";import{g as t,u as n}from"./host2.js";import{v as r}from"./runner-client.js";import i from"node:net";function a(e,t){if(e.state!==`ready`||!s(e)||e.listenerWatch)return;let r=i.connect(e.endpoint.port,`127.0.0.1`);r.unref();let a,o=new Promise(e=>{a=e}),c=setTimeout(()=>r.destroy(),500);c.unref();let l={lost:!1,ready:o,close(){clearTimeout(c),l.lost=!0,a(!1),r.removeAllListeners(),r.on(`error`,()=>{}),r.destroy()}};e.listenerWatch=l,r.on(`connect`,()=>{clearTimeout(c),a(!0)}),r.on(`error`,()=>{}),r.on(`close`,()=>{clearTimeout(c),l.lost=!0,a(!1),t()?.catch(t=>{n({level:`warn`,phase:`ios_runner_warm_stop_failed`,data:{deviceId:e.deviceId,sessionId:e.sessionId,error:String(t)}})})})}async function o(e,t){if(e.state!==`ready`||r(e)||e.commandCharges.hasOutstandingCharges)return!1;if(s(e)){let t=e.listenerWatch;if(!t||!await t.ready||t.lost)return!1}if(e.state!==`ready`||r(e)||e.commandCharges.hasOutstandingCharges)return!1;e.retention?.cancel();let i,a={cancel(){clearTimeout(i),e.retention===a&&(e.retention=void 0)}};e.retention=a;let o=c();return o>0&&(i=setTimeout(()=>{t(a,`idle_timeout`).catch(t=>{n({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e.deviceId,sessionId:e.sessionId,error:String(t)}})})},o),i.unref(),n({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e.deviceId,sessionId:e.sessionId,idleMs:o}})),!0}function s(t){return t.device.kind===`simulator`&&e(t.device)}function c(e=t().env){let n=e.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS?.trim();if(n){let e=Number(n);if(Number.isFinite(e)&&e>=0)return Math.min(Math.floor(e),2**31-1)}return 3e5}export{a as observeRunnerListener,o as retainRunnerSession};
@@ -1 +1 @@
1
- import{h as e}from"./sdk-device.js";import{c as t}from"./runner-client.js";import{t as n}from"./ios-node-interpretation.js";async function r(r,i,a,o){let s=await t(r,{command:`querySelector`,selectorKey:i.key,selectorValue:i.value,appBundleId:a},o);return{...s,...Array.isArray(s.nodes)?{nodes:s.nodes.map(t=>n(t,{reactNativeValue:e(r)}))}:{}}}export{r as queryAppleRunnerSelector};
1
+ import{S as e}from"./sdk-device.js";import{c as t}from"./runner-client.js";import{t as n}from"./ios-node-interpretation.js";async function r(r,i,a,o){let s=await t(r,{command:`querySelector`,selectorKey:i.key,selectorValue:i.value,appBundleId:a},o);return{...s,...Array.isArray(s.nodes)?{nodes:s.nodes.map(t=>n(t,{reactNativeValue:e(r)}))}:{}}}export{r as queryAppleRunnerSelector};
@@ -1 +1 @@
1
- import{R as e,V as t,Z as n}from"./sdk-contracts.js";import{S as r}from"./apple-runner-platform.js";import{r as i}from"./runner-toolchain-probe.js";import{E as a,S as o,T as s,h as c,x as l,y as u}from"./runner-client.js";import{F as d,k as f}from"./runner-error-classification.js";function p(e){let t=u(e.startupTimeoutMs),n=t??6e5,r=new AbortController,a=setTimeout(()=>{r.abort(m(n,t!==void 0))},n);a.unref?.();let o=d(e),s=o?AbortSignal.any([o,r.signal]):r.signal;return{phase:i(n,s),timeoutMs:n,explicit:t!==void 0,exhausted:r.signal,close:()=>clearTimeout(a)}}function m(t,n){return new e(`COMMAND_FAILED`,`Apple runner start exceeded its ${n?`startup timeout`:`default start budget`} of ${t}ms`,{reason:`runner_start_budget_exhausted`,timeoutMs:t,retriable:!0,hint:n?"Raise the startup timeout, or run `prepare ios-runner` first so the runner is built before it is needed.":"Run `prepare ios-runner --timeout <ms>` so the cold build has a budget of your choosing; the session runner.log names the step that stalled."})}async function h(e,n,r){return r?await new Promise((i,u)=>{let d=r.aborted?`already-spent`:l(n,r),p=()=>{if(u(t(void 0,r.reason)),e.catch(_),f(r.reason)){d===`interested`&&a(n,r),s(n);return}o(n,r)&&c(n.deviceId)};r.aborted?p():r.addEventListener(`abort`,p,{once:!0}),e.then(i,u).finally(()=>{r.removeEventListener(`abort`,p),d===`interested`&&a(n,r)})}):await e}function g(e,t){let n=t.signal?void 0:d(t);if(!n||l(e,n)!==`interested`)return()=>{};let r=()=>{o(e,n)&&c(e.deviceId)};return n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r),a(e,n)}}function _(t){if(n(t))return;let i=t instanceof e?t:void 0;r({level:`warn`,phase:`ios_runner_detached_start_failed`,data:{code:i?.code,reason:i?.details?.reason,error:t instanceof Error?t.message:String(t)}})}export{p as openRunnerStartBudget,h as raceRunnerStartAgainstCaller,g as reserveRunnerStartOwnerInterest};
1
+ import{H as e,Q as t,R as n}from"./sdk-contracts.js";import{u as r}from"./host2.js";import{r as i}from"./runner-toolchain-probe.js";import{E as a,S as o,T as s,h as c,x as l,y as u}from"./runner-client.js";import{F as d,k as f}from"./runner-error-classification.js";function p(e){let t=u(e.startupTimeoutMs),n=t??6e5,r=new AbortController,a=setTimeout(()=>{r.abort(m(n,t!==void 0))},n);a.unref?.();let o=d(e),s=o?AbortSignal.any([o,r.signal]):r.signal;return{phase:i(n,s),timeoutMs:n,explicit:t!==void 0,exhausted:r.signal,close:()=>clearTimeout(a)}}function m(e,t){return new n(`COMMAND_FAILED`,`Apple runner start exceeded its ${t?`startup timeout`:`default start budget`} of ${e}ms`,{reason:`runner_start_budget_exhausted`,timeoutMs:e,retriable:!0,hint:t?"Raise the startup timeout, or run `prepare ios-runner` first so the runner is built before it is needed.":"Run `prepare ios-runner --timeout <ms>` so the cold build has a budget of your choosing; the session runner.log names the step that stalled."})}async function h(t,n,r){return r?await new Promise((i,u)=>{let d=r.aborted?`already-spent`:l(n,r),p=()=>{if(u(e(void 0,r.reason)),t.catch(_),f(r.reason)){d===`interested`&&a(n,r),s(n);return}o(n,r)&&c(n.deviceId)};r.aborted?p():r.addEventListener(`abort`,p,{once:!0}),t.then(i,u).finally(()=>{r.removeEventListener(`abort`,p),d===`interested`&&a(n,r)})}):await t}function g(e,t){let n=t.signal?void 0:d(t);if(!n||l(e,n)!==`interested`)return()=>{};let r=()=>{o(e,n)&&c(e.deviceId)};return n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r),a(e,n)}}function _(e){if(t(e))return;let i=e instanceof n?e:void 0;r({level:`warn`,phase:`ios_runner_detached_start_failed`,data:{code:i?.code,reason:i?.details?.reason,error:e instanceof Error?e.message:String(e)}})}export{p as openRunnerStartBudget,h as raceRunnerStartAgainstCaller,g as reserveRunnerStartOwnerInterest};
@@ -1 +1 @@
1
- import{K as e,R as t,V as n,W as r,Z as i}from"./sdk-contracts.js";import{v as a}from"./sdk-device.js";import{n as o}from"./entities.js";import{t as s}from"./parser.js";import{U as c,W as l,g as u,p as d,v as f}from"./apple-runner-platform.js";import{L as p,N as m,d as h,i as g,m as _,r as v,s as y,t as b,v as x}from"./runner-error-classification.js";import{n as S,r as C}from"./runner-device-set.js";import w from"node:fs";import ee from"node:os";import T from"node:path";import E from"node:net";import D from"node:http";async function te(){return await new Promise((e,n)=>{let r=E.createServer();r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i?.port){let t=i.port;r.close(()=>e(t))}else r.close(()=>n(new t(`COMMAND_FAILED`,`Failed to allocate port`)))}),r.on(`error`,n)})}function ne(e,t,n,r){t&&A(t,e),n&&A(n,e),r&&process.stderr.write(e)}const O=new Map,k=new Map;function A(e,t){let n=(O.get(e)??Promise.resolve()).then(()=>j(e,t),()=>j(e,t)).then(()=>{k.delete(e)},t=>{k.set(e,t)}).finally(()=>{O.get(e)===n&&O.delete(e)});O.set(e,n)}async function j(e,t){await w.promises.mkdir(T.dirname(e),{recursive:!0}),await w.promises.appendFile(e,t)}async function re(e,t={}){let n=AbortSignal.any([t.signal??new AbortController().signal,AbortSignal.timeout(t.timeoutMs??2e3)]);if(n.aborted)throw n.reason;let r=O.get(e);if(r){let e=()=>{};try{await Promise.race([r,new Promise((t,r)=>{e=()=>r(n.reason),n.addEventListener(`abort`,e,{once:!0})})])}finally{n.removeEventListener(`abort`,e)}}let i=k.get(e);if(i!==void 0)throw i}function ie(e){try{w.existsSync(e)&&w.unlinkSync(e)}catch{}}function ae(e,t){if(e)return e;let n=t.replaceAll(/[^A-Za-z0-9._-]/g,`_`);return T.join(ee.tmpdir(),`agent-device`,`apple-runner`,`logs`,`${n}.log`)}function oe(e,t){let n=0;try{n=w.fstatSync(t).size}catch{}return{logPath:e,startOffset:n}}function se(e){let t=e.pollMs??50,n=Buffer.alloc(65536),r=e.file.startOffset,i=null,a=null,o=!1,s=()=>{if(!o)try{i??=w.openSync(e.file.logPath,`r`);let t=w.fstatSync(i).size;for(t<r&&(r=0);r<t;){let a=Math.min(n.length,t-r),o=w.readSync(i,n,0,a,r);if(o<=0)break;r+=o,e.onOutput(n.toString(`utf8`,0,o)),t=w.fstatSync(i).size}}catch{l()}},c=()=>{o||(a=setTimeout(()=>{s(),c()},t),a.unref?.())};function l(){if(!o&&(o=!0,a&&clearTimeout(a),a=null,i!==null)){try{w.closeSync(i)}catch{}i=null}}return c(),{drain:()=>{s(),l()},stop:l}}function ce(e,t){if(!e)return``;let n=null;try{n=w.openSync(e.logPath,`r`);let r=w.fstatSync(n).size,i=Math.max(e.startOffset,r-t),a=r-i;if(a<=0)return``;let o=Buffer.alloc(a),s=w.readSync(n,o,0,a,i);return o.toString(`utf8`,0,Math.max(s,0))}catch{return``}finally{if(n!==null)try{w.closeSync(n)}catch{}}}const M=new Map;function N(e,t){let n,r=!1;return{markUsbmuxUnattached:()=>{r=!0},resolveRoute:async(i,a=!1)=>{if(ue(e))return de(t);let o=c(e);if(o.backend===`xctest`||!r)return le(e,t);if(!a){let r=fe(e.id);if(r)return F(t,r,!0);if(n!==void 0)return F(t,n,!1)}let{tunnelIp:s}=await o.resolveTunnel(e,i);return n=s,s&&pe(e.id,s),F(t,s,!1)}}}function P(e){M.delete(e)}function le(e,t){return{kind:`usbmux`,url:`usbmux://${e.id}:${t}/command`,cachedTunnelIp:!1}}function ue(e){return e.kind!==`device`||a(e)}function de(e){return{kind:`network`,url:`http://127.0.0.1:${e}/command`,cachedTunnelIp:!1}}function F(e,t,n){return{kind:`network`,url:t?`http://[${t}]:${e}/command`:null,cachedTunnelIp:n}}function fe(e){let t=M.get(e);return t?t.expiresAt<=Date.now()?(M.delete(e),null):t.ip:null}function pe(e,t){M.set(e,{ip:t,expiresAt:Date.now()+3e4})}const I=`Connect the device by cable, trust this Mac, keep it unlocked, and retry.`;async function me(e,t,n,r,i){let a=d.fromTimeoutMs(r);return await ge(e,t,await he(e,t,a.remainingMs(),i),n,a.remainingMs(),i)}async function he(e,n,r,i){let a=await L(e,r,i);try{await R(a,1,B(`ListDevices`));let e=_e((await z(a,r,i)).payload.toString(`utf8`),n);if(e!==void 0)return e;throw new t(`DEVICE_NOT_FOUND`,`iOS device is not available through usbmux`,{deviceId:n,backend:`xctest`,usbmuxDeviceAttached:!1,hint:I})}finally{a.destroy()}}async function ge(e,t,n,r,i,a){let o=await L(e,i,a);try{await R(o,2,B(`Connect`,{DeviceID:n,PortNumber:xe(r)}));let e=ye((await z(o,i,a)).payload.toString(`utf8`),`Number`);if(e!==0)throw be({result:e,udid:t,deviceId:n,port:r});return o}catch(e){throw o.destroy(),e}}async function L(e,r,i){if(U(r,`connect to usbmuxd`),i?.aborted)throw n();return await new Promise((a,o)=>{let s=E.createConnection(e),c=!1,l=setTimeout(()=>{p(new t(`COMMAND_FAILED`,`Timed out connecting to usbmuxd`,{backend:`xctest`,socketPath:e,timeoutMs:r}))},r),u=()=>p(),d=e=>p(e),f=()=>p(n()),p=e=>{c||(c=!0,clearTimeout(l),s.off(`connect`,u),s.off(`error`,d),i?.removeEventListener(`abort`,f),e?(s.destroy(),o(e)):a(s))};s.once(`connect`,u),s.once(`error`,d),i?.addEventListener(`abort`,f,{once:!0})})}async function R(e,t,n){let r=Buffer.from(n,`utf8`),i=Buffer.alloc(16+r.length);i.writeUInt32LE(i.length,0),i.writeUInt32LE(1,4),i.writeUInt32LE(8,8),i.writeUInt32LE(t,12),r.copy(i,16),!e.write(i)&&await new Promise((t,n)=>{e.once(`drain`,t),e.once(`error`,n)})}async function z(e,r,i){if(U(r,`read usbmuxd response`),i?.aborted)throw n();return await new Promise((a,o)=>{let s=Buffer.alloc(0),c=!1,l=setTimeout(()=>m(new t(`COMMAND_FAILED`,`Timed out reading usbmuxd response`,{backend:`xctest`,timeoutMs:r})),r),u=e=>{if(s=Buffer.concat([s,e]),s.length<16)return;let n=s.readUInt32LE(0);if(n<16||n>4194304){m(new t(`COMMAND_FAILED`,`Invalid usbmuxd response length`));return}s.length<n||m(void 0,{payload:s.subarray(16,n)})},d=e=>m(e),f=()=>m(new t(`COMMAND_FAILED`,`usbmuxd closed the connection unexpectedly`)),p=()=>m(n()),m=(t,n)=>{c||(c=!0,clearTimeout(l),e.off(`data`,u),e.off(`error`,d),e.off(`close`,f),i?.removeEventListener(`abort`,p),e.pause(),t?o(t):a(n))};e.on(`data`,u),e.once(`error`,d),e.once(`close`,f),i?.addEventListener(`abort`,p,{once:!0}),e.resume()})}function B(e,t={}){return`<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>${[[`BundleID`,`com.callstack.agent-device`],[`ClientVersionString`,`agent-device`],[`MessageType`,e],[`ProgName`,`agent-device`],[`kLibUSBMuxVersion`,3],...Object.entries(t)].map(([e,t])=>typeof t==`number`?`<key>${o(e)}</key><integer>${t}</integer>`:`<key>${o(e)}</key><string>${o(t)}</string>`).join(``)}</dict></plist>`}function _e(e,t){let n;for(let r of H(s(e))){let e=ve(r);if(e?.udid===t){if(V(V(r,`Properties`),`ConnectionType`)?.text===`USB`)return e.id;n??=e.id}}return n}function ve(e){if(e.name!==`dict`)return;let t=V(e,`Properties`);if(t?.name!==`dict`)return;let n=V(t,`SerialNumber`)?.text,r=Number(V(e,`DeviceID`)?.text);if(!(!n||!Number.isSafeInteger(r)||r<=0))return{udid:n,id:r}}function ye(e,t){for(let n of H(s(e))){if(n.name!==`dict`)continue;let e=V(n,t);if(e?.name!==`integer`)continue;let r=Number(e.text);if(Number.isSafeInteger(r))return r}}function V(e,t){for(let n=0;n<e.children.length-1;n+=1){let r=e.children[n];if(r?.name===`key`&&r.text===t)return e.children[n+1]}}function*H(e){for(let t of e)yield t,yield*H(t.children)}function be(e){let{result:n,udid:r,deviceId:i,port:a}=e;return n===2?new t(`DEVICE_NOT_FOUND`,`iOS device is no longer available through usbmux`,{deviceId:r,backend:`xctest`,usbmuxDeviceAttached:!1,usbmuxResult:n,hint:I}):n===3?new t(`COMMAND_FAILED`,`XCTest runner is not listening on the device port`,{backend:`xctest`,deviceId:i,port:a,usbmuxResult:n,hint:`The device is reachable but nothing is bound to the runner port yet; this resolves once the runner finishes starting.`}):new t(`COMMAND_FAILED`,`Failed to connect to XCTest runner through usbmux`,{backend:`xctest`,deviceId:i,port:a,usbmuxResult:n,hint:`Keep the device connected by cable and unlocked, then retry.`})}function xe(e){return(e&255)<<8|e>>>8&255}function U(e,n){if(!(e>0))throw new t(`COMMAND_FAILED`,`No time remaining to ${n}`,{backend:`xctest`,timeoutMs:e})}function Se(e){return{postCommand:async(n,i,a,o,s)=>{let c=d.fromTimeoutMs(o),l=await me(e,n,i.port,c.remainingMs(),s).catch(e=>{throw e instanceof t?r(e,`no`):e});try{return await we(l,i,a,c.remainingMs(),s)}catch(e){throw l.destroy(),e}}}}const Ce=Se(`/var/run/usbmuxd`);async function we(e,r,i,a,o){if(Oe(a),o?.aborted)throw n({dispatched:`no`});let s=Buffer.from(JSON.stringify(i),`utf8`),c=AbortSignal.timeout(a),l=o?AbortSignal.any([o,c]):c,u=new D.Agent;u.createConnection=(t,n)=>(n?.(null,e),e);try{let t=await Te(u,e,r,s,l);return new Response((await De(t)).toString(`utf8`),{status:t.statusCode??500,headers:Ee(t)})}catch(e){throw o?.aborted?n():c.aborted?new t(`COMMAND_FAILED`,`Timed out waiting for XCTest runner over usbmux`,{backend:`xctest`,timeoutMs:a}):e}finally{u.destroy(),e.destroy()}}async function Te(e,t,n,r,i){return await new Promise((a,o)=>{let s=D.request({method:`POST`,host:`127.0.0.1`,path:`/command`,headers:{...p(n),"Content-Length":r.length,Connection:`close`},agent:e,signal:i},a);s.once(`error`,o),t.resume(),s.end(r)})}function Ee(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers))typeof r==`string`&&t.set(n,r);return t}async function De(e){let n=[],r=0;for await(let i of e){let e=Buffer.isBuffer(i)?i:Buffer.from(i);if(r+=e.length,r>67108864)throw new t(`COMMAND_FAILED`,`XCTest runner response exceeded size limit`);n.push(e)}return Buffer.concat(n)}function Oe(e){if(!(e>0))throw new t(`COMMAND_FAILED`,`No time remaining to send XCTest runner command`,{backend:`xctest`,timeoutMs:e})}const W=45e3;async function ke(e,t,n,r=W,i){return m(await Ae(e,t,n,r,i))}async function Ae(e,t,n,r,i){K(i);let a=d.fromTimeoutMs(r),o=N(e,t.port),s=await o.resolveRoute(a.remainingMs());if(s.kind===`usbmux`)try{return await G(e,s,{endpoint:t,command:n,timeoutMs:a.remainingMs(),signal:i})}catch(t){if(!q(e,t))throw t;o.markUsbmuxUnattached(),s=await o.resolveRoute(a.remainingMs())}return await G(e,s,{endpoint:t,command:n,timeoutMs:a.remainingMs(),signal:i})}async function G(e,n,i){let{endpoint:a,command:o,timeoutMs:s,signal:c}=i;if(K(c),s<=0)throw r(new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{port:a.port,timeoutMs:s}),`no`);if(n.kind===`usbmux`)return await Ce.postCommand(e.id,a,o,s,c);if(!n.url)throw r(new t(`COMMAND_FAILED`,`Runner command endpoint not available`,{port:a.port}),`no`);return await je(n.url,{method:`POST`,headers:p(a),body:JSON.stringify(o)},s,c)}function K(e){if(e?.aborted)throw n({dispatched:`no`})}function q(e,t){return h(t)?c(e).backend!==`xctest`:!1}async function je(e,n,r,i){let a=AbortSignal.timeout(r),o=i?AbortSignal.any([i,a]):a;try{return await fetch(e,{...n,redirect:`error`,signal:o})}catch(e){throw e===a.reason?new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:r},e):e}}const J=45e3;async function Me(e,t,n,r,a=J,o,s){let c=d.fromTimeoutMs(a),u=t.port,{resolveRoute:f,markUsbmuxUnattached:p}=N(e,u),g=await f(c.remainingMs()),_=null,v=!1,b=e=>{y(e)||(v=!0)},S=Math.max(1,Math.ceil(a/250)),C;try{C=await l(async({deadline:c})=>{let l=await Fe({device:e,endpoint:t,command:n,timeoutMs:a,logPath:r,session:o,route:g,resolveRoute:f,markUsbmuxUnattached:p,signal:s,attemptDeadline:c,setRoute:e=>{g=e},setLastError:e=>{_=e,b(e)}}).catch(e=>{throw i(e)&&b(e),e});if(l)return l;throw ze({port:u,url:g.url,lastError:_,signal:s})},{maxAttempts:S,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:x},{deadline:c,phase:`ios_runner_connect`,signal:s,retryWakeSignal:e.kind===`simulator`?o?.startupRetryWake:void 0})}catch(e){if(s?.aborted||i(e))throw Y(v);if(h(e))throw e;_||=e}if(C)return m(C);throw s?.aborted?Y(v):o?.child.exitCode!==null&&o?.child.exitCode!==void 0?X(await He({session:o,port:u,logPath:r}),v):X(Ve({device:e,port:u,url:g.url,logPath:r,lastError:_,session:o}),v)}function Y(e){return n({dispatched:e?`unknown`:`no`})}function Ne(e,t){return n(Pe(e,t)?{dispatched:`no`}:{})}function Pe(e,t){return e!==t?.reason&&y(e)}function X(n,i){return n instanceof t?i?r(n,`unknown`):e(n,`no`):n}async function Fe(e){await Ie(e);let t=await Le(e);return t.response?t.response:await Re(e,t.usedCachedTunnelIp)}async function Ie(e){if(e.attemptDeadline?.isExpired())throw new t(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:e.endpoint.port,timeoutMs:e.timeoutMs});if(e.session?.child.exitCode!==null&&e.session?.child.exitCode!==void 0)throw await He({session:e.session,port:e.endpoint.port,logPath:e.logPath});let n=e.session;if(n?.state!==`starting`)return;let r=n.readLogTail?.(Q)??``;if(!r)return;let i=Ve({device:n.device,port:e.endpoint.port,url:e.route.url,logPath:e.logPath,lastError:null,session:n,launchLogOutput:r});if(!x(i))throw i}async function Le(e){let t=e.route,n=!1;e.device.kind===`device`&&(t=await e.resolveRoute(e.attemptDeadline?.remainingMs()),n=t.cachedTunnelIp,e.setRoute(t));let r=async t=>await Z(e.device,t,{command:e.command,endpoint:e.endpoint,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onUsbmuxUnattached:e.markUsbmuxUnattached,onError:n=>{e.setLastError(n),e.device.kind===`device`&&t.cachedTunnelIp&&P(e.device.id)}}),i=await r(t);if(i||t.kind!==`usbmux`)return{response:i,usedCachedTunnelIp:n};let a=await e.resolveRoute(e.attemptDeadline?.remainingMs());return a.kind===`usbmux`?{response:null,usedCachedTunnelIp:n}:(e.setRoute(a),{response:await r(a),usedCachedTunnelIp:a.cachedTunnelIp})}async function Re(e,t){if(e.device.kind!==`device`||!t)return null;P(e.device.id);let n=await e.resolveRoute(e.attemptDeadline?.remainingMs(),!0);return e.setRoute(n),await Z(e.device,n,{command:e.command,endpoint:e.endpoint,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:e.setLastError})}function ze(e){if(e.signal?.aborted)throw n();return new t(`COMMAND_FAILED`,`Runner endpoint probe failed`,{port:e.port,url:e.url,lastError:e.lastError?String(e.lastError):void 0,..._(`runner_endpoint_probe_exhausted`)})}async function Z(e,t,n){let r=n.attemptDeadline?.remainingMs()??n.timeoutMs;try{return await G(e,t,{endpoint:n.endpoint,command:n.command,timeoutMs:Math.min(2e4,r),signal:n.signal})}catch(r){if(n.signal?.aborted||i(r))throw Ne(r,n.signal);if(t.kind===`usbmux`&&h(r)){if(!q(e,r))throw r;return n.onUsbmuxUnattached?.(),null}return n.onError(r),null}}const Q=65536;function Be(e,t,n,r){let i=`${e}\n${t}\n${n}`.toLowerCase();if(i.includes(`device is busy`)&&i.includes(`connecting`))return`Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.`;let a=r??`IOS_RUNNER_CONNECT_TIMEOUT`;return a===`IOS_RUNNER_DEVICE_NOT_PROVISIONED`?u(a):`${u(a)} ${b}`}function $(e){let n=v(new t(`COMMAND_FAILED`,e.message,{stderr:e.output,...S(e.device)}));if(n.messageSuffix)return{message:`${e.message}: ${n.messageSuffix}`,reason:n.reason,hint:n.hint}}function Ve(e){let{device:n,port:r,url:i,logPath:a,lastError:o,session:s}=e,c=`Runner did not accept connection`,l=$({message:c,output:e.launchLogOutput??s?.readLogTail?.(Q)??``,device:n}),d=new t(`COMMAND_FAILED`,l?.message??c,{port:r,url:i,logPath:l?s?.runnerLogPath??a:a,lastError:o?String(o):void 0,reason:l?.reason??f({error:o,message:c,context:{platform:`ios`,phase:`connect`}}),hint:l?.hint??u(`IOS_RUNNER_CONNECT_TIMEOUT`),..._(`runner_connect_refused`)});return g(d,s?.startupDeviceStates)}async function He(e){let{session:n,port:r,logPath:i}=e,a=await n.testPromise,o=`Runner did not accept connection (xcodebuild exited early)`,s=n.readLogTail?.(Q)??``,c=f({message:o,stdout:s,stderr:s,context:{platform:`ios`,phase:`connect`}}),l=C(n.device),u=$({message:o,output:s,device:n.device}),d=new t(`COMMAND_FAILED`,u?.message??o,{port:r,logPath:n.runnerLogPath??i,xcodebuild:{exitCode:a.exitCode,stderr:s},reason:u?.reason??c,hint:u?.hint??Be(o,s,s,c),...l,..._(`xcodebuild_exited_early`)});return g(d,n.startupDeviceStates)}export{K as a,re as c,ce as d,ae as f,ke as i,te as l,Me as n,ie as o,se as p,W as r,oe as s,J as t,ne as u};
1
+ import{G as e,H as t,Q as n,R as r,q as i}from"./sdk-contracts.js";import{T as a}from"./sdk-device.js";import{n as o}from"./entities.js";import{t as s}from"./parser.js";import{M as c,N as l,i as u,o as d,t as f}from"./host2.js";import{L as p,N as m,d as h,i as g,m as _,r as v,s as y,t as b,v as x}from"./runner-error-classification.js";import{n as S,r as C}from"./runner-device-set.js";import w from"node:fs";import ee from"node:os";import T from"node:path";import E from"node:net";import D from"node:http";async function te(){return await new Promise((e,t)=>{let n=E.createServer();n.listen(0,`127.0.0.1`,()=>{let i=n.address();if(typeof i==`object`&&i?.port){let t=i.port;n.close(()=>e(t))}else n.close(()=>t(new r(`COMMAND_FAILED`,`Failed to allocate port`)))}),n.on(`error`,t)})}function ne(e,t,n,r){t&&A(t,e),n&&A(n,e),r&&process.stderr.write(e)}const O=new Map,k=new Map;function A(e,t){let n=(O.get(e)??Promise.resolve()).then(()=>j(e,t),()=>j(e,t)).then(()=>{k.delete(e)},t=>{k.set(e,t)}).finally(()=>{O.get(e)===n&&O.delete(e)});O.set(e,n)}async function j(e,t){await w.promises.mkdir(T.dirname(e),{recursive:!0}),await w.promises.appendFile(e,t)}async function re(e,t={}){let n=AbortSignal.any([t.signal??new AbortController().signal,AbortSignal.timeout(t.timeoutMs??2e3)]);if(n.aborted)throw n.reason;let r=O.get(e);if(r){let e=()=>{};try{await Promise.race([r,new Promise((t,r)=>{e=()=>r(n.reason),n.addEventListener(`abort`,e,{once:!0})})])}finally{n.removeEventListener(`abort`,e)}}let i=k.get(e);if(i!==void 0)throw i}function ie(e){try{w.existsSync(e)&&w.unlinkSync(e)}catch{}}function ae(e,t){if(e)return e;let n=t.replaceAll(/[^A-Za-z0-9._-]/g,`_`);return T.join(ee.tmpdir(),`agent-device`,`apple-runner`,`logs`,`${n}.log`)}function oe(e,t){let n=0;try{n=w.fstatSync(t).size}catch{}return{logPath:e,startOffset:n}}function se(e){let t=e.pollMs??50,n=Buffer.alloc(65536),r=e.file.startOffset,i=null,a=null,o=!1,s=()=>{if(!o)try{i??=w.openSync(e.file.logPath,`r`);let t=w.fstatSync(i).size;for(t<r&&(r=0);r<t;){let a=Math.min(n.length,t-r),o=w.readSync(i,n,0,a,r);if(o<=0)break;r+=o,e.onOutput(n.toString(`utf8`,0,o)),t=w.fstatSync(i).size}}catch{l()}},c=()=>{o||(a=setTimeout(()=>{s(),c()},t),a.unref?.())};function l(){if(!o&&(o=!0,a&&clearTimeout(a),a=null,i!==null)){try{w.closeSync(i)}catch{}i=null}}return c(),{drain:()=>{s(),l()},stop:l}}function ce(e,t){if(!e)return``;let n=null;try{n=w.openSync(e.logPath,`r`);let r=w.fstatSync(n).size,i=Math.max(e.startOffset,r-t),a=r-i;if(a<=0)return``;let o=Buffer.alloc(a),s=w.readSync(n,o,0,a,i);return o.toString(`utf8`,0,Math.max(s,0))}catch{return``}finally{if(n!==null)try{w.closeSync(n)}catch{}}}const M=new Map;function N(e,t){let n,r=!1;return{markUsbmuxUnattached:()=>{r=!0},resolveRoute:async(i,a=!1)=>{if(ue(e))return de(t);let o=c(e);if(o.backend===`xctest`||!r)return le(e,t);if(!a){let r=fe(e.id);if(r)return F(t,r,!0);if(n!==void 0)return F(t,n,!1)}let{tunnelIp:s}=await o.resolveTunnel(e,i);return n=s,s&&pe(e.id,s),F(t,s,!1)}}}function P(e){M.delete(e)}function le(e,t){return{kind:`usbmux`,url:`usbmux://${e.id}:${t}/command`,cachedTunnelIp:!1}}function ue(e){return e.kind!==`device`||a(e)}function de(e){return{kind:`network`,url:`http://127.0.0.1:${e}/command`,cachedTunnelIp:!1}}function F(e,t,n){return{kind:`network`,url:t?`http://[${t}]:${e}/command`:null,cachedTunnelIp:n}}function fe(e){let t=M.get(e);return t?t.expiresAt<=Date.now()?(M.delete(e),null):t.ip:null}function pe(e,t){M.set(e,{ip:t,expiresAt:Date.now()+3e4})}const I=`Connect the device by cable, trust this Mac, keep it unlocked, and retry.`;async function me(e,t,n,r,i){let a=f.fromTimeoutMs(r);return await ge(e,t,await he(e,t,a.remainingMs(),i),n,a.remainingMs(),i)}async function he(e,t,n,i){let a=await L(e,n,i);try{await R(a,1,B(`ListDevices`));let e=_e((await z(a,n,i)).payload.toString(`utf8`),t);if(e!==void 0)return e;throw new r(`DEVICE_NOT_FOUND`,`iOS device is not available through usbmux`,{deviceId:t,backend:`xctest`,usbmuxDeviceAttached:!1,hint:I})}finally{a.destroy()}}async function ge(e,t,n,r,i,a){let o=await L(e,i,a);try{await R(o,2,B(`Connect`,{DeviceID:n,PortNumber:xe(r)}));let e=ye((await z(o,i,a)).payload.toString(`utf8`),`Number`);if(e!==0)throw be({result:e,udid:t,deviceId:n,port:r});return o}catch(e){throw o.destroy(),e}}async function L(e,n,i){if(U(n,`connect to usbmuxd`),i?.aborted)throw t();return await new Promise((a,o)=>{let s=E.createConnection(e),c=!1,l=setTimeout(()=>{p(new r(`COMMAND_FAILED`,`Timed out connecting to usbmuxd`,{backend:`xctest`,socketPath:e,timeoutMs:n}))},n),u=()=>p(),d=e=>p(e),f=()=>p(t()),p=e=>{c||(c=!0,clearTimeout(l),s.off(`connect`,u),s.off(`error`,d),i?.removeEventListener(`abort`,f),e?(s.destroy(),o(e)):a(s))};s.once(`connect`,u),s.once(`error`,d),i?.addEventListener(`abort`,f,{once:!0})})}async function R(e,t,n){let r=Buffer.from(n,`utf8`),i=Buffer.alloc(16+r.length);i.writeUInt32LE(i.length,0),i.writeUInt32LE(1,4),i.writeUInt32LE(8,8),i.writeUInt32LE(t,12),r.copy(i,16),!e.write(i)&&await new Promise((t,n)=>{e.once(`drain`,t),e.once(`error`,n)})}async function z(e,n,i){if(U(n,`read usbmuxd response`),i?.aborted)throw t();return await new Promise((a,o)=>{let s=Buffer.alloc(0),c=!1,l=setTimeout(()=>m(new r(`COMMAND_FAILED`,`Timed out reading usbmuxd response`,{backend:`xctest`,timeoutMs:n})),n),u=e=>{if(s=Buffer.concat([s,e]),s.length<16)return;let t=s.readUInt32LE(0);if(t<16||t>4194304){m(new r(`COMMAND_FAILED`,`Invalid usbmuxd response length`));return}s.length<t||m(void 0,{payload:s.subarray(16,t)})},d=e=>m(e),f=()=>m(new r(`COMMAND_FAILED`,`usbmuxd closed the connection unexpectedly`)),p=()=>m(t()),m=(t,n)=>{c||(c=!0,clearTimeout(l),e.off(`data`,u),e.off(`error`,d),e.off(`close`,f),i?.removeEventListener(`abort`,p),e.pause(),t?o(t):a(n))};e.on(`data`,u),e.once(`error`,d),e.once(`close`,f),i?.addEventListener(`abort`,p,{once:!0}),e.resume()})}function B(e,t={}){return`<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>${[[`BundleID`,`com.callstack.agent-device`],[`ClientVersionString`,`agent-device`],[`MessageType`,e],[`ProgName`,`agent-device`],[`kLibUSBMuxVersion`,3],...Object.entries(t)].map(([e,t])=>typeof t==`number`?`<key>${o(e)}</key><integer>${t}</integer>`:`<key>${o(e)}</key><string>${o(t)}</string>`).join(``)}</dict></plist>`}function _e(e,t){let n;for(let r of H(s(e))){let e=ve(r);if(e?.udid===t){if(V(V(r,`Properties`),`ConnectionType`)?.text===`USB`)return e.id;n??=e.id}}return n}function ve(e){if(e.name!==`dict`)return;let t=V(e,`Properties`);if(t?.name!==`dict`)return;let n=V(t,`SerialNumber`)?.text,r=Number(V(e,`DeviceID`)?.text);if(!(!n||!Number.isSafeInteger(r)||r<=0))return{udid:n,id:r}}function ye(e,t){for(let n of H(s(e))){if(n.name!==`dict`)continue;let e=V(n,t);if(e?.name!==`integer`)continue;let r=Number(e.text);if(Number.isSafeInteger(r))return r}}function V(e,t){for(let n=0;n<e.children.length-1;n+=1){let r=e.children[n];if(r?.name===`key`&&r.text===t)return e.children[n+1]}}function*H(e){for(let t of e)yield t,yield*H(t.children)}function be(e){let{result:t,udid:n,deviceId:i,port:a}=e;return t===2?new r(`DEVICE_NOT_FOUND`,`iOS device is no longer available through usbmux`,{deviceId:n,backend:`xctest`,usbmuxDeviceAttached:!1,usbmuxResult:t,hint:I}):t===3?new r(`COMMAND_FAILED`,`XCTest runner is not listening on the device port`,{backend:`xctest`,deviceId:i,port:a,usbmuxResult:t,hint:`The device is reachable but nothing is bound to the runner port yet; this resolves once the runner finishes starting.`}):new r(`COMMAND_FAILED`,`Failed to connect to XCTest runner through usbmux`,{backend:`xctest`,deviceId:i,port:a,usbmuxResult:t,hint:`Keep the device connected by cable and unlocked, then retry.`})}function xe(e){return(e&255)<<8|e>>>8&255}function U(e,t){if(!(e>0))throw new r(`COMMAND_FAILED`,`No time remaining to ${t}`,{backend:`xctest`,timeoutMs:e})}function Se(t){return{postCommand:async(n,i,a,o,s)=>{let c=f.fromTimeoutMs(o),l=await me(t,n,i.port,c.remainingMs(),s).catch(t=>{throw t instanceof r?e(t,`no`):t});try{return await we(l,i,a,c.remainingMs(),s)}catch(e){throw l.destroy(),e}}}}const Ce=Se(`/var/run/usbmuxd`);async function we(e,n,i,a,o){if(Oe(a),o?.aborted)throw t({dispatched:`no`});let s=Buffer.from(JSON.stringify(i),`utf8`),c=AbortSignal.timeout(a),l=o?AbortSignal.any([o,c]):c,u=new D.Agent;u.createConnection=(t,n)=>(n?.(null,e),e);try{let t=await Te(u,e,n,s,l);return new Response((await De(t)).toString(`utf8`),{status:t.statusCode??500,headers:Ee(t)})}catch(e){throw o?.aborted?t():c.aborted?new r(`COMMAND_FAILED`,`Timed out waiting for XCTest runner over usbmux`,{backend:`xctest`,timeoutMs:a}):e}finally{u.destroy(),e.destroy()}}async function Te(e,t,n,r,i){return await new Promise((a,o)=>{let s=D.request({method:`POST`,host:`127.0.0.1`,path:`/command`,headers:{...p(n),"Content-Length":r.length,Connection:`close`},agent:e,signal:i},a);s.once(`error`,o),t.resume(),s.end(r)})}function Ee(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers))typeof r==`string`&&t.set(n,r);return t}async function De(e){let t=[],n=0;for await(let i of e){let e=Buffer.isBuffer(i)?i:Buffer.from(i);if(n+=e.length,n>67108864)throw new r(`COMMAND_FAILED`,`XCTest runner response exceeded size limit`);t.push(e)}return Buffer.concat(t)}function Oe(e){if(!(e>0))throw new r(`COMMAND_FAILED`,`No time remaining to send XCTest runner command`,{backend:`xctest`,timeoutMs:e})}const W=45e3;async function ke(e,t,n,r=W,i){return m(await Ae(e,t,n,r,i))}async function Ae(e,t,n,r,i){K(i);let a=f.fromTimeoutMs(r),o=N(e,t.port),s=await o.resolveRoute(a.remainingMs());if(s.kind===`usbmux`)try{return await G(e,s,{endpoint:t,command:n,timeoutMs:a.remainingMs(),signal:i})}catch(t){if(!q(e,t))throw t;o.markUsbmuxUnattached(),s=await o.resolveRoute(a.remainingMs())}return await G(e,s,{endpoint:t,command:n,timeoutMs:a.remainingMs(),signal:i})}async function G(t,n,i){let{endpoint:a,command:o,timeoutMs:s,signal:c}=i;if(K(c),s<=0)throw e(new r(`COMMAND_FAILED`,`Runner command deadline exceeded`,{port:a.port,timeoutMs:s}),`no`);if(n.kind===`usbmux`)return await Ce.postCommand(t.id,a,o,s,c);if(!n.url)throw e(new r(`COMMAND_FAILED`,`Runner command endpoint not available`,{port:a.port}),`no`);return await je(n.url,{method:`POST`,headers:p(a),body:JSON.stringify(o)},s,c)}function K(e){if(e?.aborted)throw t({dispatched:`no`})}function q(e,t){return h(t)?c(e).backend!==`xctest`:!1}async function je(e,t,n,i){let a=AbortSignal.timeout(n),o=i?AbortSignal.any([i,a]):a;try{return await fetch(e,{...t,redirect:`error`,signal:o})}catch(e){throw e===a.reason?new r(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:n},e):e}}const J=45e3;async function Me(e,t,r,i,a=J,o,s){let c=f.fromTimeoutMs(a),u=t.port,{resolveRoute:d,markUsbmuxUnattached:p}=N(e,u),g=await d(c.remainingMs()),_=null,v=!1,b=e=>{y(e)||(v=!0)},S=Math.max(1,Math.ceil(a/250)),C;try{C=await l(async({deadline:c})=>{let l=await Fe({device:e,endpoint:t,command:r,timeoutMs:a,logPath:i,session:o,route:g,resolveRoute:d,markUsbmuxUnattached:p,signal:s,attemptDeadline:c,setRoute:e=>{g=e},setLastError:e=>{_=e,b(e)}}).catch(e=>{throw n(e)&&b(e),e});if(l)return l;throw ze({port:u,url:g.url,lastError:_,signal:s})},{maxAttempts:S,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:x},{deadline:c,phase:`ios_runner_connect`,signal:s,retryWakeSignal:e.kind===`simulator`?o?.startupRetryWake:void 0})}catch(e){if(s?.aborted||n(e))throw Y(v);if(h(e))throw e;_||=e}if(C)return m(C);throw s?.aborted?Y(v):o?.child.exitCode!==null&&o?.child.exitCode!==void 0?X(await He({session:o,port:u,logPath:i}),v):X(Ve({device:e,port:u,url:g.url,logPath:i,lastError:_,session:o}),v)}function Y(e){return t({dispatched:e?`unknown`:`no`})}function Ne(e,n){return t(Pe(e,n)?{dispatched:`no`}:{})}function Pe(e,t){return e!==t?.reason&&y(e)}function X(t,n){return t instanceof r?n?e(t,`unknown`):i(t,`no`):t}async function Fe(e){await Ie(e);let t=await Le(e);return t.response?t.response:await Re(e,t.usedCachedTunnelIp)}async function Ie(e){if(e.attemptDeadline?.isExpired())throw new r(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:e.endpoint.port,timeoutMs:e.timeoutMs});if(e.session?.child.exitCode!==null&&e.session?.child.exitCode!==void 0)throw await He({session:e.session,port:e.endpoint.port,logPath:e.logPath});let t=e.session;if(t?.state!==`starting`)return;let n=t.readLogTail?.(Q)??``;if(!n)return;let i=Ve({device:t.device,port:e.endpoint.port,url:e.route.url,logPath:e.logPath,lastError:null,session:t,launchLogOutput:n});if(!x(i))throw i}async function Le(e){let t=e.route,n=!1;e.device.kind===`device`&&(t=await e.resolveRoute(e.attemptDeadline?.remainingMs()),n=t.cachedTunnelIp,e.setRoute(t));let r=async t=>await Z(e.device,t,{command:e.command,endpoint:e.endpoint,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onUsbmuxUnattached:e.markUsbmuxUnattached,onError:n=>{e.setLastError(n),e.device.kind===`device`&&t.cachedTunnelIp&&P(e.device.id)}}),i=await r(t);if(i||t.kind!==`usbmux`)return{response:i,usedCachedTunnelIp:n};let a=await e.resolveRoute(e.attemptDeadline?.remainingMs());return a.kind===`usbmux`?{response:null,usedCachedTunnelIp:n}:(e.setRoute(a),{response:await r(a),usedCachedTunnelIp:a.cachedTunnelIp})}async function Re(e,t){if(e.device.kind!==`device`||!t)return null;P(e.device.id);let n=await e.resolveRoute(e.attemptDeadline?.remainingMs(),!0);return e.setRoute(n),await Z(e.device,n,{command:e.command,endpoint:e.endpoint,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:e.setLastError})}function ze(e){if(e.signal?.aborted)throw t();return new r(`COMMAND_FAILED`,`Runner endpoint probe failed`,{port:e.port,url:e.url,lastError:e.lastError?String(e.lastError):void 0,..._(`runner_endpoint_probe_exhausted`)})}async function Z(e,t,r){let i=r.attemptDeadline?.remainingMs()??r.timeoutMs;try{return await G(e,t,{endpoint:r.endpoint,command:r.command,timeoutMs:Math.min(2e4,i),signal:r.signal})}catch(i){if(r.signal?.aborted||n(i))throw Ne(i,r.signal);if(t.kind===`usbmux`&&h(i)){if(!q(e,i))throw i;return r.onUsbmuxUnattached?.(),null}return r.onError(i),null}}const Q=65536;function Be(e,t,n,r){let i=`${e}\n${t}\n${n}`.toLowerCase();if(i.includes(`device is busy`)&&i.includes(`connecting`))return`Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.`;let a=r??`IOS_RUNNER_CONNECT_TIMEOUT`;return a===`IOS_RUNNER_DEVICE_NOT_PROVISIONED`?u(a):`${u(a)} ${b}`}function $(e){let t=v(new r(`COMMAND_FAILED`,e.message,{stderr:e.output,...S(e.device)}));if(t.messageSuffix)return{message:`${e.message}: ${t.messageSuffix}`,reason:t.reason,hint:t.hint}}function Ve(e){let{device:t,port:n,url:i,logPath:a,lastError:o,session:s}=e,c=`Runner did not accept connection`,l=$({message:c,output:e.launchLogOutput??s?.readLogTail?.(Q)??``,device:t}),f=new r(`COMMAND_FAILED`,l?.message??c,{port:n,url:i,logPath:l?s?.runnerLogPath??a:a,lastError:o?String(o):void 0,reason:l?.reason??d({error:o,message:c,context:{platform:`ios`,phase:`connect`}}),hint:l?.hint??u(`IOS_RUNNER_CONNECT_TIMEOUT`),..._(`runner_connect_refused`)});return g(f,s?.startupDeviceStates)}async function He(e){let{session:t,port:n,logPath:i}=e,a=await t.testPromise,o=`Runner did not accept connection (xcodebuild exited early)`,s=t.readLogTail?.(Q)??``,c=d({message:o,stdout:s,stderr:s,context:{platform:`ios`,phase:`connect`}}),l=C(t.device),u=$({message:o,output:s,device:t.device}),f=new r(`COMMAND_FAILED`,u?.message??o,{port:n,logPath:t.runnerLogPath??i,xcodebuild:{exitCode:a.exitCode,stderr:s},reason:u?.reason??c,hint:u?.hint??Be(o,s,s,c),...l,..._(`xcodebuild_exited_early`)});return g(f,t.startupDeviceStates)}export{K as a,re as c,ce as d,ae as f,ke as i,te as l,Me as n,ie as o,se as p,W as r,oe as s,J as t,ne as u};
@@ -1,2 +1,2 @@
1
- import{R as e,V as t,Z as n}from"./sdk-contracts.js";import{J as r,b as i,d as a,k as o,l as s,n as c,p as l,t as u,x as d}from"./apple-runner-platform.js";import f from"node:fs";import p from"node:path";function m(e,t){return{deadline:e!==void 0&&Number.isFinite(e)?l.fromTimeoutMs(Math.max(0,e)):void 0,signal:t}}function h(e,t){let n=e?.deadline;if(!n)return;let r=Math.floor(n.remainingMs());if(r<=0)throw g(t);return r}function g(t){return new e(`COMMAND_FAILED`,`The Apple runner budget ran out before this step began`,{phase:t,reason:`runner_phase_budget_exhausted`,retriable:!0})}function _(t){return t instanceof e&&t.details?.reason===`runner_phase_budget_exhausted`}const v=131072;function y(e){let n=e?.deadline,r=l.fromTimeoutMs(Math.min(45e3,n?n.remainingMs():1/0));return{attemptTimeoutMs:()=>Math.min(u,Math.floor(r.remainingMs())),keyProbeTimeoutMs:()=>Math.min(2e3,Math.floor(r.remainingMs()/2)),throwIfCanceled:()=>{if(e?.signal?.aborted)throw t({phase:`apple_toolchain_probe`})}}}const b=6e5;let x;function S(){return x??=d({ttlMs:b,scheduleExpiry:!0}),x}let C;function w(){return C??=d({ttlMs:b,scheduleExpiry:!0}),C}let T;function E(e){return w()?.get(e)}function D(e,t){w()?.set(e,t)}function O(e,t){let n=y(t);n.throwIfCanceled();let r=i(),a=r===void 0?N(n):P(r)??r;if(a===void 0)return M(e,n);let o=k(a);n.throwIfCanceled();let s=A(j(a,o,e),e,n),c={developerDir:a,bundleIdentity:o};return r===void 0?T=c:D(r,c),s}function k(e){try{let t=f.statSync(p.join(e,`..`,`version.plist`));return`${t.ino}:${Math.trunc(t.mtimeMs)}`}catch{return}}function A(e,t,n){let r=S().get(e);if(r)return S().set(e,r),r;let i=M(t,n);return S().set(e,i),i}function j(e,t,n){return`${e}\0${t??``}\0${n}`}function M(e,t){let n=L(e,t);if(!n.ok)throw R(n.failures);return n.value}function N(e){let t=P(c);if(t)return t;let n=F(e);if(n!==void 0)return P(n)??n}function P(e){if(e!==void 0)try{return f.realpathSync(e.trim())||void 0}catch{return}}function F(e){let t=e.keyProbeTimeoutMs();if(t<=0)return;let n;try{let e=r(`xcode-select`,[`-p`],{allowFailure:!0,timeoutMs:t,maxBuffer:v});n=e.exitCode===0?e.stdout.trim():void 0}catch{n=void 0}return e.throwIfCanceled(),n||void 0}function I(e){let t=i(),n=t===void 0?T:E(t);if(n!==void 0)return S().get(j(n.developerDir,n.bundleIdentity,a(s(e),e.kind)))?.xcodeVersion}function L(e,t){let n=H(z(`xcodebuild`,[`-version`],t)),r=z(`xcrun`,[`--sdk`,e,`--show-sdk-version`],t),i=z(`xcrun`,[`--sdk`,e,`--show-sdk-build-version`],t);return!n.ok||!r.ok||!i.ok?{ok:!1,failures:[n,r,i].flatMap(e=>e.ok?[]:[e.failure])}:{ok:!0,value:{xcodeVersion:n.value.version,xcodeBuildVersion:n.value.buildVersion,sdkName:e,sdkVersion:r.value,sdkBuildVersion:i.value}}}function R(t){return new e(`COMMAND_FAILED`,`Could not read the Xcode toolchain versions the Apple runner cache is keyed on (${t.map(e=>`${e.probe}: ${e.detail}`).join(`; `)})`,{reason:`apple_toolchain_probe_unavailable`,retriable:!0,probes:t,hint:"The Apple runner cache is keyed on the toolchain version, so a cache decision cannot be made without it. Retry once the host is less loaded, or check `xcode-select -p` and `xcodebuild -version`."})}function z(e,t,r){let i=[e,...t].join(` `),a;try{a=B(e,t,r)}catch(e){if(r.throwIfCanceled(),n(e)||_(e))throw e;return U(i,`probe_error`,e instanceof Error?e.message:`${e}`)}if(a.exitCode!==0)return U(i,`nonzero_exit`,`exit ${a.exitCode}${a.stderr.trim()?`: ${a.stderr.trim()}`:``}`);let o=a.stdout.trim();return o?{ok:!0,value:o}:U(i,`empty_output`,`no output`)}function B(e,t,n){try{return V(e,t,n)}catch(r){if(!o(r))throw r;return V(e,t,n)}}function V(e,t,n){n.throwIfCanceled();let i=n.attemptTimeoutMs();if(i<=0)throw g(`apple_toolchain_probe`);return r(e,t,{allowFailure:!0,timeoutMs:i,maxBuffer:v})}function H(e){if(!e.ok)return e;let t=e.value.match(/^Xcode\s+(.+)$/m)?.[1]?.trim(),n=e.value.match(/^Build version\s+(.+)$/m)?.[1]?.trim();return!t||!n?U(`xcodebuild -version`,`unparsable_output`,`unrecognized output: ${e.value.replaceAll(`
1
+ import{H as e,Q as t,R as n}from"./sdk-contracts.js";import{L as r,_ as i,c as a,l as o,t as s}from"./host2.js";import{f as c,n as l,t as u,u as d}from"./apple-runner-platform.js";import f from"node:fs";import p from"node:path";function m(e,t){return{deadline:e!==void 0&&Number.isFinite(e)?s.fromTimeoutMs(Math.max(0,e)):void 0,signal:t}}function h(e,t){let n=e?.deadline;if(!n)return;let r=Math.floor(n.remainingMs());if(r<=0)throw g(t);return r}function g(e){return new n(`COMMAND_FAILED`,`The Apple runner budget ran out before this step began`,{phase:e,reason:`runner_phase_budget_exhausted`,retriable:!0})}function _(e){return e instanceof n&&e.details?.reason===`runner_phase_budget_exhausted`}const v=131072;function y(t){let n=t?.deadline,r=s.fromTimeoutMs(Math.min(45e3,n?n.remainingMs():1/0));return{attemptTimeoutMs:()=>Math.min(u,Math.floor(r.remainingMs())),keyProbeTimeoutMs:()=>Math.min(2e3,Math.floor(r.remainingMs()/2)),throwIfCanceled:()=>{if(t?.signal?.aborted)throw e({phase:`apple_toolchain_probe`})}}}const b=6e5;let x;function S(){return x??=o({ttlMs:b,scheduleExpiry:!0}),x}let C;function w(){return C??=o({ttlMs:b,scheduleExpiry:!0}),C}let T;function E(e){return w()?.get(e)}function D(e,t){w()?.set(e,t)}function O(e,t){let n=y(t);n.throwIfCanceled();let r=a(),i=r===void 0?N(n):P(r)??r;if(i===void 0)return M(e,n);let o=k(i);n.throwIfCanceled();let s=A(j(i,o,e),e,n),c={developerDir:i,bundleIdentity:o};return r===void 0?T=c:D(r,c),s}function k(e){try{let t=f.statSync(p.join(e,`..`,`version.plist`));return`${t.ino}:${Math.trunc(t.mtimeMs)}`}catch{return}}function A(e,t,n){let r=S().get(e);if(r)return S().set(e,r),r;let i=M(t,n);return S().set(e,i),i}function j(e,t,n){return`${e}\0${t??``}\0${n}`}function M(e,t){let n=L(e,t);if(!n.ok)throw R(n.failures);return n.value}function N(e){let t=P(l);if(t)return t;let n=F(e);if(n!==void 0)return P(n)??n}function P(e){if(e!==void 0)try{return f.realpathSync(e.trim())||void 0}catch{return}}function F(e){let t=e.keyProbeTimeoutMs();if(t<=0)return;let n;try{let e=r(`xcode-select`,[`-p`],{allowFailure:!0,timeoutMs:t,maxBuffer:v});n=e.exitCode===0?e.stdout.trim():void 0}catch{n=void 0}return e.throwIfCanceled(),n||void 0}function I(e){let t=a(),n=t===void 0?T:E(t);if(n!==void 0)return S().get(j(n.developerDir,n.bundleIdentity,c(d(e),e.kind)))?.xcodeVersion}function L(e,t){let n=H(z(`xcodebuild`,[`-version`],t)),r=z(`xcrun`,[`--sdk`,e,`--show-sdk-version`],t),i=z(`xcrun`,[`--sdk`,e,`--show-sdk-build-version`],t);return!n.ok||!r.ok||!i.ok?{ok:!1,failures:[n,r,i].flatMap(e=>e.ok?[]:[e.failure])}:{ok:!0,value:{xcodeVersion:n.value.version,xcodeBuildVersion:n.value.buildVersion,sdkName:e,sdkVersion:r.value,sdkBuildVersion:i.value}}}function R(e){return new n(`COMMAND_FAILED`,`Could not read the Xcode toolchain versions the Apple runner cache is keyed on (${e.map(e=>`${e.probe}: ${e.detail}`).join(`; `)})`,{reason:`apple_toolchain_probe_unavailable`,retriable:!0,probes:e,hint:"The Apple runner cache is keyed on the toolchain version, so a cache decision cannot be made without it. Retry once the host is less loaded, or check `xcode-select -p` and `xcodebuild -version`."})}function z(e,n,r){let i=[e,...n].join(` `),a;try{a=B(e,n,r)}catch(e){if(r.throwIfCanceled(),t(e)||_(e))throw e;return U(i,`probe_error`,e instanceof Error?e.message:`${e}`)}if(a.exitCode!==0)return U(i,`nonzero_exit`,`exit ${a.exitCode}${a.stderr.trim()?`: ${a.stderr.trim()}`:``}`);let o=a.stdout.trim();return o?{ok:!0,value:o}:U(i,`empty_output`,`no output`)}function B(e,t,n){try{return V(e,t,n)}catch(r){if(!i(r))throw r;return V(e,t,n)}}function V(e,t,n){n.throwIfCanceled();let i=n.attemptTimeoutMs();if(i<=0)throw g(`apple_toolchain_probe`);return r(e,t,{allowFailure:!0,timeoutMs:i,maxBuffer:v})}function H(e){if(!e.ok)return e;let t=e.value.match(/^Xcode\s+(.+)$/m)?.[1]?.trim(),n=e.value.match(/^Build version\s+(.+)$/m)?.[1]?.trim();return!t||!n?U(`xcodebuild -version`,`unparsable_output`,`unrecognized output: ${e.value.replaceAll(`
2
2
  `,` `)}`):{ok:!0,value:{version:t,buildVersion:n}}}function U(e,t,n){return{ok:!1,failure:{probe:e,reason:t,detail:n.length>200?`${n.slice(0,200)}…`:n}}}export{h as i,O as n,m as r,I as t};
@@ -1,2 +1,2 @@
1
- import{r as e}from"./rolldown-runtime.js";import{G as t,R as n,W as r,lt as i}from"./sdk-contracts.js";import{N as a,v as o}from"./sdk-device.js";import{r as s}from"./touch-runtime.js";import{A as c,O as l,V as u,a as d,d as ee,l as te,o as ne,w as re}from"./apple-runner-platform.js";import{n as f}from"./runner-toolchain-probe.js";import{AsyncLocalStorage as ie}from"node:async_hooks";import p from"node:crypto";import m from"node:fs";import ae from"node:os";import h from"node:path";const g=new ie;function oe(e,t){return{runCommand:e,...t}}function se(e,t,n={}){let r=ce(e,n);return v(r?r.provider:t)}function ce(e,t={}){let n=g.getStore();return n&&n.deviceId===e.id&&(n.requestId?n.requestId===t.requestId:!t.requestId)?n:void 0}async function _(e,t,n){if(!e)return await n();let r={provider:v(e),deviceId:t.deviceId,requestId:t.requestId};return await g.run(r,n)}function v(e){return typeof e==`function`?{runCommand:e,hasLiveSession:()=>!0}:e}const y=[`tap`,`doubleTap`,`longPress`];function le(e){return typeof e==`string`&&y.includes(e)}function b(e,t){return r(new n(`INVALID_ARGS`,e,{...t,reason:`runner_sequence_invalid`}),`no`)}function x(e,t,n){return b(n,{stepIndex:e,kind:typeof t==`string`?t:void 0})}function ue(e){if(!Array.isArray(e)||e.length===0)throw b(`sequence requires at least one step`,{stepCount:Array.isArray(e)?e.length:0});if(e.length>20)throw b(`sequence accepts at most 20 steps, received ${e.length}`,{stepCount:e.length,maxSteps:20});e.forEach((e,t)=>de(e,t))}function de(e,t){if(!le(e.kind))throw x(t,e.kind,`sequence step ${t} has unsupported kind "${String(e.kind)}"; allowed: ${y.join(`, `)}`);if(!Number.isFinite(e.x)||!Number.isFinite(e.y))throw x(t,e.kind,`sequence step ${t} (${e.kind}) requires finite x and y`);e.durationMs!==void 0&&S(e.durationMs,0,1e4,t,e.kind,`durationMs`),e.pauseMs!==void 0&&S(e.pauseMs,0,1e4,t,e.kind,`pauseMs`)}function S(e,t,n,r,i,a){if(!Number.isFinite(e)||e<t||e>n)throw x(r,i,`sequence step ${r} (${i}) ${a} must be between ${t} and ${n}`)}function C(e,t){return ue(e),{command:`sequence`,steps:e,appBundleId:t}}async function fe(e,n,r,i,a){let o=pe(me(e,n,r),20).map(e=>C(e,i)),s,c,l=0,u=[],d=0;for(let e of o){let n;try{n=await a(e)}catch(e){throw t(e,l)}s??=n,c=n;let r;try{r=w(n)}catch(e){throw t(ge(e,d),l+he(e))}l+=r.completedSteps,u.push(...r.results),d+=e.steps?.length??0}return{...s??{},completedSteps:l,sequenceResults:u,...c?.gestureEndUptimeMs===void 0?{}:{gestureEndUptimeMs:c.gestureEndUptimeMs},timingMode:`runner-sequence`}}function pe(e,t,n=2e4){let r=[],i=[],a=0;for(let o of e){let e=(o.durationMs??0)+(o.pauseMs??0)+250;i.length>0&&(i.length>=t||a+e>n)&&(r.push(i),i=[],a=0),i.push(o),a+=e}return i.length>0&&r.push(i),r}function me(e,t,n){let r=n.doubleTap?`doubleTap`:n.holdMs>0?`longPress`:`tap`,i=r===`tap`&&a(e);return Array.from({length:n.count},(e,a)=>{let[o,c]=s(a,n.jitterPx);return{kind:r,x:t.x+o,y:t.y+c,...i?{synthesized:!0}:{},...n.holdMs>0?{durationMs:n.holdMs}:{},...a<n.count-1&&n.intervalMs>0?{pauseMs:n.intervalMs}:{}}})}function he(e){let t=e instanceof n?e.details?.completedSteps:void 0;return typeof t==`number`?t:0}function ge(e,t){if(t===0||!(e instanceof n)||!e.details)return e;let r=e.details.failedStepIndex;if(typeof r!=`number`)return e;let i=e.details.completedSteps;return new n(e.code,e.message,{...e.details,failedStepIndex:r+t,chunkStepIndex:r,...typeof i==`number`?{completedSteps:t+i}:{}},e.cause)}function w(e){let t=ve(e.sequenceResults),n=typeof e.completedSteps==`number`&&Number.isFinite(e.completedSteps)?e.completedSteps:t.filter(e=>e.ok).length,r=t.findIndex(e=>!e.ok),i=typeof e.failedStepIndex==`number`&&Number.isFinite(e.failedStepIndex)?e.failedStepIndex:r>=0?r:void 0;if(i!==void 0)throw _e(t,n,i);return{results:t,completedSteps:n,failedStepIndex:i}}function _e(e,t,r){let a=e[r],o=a?.kind??`step`,s=a?.errorMessage??`sequence step ${r} (${o}) failed`;return new n(i(a?.errorCode),s,{failedStepIndex:r,failedStepKind:o,completedSteps:t,sequenceResults:e,hint:`Run snapshot -i to inspect the current UI, then continue from the observed state.`})}function ve(e){return Array.isArray(e)?e.map(e=>{let t=e??{};return{ok:t.ok===!0,kind:typeof t.kind==`string`?t.kind:`unknown`,errorCode:typeof t.errorCode==`string`?t.errorCode:void 0,errorMessage:typeof t.errorMessage==`string`?t.errorMessage:void 0,gestureStartUptimeMs:typeof t.gestureStartUptimeMs==`number`?t.gestureStartUptimeMs:void 0,gestureEndUptimeMs:typeof t.gestureEndUptimeMs==`number`?t.gestureEndUptimeMs:void 0}}):[]}const ye=h.join(`apple`,`runner`,`AgentDeviceRunner`),be=h.join(`dist`,`apple`,`runner`,`AgentDeviceRunner`),xe=h.join(`apple`,`snapshot-presentation`),Se=h.join(`dist`,`apple`,`snapshot-presentation`);function T(e){let t=h.join(e,ye);return m.existsSync(t)?t:h.join(e,be)}function E(e){return h.join(T(e),`AgentDeviceRunner.xcodeproj`)}function D(e){let t=h.join(e,xe);return m.existsSync(t)?t:h.join(e,Se)}const O=new Set([`.build`,`.swiftpm`,`xcuserdata`]),k=new Set([`.DS_Store`]),A=new Set([`.xcuserstate`]),j=new Set([`.build`,`.swiftpm`,`SnapshotPresentationConformance`,`Tests`,`xcuserdata`]),M=new Map;function Ce(e){let t=[{path:T(e),ignoredDirectoryNames:O},{path:D(e),ignoredDirectoryNames:j}],n=Te(t),r=we(e,n),i=JSON.stringify(t.map(({path:e})=>e)),a=M.get(i);if(a?.fileStatsFingerprint===r)return a.sourceFingerprint;let o=p.createHash(`sha256`);for(let t of n){let n=h.relative(e,t);o.update(n),o.update(`\0`),o.update(m.readFileSync(t)),o.update(`\0`)}let s=o.digest(`hex`);return M.set(i,{fileStatsFingerprint:r,sourceFingerprint:s}),s}function we(e,t){let n=p.createHash(`sha256`);for(let r of t){let t=h.relative(e,r),i=m.statSync(r);n.update(t),n.update(`\0`),n.update(String(i.size)),n.update(`\0`),n.update(String(Math.trunc(i.mtimeMs))),n.update(`\0`)}return n.digest(`hex`)}function Te(e){return[...new Set(e.flatMap(({path:e,ignoredDirectoryNames:t})=>Ee(e,t)))].sort((e,t)=>e.localeCompare(t))}function Ee(e,t){return m.existsSync(e)?N(e,t,!1):[]}function N(e,t,n){let r=[];for(let i of m.readdirSync(e,{withFileTypes:!0})){let a=h.join(e,i.name);if(i.isDirectory()){if(t.has(i.name))continue;let e=n||Oe(i.name);r.push(...N(a,t,e))}else if(i.isFile()){if(n?De(i.name):!Ae(i.name))continue;r.push(a)}}return r}function De(e){return k.has(e)||A.has(h.extname(e))}function Oe(e){return e.endsWith(`.xcodeproj`)||e.endsWith(`.xcworkspace`)}const ke=new Set([`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`,`.xcscheme`,`.xcworkspacedata`]);function Ae(e){return ke.has(h.extname(e))}const je=h.join(ae.homedir(),`.agent-device`,`apple-runner`),Me=`.agent-device-runner-cache.json`,P=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`],F=`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_ISOLATION_CANARY`,Ne=`${F} -D AGENT_DEVICE_RUNNER_UNIT_TESTS`;function I(e){return e?.trim()??``}function L(e=l().env){return I(e.AGENT_DEVICE_IOS_BUNDLE_ID)||I(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function R(e=l().env){return I(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${L(e)}.uitests`}function z(e){let t=L(e),n=R(e);return Array.from(new Set([I(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}function Pe(e,t=re(),n){let r=te(e),{env:i}=l();return{schemaVersion:3,packageVersion:u(t),runnerSourceFingerprint:Ce(t),...f(ee(r,e.kind),n),platformName:r,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:d(e),runnerBundleBuildSettings:J(i),runnerSigningBuildSettings:q(i,e.kind===`device`,e),runnerPerformanceBuildSettings:Y(),runnerArchBuildSettings:X(i),runnerSandboxBuildArgs:Z(i)}}function Fe(e,t){let n=l().env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();return n?h.resolve(n):B(e,t)}function B(e,t){return h.join(Ie(e),V(t))}function Ie(e){return h.join(je,`derived`,ne(e))}function V(e){return`cache-${p.createHash(`sha256`).update(G(H(e))).digest(`hex`).slice(0,16)}`}function H(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function Le(e,t){let n=H(e),r=H(t);return[...new Set([...Object.keys(n),...Object.keys(r)])].sort((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=U(n[e]),i=U(r[e]);return t===i?[]:[{key:e,expected:W(t),actual:W(i)}]})}function U(e){return e===void 0?`(absent)`:G(e)}function W(e){return e.length<=300?e:`${e.slice(0,149)}…${e.slice(-149)}`}function G(e){return JSON.stringify(K(e))}function K(e){return Array.isArray(e)?e.map(e=>K(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,K(t)]))}function Re(e){return o(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function q(e=l().env,t=!1,n={platform:`apple`}){if(o(n))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let r=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,a=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,s=[`CODE_SIGN_STYLE=${a?`Manual`:`Automatic`}`];return r&&s.push(`DEVELOPMENT_TEAM=${r}`),i&&s.push(`CODE_SIGN_IDENTITY=${i}`),a&&s.push(`PROVISIONING_PROFILE_SPECIFIER=${a}`),s}function J(e=l().env){let t=L(e),n=R(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function Y(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function X(e=l().env){let t=e.AGENT_DEVICE_XCUITEST_ARCHS?.trim();return t?[`ARCHS=${t}`]:[]}function ze(e){let t=h.join(e,`Build`,`Intermediates.noindex`);return[`SYMROOT=${h.join(e,`Build`,`Products`)}`,`OBJROOT=${t}`,`SHARED_PRECOMPS_DIR=${h.join(t,`PrecompiledHeaders`)}`]}function Z(e=l().env){return[...P,`OTHER_SWIFT_FLAGS=${Be(e)}`]}function Be(e){return c(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?Ne:F}const Ve=/^\s*Build settings from command line:\s*$/,He=/^\s+([A-Z][A-Z0-9_]*)\s*=\s*(.*)$/,Q=/^([A-Z][A-Z0-9_]*)=(.*)$/,Ue=/^\s*Command line invocation:\s*$/;function We(e){let t;try{t=m.readFileSync(e,`utf8`)}catch{return null}let n=t.split(`
2
- `),r=new Map,i=!1,a=``;for(let[e,t]of n.entries()){if(Ue.test(t)){a=n[e+1]??``;continue}if(Ve.test(t)){i=!0;continue}if(!i)continue;let o=He.exec(t);if(!o)break;r.set(o[1],o[2].trimEnd())}return i?{settings:r,invocationLine:a}:null}function $(e){return[...e.runnerBundleBuildSettings,...e.runnerSigningBuildSettings,...e.runnerPerformanceBuildSettings,...e.runnerArchBuildSettings,...e.runnerSandboxBuildArgs]}function Ge(e){let t={};for(let n of $(e)){let e=Q.exec(n);e&&(t[e[1]]=e[2])}return t}function Ke(e,t){return $(e).filter(e=>!Q.test(e)).filter(e=>!t.includes(e)).map(e=>({key:`(invocation flag)`,expected:e,actual:`absent from the "Command line invocation:" line`}))}function qe(e,t){let n=We(t);return n?[...Object.entries(Ge(e)).filter(([e,t])=>{let r=n.settings.get(e);return r===void 0?t!==``:r!==t}).map(([e,t])=>({key:e,expected:t,actual:n.settings.get(e)??`(absent)`})),...Ke(e,n.invocationLine)]:[{key:`(build log)`,expected:`a "Build settings from command line:" block`,actual:`missing or unreadable log`}]}function Je(e,t){let r=qe(e,t);if(r.length!==0)throw new n(`COMMAND_FAILED`,`The Apple runner build did not use the settings its cache identity records`,{reason:`runner_build_settings_mismatch`,buildLogPath:t,differences:r,hint:`Align the build invocation with the runner cache identity resolvers, or rebuild without the cache.`})}var Ye=e({resolveRunnerContainerBundleIds:()=>z,withAppleRunnerProvider:()=>_});export{fe as C,_ as E,w as S,se as T,Z as _,Je as a,E as b,X as c,V as d,z as f,Y as g,Re as h,Le as i,ze as l,B as m,Me as n,Pe as o,Fe as p,H as r,L as s,Ye as t,J as u,q as v,oe as w,C as x,G as y};
1
+ import{r as e}from"./rolldown-runtime.js";import{G as t,K as n,R as r,ut as i}from"./sdk-contracts.js";import{T as a,V as o}from"./sdk-device.js";import{r as s}from"./touch-runtime.js";import{A as c,f as l,g as u,v as d}from"./host2.js";import{a as ee,f as te,o as ne,s as re,u as ie}from"./apple-runner-platform.js";import{n as ae}from"./runner-toolchain-probe.js";import{AsyncLocalStorage as oe}from"node:async_hooks";import f from"node:crypto";import p from"node:fs";import se from"node:os";import m from"node:path";const h=new oe;function g(e,t){return{runCommand:e,...t}}function ce(e,t,n={}){let r=le(e,n);return v(r?r.provider:t)}function le(e,t={}){let n=h.getStore();return n&&n.deviceId===e.id&&(n.requestId?n.requestId===t.requestId:!t.requestId)?n:void 0}async function _(e,t,n){if(!e)return await n();let r={provider:v(e),deviceId:t.deviceId,requestId:t.requestId};return await h.run(r,n)}function v(e){return typeof e==`function`?{runCommand:e,hasLiveSession:()=>!0}:e}const y=[`tap`,`doubleTap`,`longPress`];function ue(e){return typeof e==`string`&&y.includes(e)}function b(e,n){return t(new r(`INVALID_ARGS`,e,{...n,reason:`runner_sequence_invalid`}),`no`)}function x(e,t,n){return b(n,{stepIndex:e,kind:typeof t==`string`?t:void 0})}function de(e){if(!Array.isArray(e)||e.length===0)throw b(`sequence requires at least one step`,{stepCount:Array.isArray(e)?e.length:0});if(e.length>20)throw b(`sequence accepts at most 20 steps, received ${e.length}`,{stepCount:e.length,maxSteps:20});e.forEach((e,t)=>fe(e,t))}function fe(e,t){if(!ue(e.kind))throw x(t,e.kind,`sequence step ${t} has unsupported kind "${String(e.kind)}"; allowed: ${y.join(`, `)}`);if(!Number.isFinite(e.x)||!Number.isFinite(e.y))throw x(t,e.kind,`sequence step ${t} (${e.kind}) requires finite x and y`);e.durationMs!==void 0&&S(e.durationMs,0,1e4,t,e.kind,`durationMs`),e.pauseMs!==void 0&&S(e.pauseMs,0,1e4,t,e.kind,`pauseMs`)}function S(e,t,n,r,i,a){if(!Number.isFinite(e)||e<t||e>n)throw x(r,i,`sequence step ${r} (${i}) ${a} must be between ${t} and ${n}`)}function C(e,t){return de(e),{command:`sequence`,steps:e,appBundleId:t}}async function pe(e,t,r,i,a){let o=me(he(e,t,r),20).map(e=>C(e,i)),s,c,l=0,u=[],d=0;for(let e of o){let t;try{t=await a(e)}catch(e){throw n(e,l)}s??=t,c=t;let r;try{r=w(t)}catch(e){throw n(_e(e,d),l+ge(e))}l+=r.completedSteps,u.push(...r.results),d+=e.steps?.length??0}return{...s??{},completedSteps:l,sequenceResults:u,...c?.gestureEndUptimeMs===void 0?{}:{gestureEndUptimeMs:c.gestureEndUptimeMs},timingMode:`runner-sequence`}}function me(e,t,n=2e4){let r=[],i=[],a=0;for(let o of e){let e=(o.durationMs??0)+(o.pauseMs??0)+250;i.length>0&&(i.length>=t||a+e>n)&&(r.push(i),i=[],a=0),i.push(o),a+=e}return i.length>0&&r.push(i),r}function he(e,t,n){let r=n.doubleTap?`doubleTap`:n.holdMs>0?`longPress`:`tap`,i=r===`tap`&&o(e);return Array.from({length:n.count},(e,a)=>{let[o,c]=s(a,n.jitterPx);return{kind:r,x:t.x+o,y:t.y+c,...i?{synthesized:!0}:{},...n.holdMs>0?{durationMs:n.holdMs}:{},...a<n.count-1&&n.intervalMs>0?{pauseMs:n.intervalMs}:{}}})}function ge(e){let t=e instanceof r?e.details?.completedSteps:void 0;return typeof t==`number`?t:0}function _e(e,t){if(t===0||!(e instanceof r)||!e.details)return e;let n=e.details.failedStepIndex;if(typeof n!=`number`)return e;let i=e.details.completedSteps;return new r(e.code,e.message,{...e.details,failedStepIndex:n+t,chunkStepIndex:n,...typeof i==`number`?{completedSteps:t+i}:{}},e.cause)}function w(e){let t=ye(e.sequenceResults),n=typeof e.completedSteps==`number`&&Number.isFinite(e.completedSteps)?e.completedSteps:t.filter(e=>e.ok).length,r=t.findIndex(e=>!e.ok),i=typeof e.failedStepIndex==`number`&&Number.isFinite(e.failedStepIndex)?e.failedStepIndex:r>=0?r:void 0;if(i!==void 0)throw ve(t,n,i);return{results:t,completedSteps:n,failedStepIndex:i}}function ve(e,t,n){let a=e[n],o=a?.kind??`step`,s=a?.errorMessage??`sequence step ${n} (${o}) failed`;return new r(i(a?.errorCode),s,{failedStepIndex:n,failedStepKind:o,completedSteps:t,sequenceResults:e,hint:`Run snapshot -i to inspect the current UI, then continue from the observed state.`})}function ye(e){return Array.isArray(e)?e.map(e=>{let t=e??{};return{ok:t.ok===!0,kind:typeof t.kind==`string`?t.kind:`unknown`,errorCode:typeof t.errorCode==`string`?t.errorCode:void 0,errorMessage:typeof t.errorMessage==`string`?t.errorMessage:void 0,gestureStartUptimeMs:typeof t.gestureStartUptimeMs==`number`?t.gestureStartUptimeMs:void 0,gestureEndUptimeMs:typeof t.gestureEndUptimeMs==`number`?t.gestureEndUptimeMs:void 0}}):[]}const be=m.join(`apple`,`runner`,`AgentDeviceRunner`),xe=m.join(`dist`,`apple`,`runner`,`AgentDeviceRunner`),Se=m.join(`apple`,`snapshot-presentation`),Ce=m.join(`dist`,`apple`,`snapshot-presentation`);function T(e){let t=m.join(e,be);return p.existsSync(t)?t:m.join(e,xe)}function E(e){return m.join(T(e),`AgentDeviceRunner.xcodeproj`)}function D(e){let t=m.join(e,Se);return p.existsSync(t)?t:m.join(e,Ce)}const O=new Set([`.build`,`.swiftpm`,`xcuserdata`]),k=new Set([`.DS_Store`]),A=new Set([`.xcuserstate`]),we=new Set([`.build`,`.swiftpm`,`SnapshotPresentationConformance`,`Tests`,`xcuserdata`]),j=new Map;function Te(e){let t=[{path:T(e),ignoredDirectoryNames:O},{path:D(e),ignoredDirectoryNames:we}],n=De(t),r=Ee(e,n),i=JSON.stringify(t.map(({path:e})=>e)),a=j.get(i);if(a?.fileStatsFingerprint===r)return a.sourceFingerprint;let o=f.createHash(`sha256`);for(let t of n){let n=m.relative(e,t);o.update(n),o.update(`\0`),o.update(p.readFileSync(t)),o.update(`\0`)}let s=o.digest(`hex`);return j.set(i,{fileStatsFingerprint:r,sourceFingerprint:s}),s}function Ee(e,t){let n=f.createHash(`sha256`);for(let r of t){let t=m.relative(e,r),i=p.statSync(r);n.update(t),n.update(`\0`),n.update(String(i.size)),n.update(`\0`),n.update(String(Math.trunc(i.mtimeMs))),n.update(`\0`)}return n.digest(`hex`)}function De(e){return[...new Set(e.flatMap(({path:e,ignoredDirectoryNames:t})=>Oe(e,t)))].sort((e,t)=>e.localeCompare(t))}function Oe(e,t){return p.existsSync(e)?M(e,t,!1):[]}function M(e,t,n){let r=[];for(let i of p.readdirSync(e,{withFileTypes:!0})){let a=m.join(e,i.name);if(i.isDirectory()){if(t.has(i.name))continue;let e=n||Ae(i.name);r.push(...M(a,t,e))}else if(i.isFile()){if(n?ke(i.name):!Me(i.name))continue;r.push(a)}}return r}function ke(e){return k.has(e)||A.has(m.extname(e))}function Ae(e){return e.endsWith(`.xcodeproj`)||e.endsWith(`.xcworkspace`)}const je=new Set([`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`,`.xcscheme`,`.xcworkspacedata`]);function Me(e){return je.has(m.extname(e))}const N=m.join(se.homedir(),`.agent-device`,`apple-runner`),Ne=`.agent-device-runner-cache.json`,Pe=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`],P=`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_ISOLATION_CANARY`,Fe=`${P} -D AGENT_DEVICE_RUNNER_UNIT_TESTS`;function F(e){return e?.trim()??``}function I(e=u().env){return F(e.AGENT_DEVICE_IOS_BUNDLE_ID)||F(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function L(e=u().env){return F(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${I(e)}.uitests`}function R(e){let t=I(e),n=L(e);return Array.from(new Set([F(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}function Ie(e,t=l(),n){let r=ie(e),{env:i}=u();return{schemaVersion:3,packageVersion:c(t),runnerSourceFingerprint:Te(t),...ae(te(r,e.kind),n),platformName:r,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:ee(e),runnerBundleBuildSettings:q(i),runnerSigningBuildSettings:K(i,e.kind===`device`,e),runnerPerformanceBuildSettings:J(),runnerArchBuildSettings:Y(i),runnerSandboxBuildArgs:X(i)}}function Le(e,t){return re(u().env)??z(e,t)}function Re(e){let t=m.join(N,`derived`);return e===`ios`?t:m.join(t,e)}function z(e,t){return m.join(ze(e),B(t))}function ze(e){return m.join(N,`derived`,ne(e))}function B(e){return`cache-${f.createHash(`sha256`).update(W(V(e))).digest(`hex`).slice(0,16)}`}function V(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function Be(e,t){let n=V(e),r=V(t);return[...new Set([...Object.keys(n),...Object.keys(r)])].sort((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=H(n[e]),i=H(r[e]);return t===i?[]:[{key:e,expected:U(t),actual:U(i)}]})}function H(e){return e===void 0?`(absent)`:W(e)}function U(e){return e.length<=300?e:`${e.slice(0,149)}…${e.slice(-149)}`}function W(e){return JSON.stringify(G(e))}function G(e){return Array.isArray(e)?e.map(e=>G(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,G(t)]))}function Ve(e){return a(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function K(e=u().env,t=!1,n={platform:`apple`}){if(a(n))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let r=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,o=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,s=[`CODE_SIGN_STYLE=${o?`Manual`:`Automatic`}`];return r&&s.push(`DEVELOPMENT_TEAM=${r}`),i&&s.push(`CODE_SIGN_IDENTITY=${i}`),o&&s.push(`PROVISIONING_PROFILE_SPECIFIER=${o}`),s}function q(e=u().env){let t=I(e),n=L(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function J(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function Y(e=u().env){let t=e.AGENT_DEVICE_XCUITEST_ARCHS?.trim();return t?[`ARCHS=${t}`]:[]}function He(e){let t=m.join(e,`Build`,`Intermediates.noindex`);return[`SYMROOT=${m.join(e,`Build`,`Products`)}`,`OBJROOT=${t}`,`SHARED_PRECOMPS_DIR=${m.join(t,`PrecompiledHeaders`)}`]}function X(e=u().env){return[...Pe,`OTHER_SWIFT_FLAGS=${Ue(e)}`]}function Ue(e){return d(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?Fe:P}const We=/^\s*Build settings from command line:\s*$/,Ge=/^\s+([A-Z][A-Z0-9_]*)\s*=\s*(.*)$/,Z=/^([A-Z][A-Z0-9_]*)=(.*)$/,Q=/^\s*Command line invocation:\s*$/;function Ke(e){let t;try{t=p.readFileSync(e,`utf8`)}catch{return null}let n=t.split(`
2
+ `),r=new Map,i=!1,a=``;for(let[e,t]of n.entries()){if(Q.test(t)){a=n[e+1]??``;continue}if(We.test(t)){i=!0;continue}if(!i)continue;let o=Ge.exec(t);if(!o)break;r.set(o[1],o[2].trimEnd())}return i?{settings:r,invocationLine:a}:null}function $(e){return[...e.runnerBundleBuildSettings,...e.runnerSigningBuildSettings,...e.runnerPerformanceBuildSettings,...e.runnerArchBuildSettings,...e.runnerSandboxBuildArgs]}function qe(e){let t={};for(let n of $(e)){let e=Z.exec(n);e&&(t[e[1]]=e[2])}return t}function Je(e,t){return $(e).filter(e=>!Z.test(e)).filter(e=>!t.includes(e)).map(e=>({key:`(invocation flag)`,expected:e,actual:`absent from the "Command line invocation:" line`}))}function Ye(e,t){let n=Ke(t);return n?[...Object.entries(qe(e)).filter(([e,t])=>{let r=n.settings.get(e);return r===void 0?t!==``:r!==t}).map(([e,t])=>({key:e,expected:t,actual:n.settings.get(e)??`(absent)`})),...Je(e,n.invocationLine)]:[{key:`(build log)`,expected:`a "Build settings from command line:" block`,actual:`missing or unreadable log`}]}function Xe(e,t){let n=Ye(e,t);if(n.length!==0)throw new r(`COMMAND_FAILED`,`The Apple runner build did not use the settings its cache identity records`,{reason:`runner_build_settings_mismatch`,buildLogPath:t,differences:n,hint:`Align the build invocation with the runner cache identity resolvers, or rebuild without the cache.`})}var Ze=e({resolveRunnerContainerBundleIds:()=>R,withAppleRunnerProvider:()=>_});export{w as C,_ as D,ce as E,C as S,g as T,X as _,Xe as a,W as b,Y as c,B as d,R as f,J as g,Ve as h,Be as i,He as l,z as m,Ne as n,Ie as o,Le as p,V as r,I as s,Ze as t,q as u,Re as v,pe as w,E as x,K as y};
@@ -1 +1 @@
1
- import{R as e,s as t}from"./sdk-contracts.js";import{in as n}from"./sdk-batch.js";import{n as r}from"./request-runtime-binding.js";function i(e,n){return t(`UNSUPPORTED_OPERATION`,`${e} is not supported on this device`,{reason:n.reason},n.hint?{hint:n.hint}:void 0)}async function a(e){let t=await c(e.inspectFacts)(e.device);for(let r of e.required){let a=t.operations[r],o=e.subject===void 0?a:n(a,e.subject);if(!o.available)return{type:`response`,response:e.unavailableResponse?e.unavailableResponse(o):i(e.command,o)}}return{type:`admitted`,bind:l(e.bindDevice)}}async function o(e){let t=await a({...e,required:e.use.required});if(t.type===`response`)return t;let n=await t.bind(e.device,e.use);return e.readiness&&await r(n,e.platformServices),{type:`runtime`,runtime:n}}async function s(e,t){let n=await o(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:async({dispatchContext:e})=>await t(r,e)}}function c(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`,{reason:`runtime-gateway-missing`})}function l(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime binding is unavailable.`,{reason:`runtime-gateway-missing`})}export{i,o as n,s as r,a as t};
1
+ import{R as e,s as t}from"./sdk-contracts.js";import{_n as n}from"./sdk-batch.js";import{n as r}from"./request-runtime-binding.js";function i(e,n){return t(`UNSUPPORTED_OPERATION`,`${e} is not supported on this device`,{reason:n.reason},n.hint?{hint:n.hint}:void 0)}async function a(e){let t=await c(e.inspectFacts)(e.device);for(let r of e.required){let a=t.operations[r],o=e.subject===void 0?a:n(a,e.subject);if(!o.available)return{type:`response`,response:e.unavailableResponse?e.unavailableResponse(o):i(e.command,o)}}return{type:`admitted`,bind:l(e.bindDevice)}}async function o(e){let t=await a({...e,required:e.use.required});if(t.type===`response`)return t;let n=await t.bind(e.device,e.use);return e.readiness&&await r(n,e.platformServices),{type:`runtime`,runtime:n}}async function s(e,t){let n=await o(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:async({dispatchContext:e})=>await t(r,e)}}function c(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`,{reason:`runtime-gateway-missing`})}function l(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime binding is unavailable.`,{reason:`runtime-gateway-missing`})}export{i,o as n,s as r,a as t};
@@ -1 +1 @@
1
- import{R as e}from"./sdk-contracts.js";import{O as t}from"./sdk-device.js";import{on as n}from"./sdk-batch.js";const r={support:`supported`},i={support:`unsupported`},a={lease:r,inventory:{support:`partial`,note:`Inventory exposes only the leased cloud device, not the provider catalog.`},install:{support:`partial`,note:`Requires provider-specific upload or a path visible to the remote Appium server.`},snapshot:{support:`partial`,note:`Uses Appium page source XML, not agent-device native snapshot backends.`},screenshot:r,tap:r,doubleTap:r,longPress:r,swipe:r,scroll:{support:`partial`,note:`Implemented as viewport-relative W3C pointer gestures.`},fill:r,type:r,keyboard:{support:`partial`,note:"Enter presses Android keycode 66 through `mobile: pressKey` and types a newline into the focused iOS field; dismiss uses the Appium hide-keyboard route, and Android status uses the Appium keyboard probe."},back:r,home:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},orientation:{support:`partial`,note:`Uses the WebDriver rotation/orientation endpoints; four-way rotation collapses to portrait/landscape on drivers that only accept the two-way endpoint. Rotates the current display, so an activity that does not pin its orientation may need rotating again once it is foreground.`},appSwitcher:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},volumeUp:{support:`partial`,note:`Uses provider/Appium mobile pressButton volumeup support where available; real devices only.`},volumeDown:{support:`partial`,note:`Uses provider/Appium mobile pressButton volumedown support where available; real devices only.`},power:{support:`unsupported`,note:`XCUITest exposes no power press to Appium on any iOS session.`},tvRemote:i,"clipboard.read":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},"clipboard.write":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},settings:i,alert:i,pinch:i,rotateGesture:i,transformGesture:i,tapGesture:i,logs:i,record:i,artifacts:i,portReverse:i,nativeSnapshotBackend:{support:`unsupported`,note:`Cloud WebDriver cannot upload or run agent-device native runner/helper backends.`}};function o(e){let t=e.platform===`android`?{...a,volumeUp:{support:`partial`,note:`Uses provider/Appium mobile pressKey keycode 24 where available.`},volumeDown:{support:`partial`,note:`Uses provider/Appium mobile pressKey keycode 25 where available.`},power:{support:`partial`,note:`Uses provider/Appium mobile pressKey keycode 26 where available; the screen state after the press is the device's own.`}}:a;return{provider:e.provider,platform:e.platform,snapshotBackend:e.platform===`ios`?`xctest`:`android`,snapshotSource:`appium-page-source`,operations:l(t,e.overrides)}}function s(e,t){return e.operations[t].support!==`unsupported`}function c(e,t){let n=e.operations[t],r=n.note?` ${n.note}`:``;return`${e.provider} WebDriver runtime does not support ${t}.${r}`}function l(e,t){let n={...e};for(let[r,i]of Object.entries(t??{}))n[r]=typeof i==`string`?{...e[r],support:i}:{...e[r],...i};return n}function u(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function d(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:p(e?.launchTarget,n,r)}}function f(e){return e===`ios`?`xctest`:`android`}function p(...e){return e.find(e=>e!==void 0)}const m=n(`owner-capability-missing`,`The WebDriver provider session is no longer active for this device.`);function h(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await _(e,o,t,n,r.uploadPath,i,a);return await o.client.installApp(s?.appReference??r.appPath,a),d(s,i)},n=async(e,n,r,i,a)=>await t(e,n,{appPath:r,uploadPath:r},i,a);return Object.freeze({fact:t=>g(e.findSessionForDevice(t)),installApp:n,installInstallablePath:async(e,t,r,i)=>await n(e,``,t,r,i),deployApp:async(e,t,r)=>v(await n(e,t.app,t.appPath,{relaunch:t.replaceExisting,appIdentifierHint:t.app,packageNameHint:t.app},r),t.app),deployMaterializedApp:async(e,n,r)=>v(await t(e,``,{appPath:n.artifact.installablePath,uploadPath:n.artifact.uploadPath??n.artifact.installablePath},{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function g(e){return e?s(e.capabilities,`install`)?Object.freeze({available:!0}):n(`owner-capability-missing`,c(e.capabilities,`install`)):m}async function _(n,r,i,a,o,l,u){if(!s(r.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,c(r.capabilities,`install`),{provider:n.provider,deviceId:i.id,platform:t(i)});let d=r.prepared.uploadApp??n.uploadApp;if(d)return await d({provider:n.provider,lease:r.lease,device:i,app:a,appPath:o,options:l,signal:u})}function v(t,n){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...t.bundleId?{bundleId:t.bundleId}:{},...t.packageName?{packageName:t.packageName}:{},...t.appName?{appName:t.appName}:{},...t.launchTarget??n?{launchTarget:t.launchTarget??n}:{}}}export{s as a,u as i,m as n,o,f as r,c as s,h as t};
1
+ import{R as e}from"./sdk-contracts.js";import{I as t}from"./sdk-device.js";import{yn as n}from"./sdk-batch.js";const r={support:`supported`},i={support:`unsupported`},a={support:`partial`,note:`Uses provider/Appium mobile pressKey support where available.`},o={lease:r,inventory:{support:`partial`,note:`Inventory exposes only the leased cloud device, not the provider catalog.`},install:{support:`partial`,note:`Requires provider-specific upload or a path visible to the remote Appium server.`},snapshot:{support:`partial`,note:`Uses Appium page source XML, not agent-device native snapshot backends.`},screenshot:r,tap:r,doubleTap:r,longPress:r,swipe:r,scroll:{support:`partial`,note:`Implemented as viewport-relative W3C pointer gestures.`},fill:r,type:r,keyboard:{support:`partial`,note:"Enter presses Android keycode 66 through `mobile: pressKey` and types a newline into the focused iOS field; dismiss uses the Appium hide-keyboard route, and Android status uses the Appium keyboard probe."},back:r,home:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},orientation:{support:`partial`,note:`Uses the WebDriver rotation/orientation endpoints; four-way rotation collapses to portrait/landscape on drivers that only accept the two-way endpoint. Rotates the current display, so an activity that does not pin its orientation may need rotating again once it is foreground.`},appSwitcher:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},volumeUp:{support:`partial`,note:`Uses provider/Appium mobile pressButton volumeup support where available; real devices only.`},volumeDown:{support:`partial`,note:`Uses provider/Appium mobile pressButton volumedown support where available; real devices only.`},power:i,mute:i,sleep:i,wake:i,mediaPlayPause:i,mediaNext:i,mediaPrevious:i,mediaRewind:i,mediaFastForward:i,tvRemote:i,"clipboard.read":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},"clipboard.write":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},settings:i,alert:i,pinch:i,rotateGesture:i,transformGesture:i,tapGesture:i,logs:i,record:i,artifacts:i,portReverse:i,nativeSnapshotBackend:{support:`unsupported`,note:`Cloud WebDriver cannot upload or run agent-device native runner/helper backends.`}};function s(e){let t=e.platform===`android`?{...o,volumeUp:a,volumeDown:a,power:a,mute:a,sleep:a,wake:a,mediaPlayPause:a,mediaNext:a,mediaPrevious:a,mediaRewind:a,mediaFastForward:a}:o;return{provider:e.provider,platform:e.platform,snapshotBackend:e.platform===`ios`?`xctest`:`android`,snapshotSource:`appium-page-source`,operations:u(t,e.overrides)}}function c(e,t){return e.operations[t].support!==`unsupported`}function l(e,t){let n=e.operations[t],r=n.note?` ${n.note}`:``;return`${e.provider} WebDriver runtime does not support ${t}.${r}`}function u(e,t){let n={...e};for(let[r,i]of Object.entries(t??{}))n[r]=typeof i==`string`?{...e[r],support:i}:{...e[r],...i};return n}function d(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function f(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:m(e?.launchTarget,n,r)}}function p(e){return e===`ios`?`xctest`:`android`}function m(...e){return e.find(e=>e!==void 0)}const h=n(`owner-capability-missing`,`The WebDriver provider session is no longer active for this device.`);function g(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await v(e,o,t,n,r.uploadPath,i,a);return await o.client.installApp(s?.appReference??r.appPath,a),f(s,i)},n=async(e,n,r,i,a)=>await t(e,n,{appPath:r,uploadPath:r},i,a);return Object.freeze({fact:t=>_(e.findSessionForDevice(t)),installApp:n,installInstallablePath:async(e,t,r,i)=>await n(e,``,t,r,i),deployApp:async(e,t,r)=>y(await n(e,t.app,t.appPath,{relaunch:t.replaceExisting,appIdentifierHint:t.app,packageNameHint:t.app},r),t.app),deployMaterializedApp:async(e,n,r)=>y(await t(e,``,{appPath:n.artifact.installablePath,uploadPath:n.artifact.uploadPath??n.artifact.installablePath},{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function _(e){return e?c(e.capabilities,`install`)?Object.freeze({available:!0}):n(`owner-capability-missing`,l(e.capabilities,`install`)):h}async function v(n,r,i,a,o,s,u){if(!c(r.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,l(r.capabilities,`install`),{provider:n.provider,deviceId:i.id,platform:t(i)});let d=r.prepared.uploadApp??n.uploadApp;if(d)return await d({provider:n.provider,lease:r.lease,device:i,app:a,appPath:o,options:s,signal:u})}function y(t,n){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...t.bundleId?{bundleId:t.bundleId}:{},...t.packageName?{packageName:t.packageName}:{},...t.appName?{appName:t.appName}:{},...t.launchTarget??n?{launchTarget:t.launchTarget??n}:{}}}export{c as a,d as i,h as n,s as o,p as r,l as s,g as t};