agent-device 0.21.13 → 0.21.15

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 (298) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.13.apk → agent-device-android-ime-helper-0.21.15.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.15.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.13.manifest.json → agent-device-android-ime-helper-0.21.15.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.15.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.15.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.13.manifest.json → agent-device-android-snapshot-helper-0.21.15.manifest.json} +6 -6
  7. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +11 -1
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +110 -2
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +4 -2
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerMainOwnedState.swift +27 -0
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedTextEntry.h +8 -2
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedTextEntry.m +26 -1
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +12 -19
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +59 -20
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift +2 -3
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +179 -91
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +21 -24
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -1
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+GestureExecution.swift +9 -13
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +36 -49
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+MainThreadWork.swift +11 -15
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +136 -29
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +20 -21
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +3 -0
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +6 -5
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollDragExecution.swift +12 -24
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +22 -42
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +15 -18
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift +73 -31
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +20 -11
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCaptureTarget.swift +9 -7
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotExecution.swift +5 -4
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +2 -2
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +51 -19
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +5 -2
  36. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +78 -10
  37. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +32 -2
  38. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +7 -4
  39. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +23 -0
  40. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +17 -10
  41. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +8 -9
  42. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +9 -15
  43. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +12 -11
  44. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotCoordinateSpace.swift +16 -19
  45. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotGeometry.swift +24 -9
  46. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +66 -10
  47. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationInvariant.swift +12 -10
  48. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +1 -0
  49. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +27 -5
  50. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFoldProjection.swift +1 -0
  51. package/dist/src/adapter.js +1 -1
  52. package/dist/src/adb-executor.js +1 -1
  53. package/dist/src/adb-failure.js +1 -1
  54. package/dist/src/adb-transport.js +1 -1
  55. package/dist/src/agent-browser-provider.js +1 -1
  56. package/dist/src/agent-browser-tool.js +1 -1
  57. package/dist/src/agent-device-client.js +2 -2
  58. package/dist/src/ai-sdk.js +1 -1
  59. package/dist/src/alert-runtime.js +1 -1
  60. package/dist/src/android-adb.d.ts +1 -8
  61. package/dist/src/android-input-ownership.js +1 -1
  62. package/dist/src/android-snapshot-quality.js +1 -0
  63. package/dist/src/android-system-chrome.js +1 -1
  64. package/dist/src/android.js +1 -1
  65. package/dist/src/app-catalog.js +1 -1
  66. package/dist/src/app-deployment-resolution.js +1 -1
  67. package/dist/src/app-inventory.js +1 -1
  68. package/dist/src/app-launch.js +1 -1
  69. package/dist/src/app-lifecycle.js +1 -1
  70. package/dist/src/app-lifecycle2.js +1 -1
  71. package/dist/src/app-log-files.js +1 -1
  72. package/dist/src/app-log-runtime2.js +1 -1
  73. package/dist/src/app-resolution.js +2 -2
  74. package/dist/src/apple-runner-platform.js +1 -1
  75. package/dist/src/application-lifecycle-interaction.js +1 -1
  76. package/dist/src/archive.js +1 -1
  77. package/dist/src/artifact-download.js +1 -1
  78. package/dist/src/auth-session.js +1 -1
  79. package/dist/src/auth.js +1 -1
  80. package/dist/src/backend-snapshot-options.js +1 -1
  81. package/dist/src/boot-diagnostics.js +1 -1
  82. package/dist/src/capture-disclosure.js +1 -1
  83. package/dist/src/capture.js +1 -1
  84. package/dist/src/cli-config.js +1 -1
  85. package/dist/src/cli-help.js +2 -2
  86. package/dist/src/cli.js +4 -4
  87. package/dist/src/click-button.js +1 -1
  88. package/dist/src/client-metro.js +1 -1
  89. package/dist/src/client-types.d.ts +102 -95
  90. package/dist/src/clipboard-shell-response.js +1 -1
  91. package/dist/src/command-schema.js +1 -1
  92. package/dist/src/command-tools.js +3 -3
  93. package/dist/src/connection-runtime.js +1 -1
  94. package/dist/src/connection.js +1 -1
  95. package/dist/src/contracts.d.ts +1 -1
  96. package/dist/src/contracts.js +1 -1
  97. package/dist/src/daemon-client-lifecycle.js +1 -1
  98. package/dist/src/daemon.js +1 -1
  99. package/dist/src/debug-symbols-facade.js +1 -1
  100. package/dist/src/device-claim-rule.js +2 -2
  101. package/dist/src/device-input-state.d.ts +15 -2
  102. package/dist/src/device-inventory-context.js +1 -1
  103. package/dist/src/device-rotation.js +1 -1
  104. package/dist/src/device-selection-resolver.js +1 -1
  105. package/dist/src/device-session.js +1 -1
  106. package/dist/src/device-shell.js +1 -1
  107. package/dist/src/device2.js +1 -1
  108. package/dist/src/devicectl.js +1 -1
  109. package/dist/src/diagnostics.js +1 -1
  110. package/dist/src/dispatch-resolve.js +1 -1
  111. package/dist/src/doctor2.js +1 -1
  112. package/dist/src/engine-eval-script.js +1 -1
  113. package/dist/src/error.js +1 -1
  114. package/dist/src/exec.js +1 -1
  115. package/dist/src/file.js +1 -1
  116. package/dist/src/find.js +1 -1
  117. package/dist/src/format.js +1 -1
  118. package/dist/src/gesture-plan-types.d.ts +1 -1
  119. package/dist/src/gesture-plan.js +1 -1
  120. package/dist/src/gesture-runtime.js +1 -1
  121. package/dist/src/harmonyos.js +1 -1
  122. package/dist/src/helper.js +2 -2
  123. package/dist/src/human-control-contract.js +1 -1
  124. package/dist/src/human-control.js +1 -1
  125. package/dist/src/index.d.ts +7 -3
  126. package/dist/src/index.js +1 -1
  127. package/dist/src/input-actions.js +1 -1
  128. package/dist/src/input-actions2.js +1 -1
  129. package/dist/src/install-artifact-facade.js +1 -1
  130. package/dist/src/install-source-network-transport.js +1 -1
  131. package/dist/src/install-source2.js +1 -1
  132. package/dist/src/interaction-positionals.js +1 -1
  133. package/dist/src/interaction-ref-policy.js +1 -1
  134. package/dist/src/interaction2.js +1 -1
  135. package/dist/src/interactor-operation-binding.js +1 -1
  136. package/dist/src/interactor.js +4 -4
  137. package/dist/src/interactor2.js +1 -1
  138. package/dist/src/interactors.js +1 -1
  139. package/dist/src/internal/bin.js +1 -1
  140. package/dist/src/internal/daemon.js +2 -2
  141. package/dist/src/internal/png-worker.js +1 -1
  142. package/dist/src/internal/run-script-http-child.js +1 -1
  143. package/dist/src/inventory.js +1 -1
  144. package/dist/src/inventory2.js +1 -1
  145. package/dist/src/inventory3.js +1 -1
  146. package/dist/src/inventory5.js +1 -1
  147. package/dist/src/ios-snapshot-acquisition.js +1 -1
  148. package/dist/src/ios-snapshot-engine.js +1 -0
  149. package/dist/src/ios-snapshot-runtime.js +1 -1
  150. package/dist/src/lease.js +1 -1
  151. package/dist/src/limrun-download-file.js +1 -1
  152. package/dist/src/limrun-runtime-dependencies.js +1 -1
  153. package/dist/src/limrun.d.ts +16 -3
  154. package/dist/src/linux.js +1 -1
  155. package/dist/src/location-coordinates.js +1 -1
  156. package/dist/src/managed-device-scope.js +1 -1
  157. package/dist/src/mechanics.js +17 -17
  158. package/dist/src/mobile-snapshot-semantics.js +1 -1
  159. package/dist/src/multitouch-support.js +1 -1
  160. package/dist/src/native-build-cache.js +1 -0
  161. package/dist/src/observation.js +1 -1
  162. package/dist/src/overlay.js +3 -0
  163. package/dist/src/parameterized-recorded-fill.js +1 -1
  164. package/dist/src/perf-facade.js +1 -1
  165. package/dist/src/perf-runtime-operation-builder.js +1 -1
  166. package/dist/src/perf-runtime-plan.js +1 -1
  167. package/dist/src/perf-target.js +2 -2
  168. package/dist/src/perf.js +1 -1
  169. package/dist/src/physical-device-control.js +1 -1
  170. package/dist/src/platform-runtime-host.js +1 -1
  171. package/dist/src/platform-runtime-managed-owner.js +1 -1
  172. package/dist/src/platform-runtime-open-target.js +1 -1
  173. package/dist/src/platform-runtime-operation-host.js +4 -4
  174. package/dist/src/platform-runtime-runtime-hints.js +1 -1
  175. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  176. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  177. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  178. package/dist/src/platform-runtime.js +1 -1
  179. package/dist/src/platform-runtime2.js +1 -1
  180. package/dist/src/png-crop-bytes.js +1 -1
  181. package/dist/src/png-size.js +1 -1
  182. package/dist/src/png-worker-client.js +1 -1
  183. package/dist/src/png.js +1 -1
  184. package/dist/src/prepare-kind.js +1 -1
  185. package/dist/src/provider-session-ownership.js +1 -1
  186. package/dist/src/provider-webdriver.js +1 -1
  187. package/dist/src/proxy.js +1 -1
  188. package/dist/src/quality-warnings.js +1 -1
  189. package/dist/src/react-native.js +1 -1
  190. package/dist/src/record-runtime.js +1 -1
  191. package/dist/src/recording.js +1 -1
  192. package/dist/src/rect-center.js +1 -1
  193. package/dist/src/register-builtins.js +1 -1
  194. package/dist/src/registry.js +36 -36
  195. package/dist/src/remote-config2.js +1 -1
  196. package/dist/src/replay-divergence.js +1 -1
  197. package/dist/src/replay.js +1 -1
  198. package/dist/src/reporting.js +1 -1
  199. package/dist/src/request-admission.js +1 -1
  200. package/dist/src/request-cancel.js +1 -1
  201. package/dist/src/request-runtime-binding.js +1 -1
  202. package/dist/src/retry.js +1 -1
  203. package/dist/src/runner-cache-metadata.js +1 -1
  204. package/dist/src/runner-client.js +1 -1
  205. package/dist/src/runner-dev-tools-security.js +1 -1
  206. package/dist/src/runner-device-readiness.js +1 -1
  207. package/dist/src/runner-disposal.js +1 -1
  208. package/dist/src/runner-error-classification.js +1 -1
  209. package/dist/src/runner.js +1 -1
  210. package/dist/src/runtime-transport-hints.js +1 -1
  211. package/dist/src/runtime.js +1 -3
  212. package/dist/src/runtime10.js +2 -2
  213. package/dist/src/runtime2.js +4 -4
  214. package/dist/src/runtime3.js +1 -1
  215. package/dist/src/runtime4.js +5 -5
  216. package/dist/src/runtime5.js +1 -1
  217. package/dist/src/runtime6.js +1 -1
  218. package/dist/src/runtime7.js +1 -1
  219. package/dist/src/runtime8.js +1 -1
  220. package/dist/src/runtime9.js +1 -1
  221. package/dist/src/screen-recording-admission-ledger.js +1 -1
  222. package/dist/src/screen-recording-completion.js +1 -1
  223. package/dist/src/screen-recording-options.js +1 -1
  224. package/dist/src/screen-recording-resource-recovery.js +1 -1
  225. package/dist/src/screenshot-density.js +1 -1
  226. package/dist/src/screenshot-image.js +1 -1
  227. package/dist/src/screenshot-overlay-draw.js +1 -1
  228. package/dist/src/screenshot-runtime.js +1 -1
  229. package/dist/src/screenshot.js +1 -1
  230. package/dist/src/screenshot3.js +1 -1
  231. package/dist/src/script.js +1 -1
  232. package/dist/src/scroll-command.d.ts +13 -6
  233. package/dist/src/scroll-command.js +1 -1
  234. package/dist/src/scroll-gesture.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 +59 -12
  238. package/dist/src/sdk-contracts.js +2 -2
  239. package/dist/src/sdk-device.js +1 -1
  240. package/dist/src/sdk-finders.d.ts +1 -1
  241. package/dist/src/sdk-io.js +1 -1
  242. package/dist/src/sdk-remote-config.js +1 -1
  243. package/dist/src/sdk-selectors.d.ts +1 -1
  244. package/dist/src/selection.js +0 -0
  245. package/dist/src/selector-runtime.js +1 -1
  246. package/dist/src/server.js +1 -1
  247. package/dist/src/session-allocation.js +1 -1
  248. package/dist/src/session-routing.js +1 -1
  249. package/dist/src/session-runtime-admission.js +1 -1
  250. package/dist/src/session-snapshot.js +1 -1
  251. package/dist/src/session-store.js +1 -1
  252. package/dist/src/session.js +1 -1
  253. package/dist/src/session2.js +4 -4
  254. package/dist/src/settings.js +1 -1
  255. package/dist/src/settings2.js +1 -0
  256. package/dist/src/simctl.js +1 -1
  257. package/dist/src/simulator-state.js +1 -1
  258. package/dist/src/simulator.js +1 -1
  259. package/dist/src/snapshot-capture-annotations.js +1 -1
  260. package/dist/src/snapshot-desktop-projection.js +1 -1
  261. package/dist/src/snapshot-runtime-binding.js +1 -1
  262. package/dist/src/snapshot-runtime.js +1 -1
  263. package/dist/src/snapshot-state.js +1 -1
  264. package/dist/src/snapshot2.js +1 -1
  265. package/dist/src/snapshot3.js +1 -1
  266. package/dist/src/snapshot4.js +1 -1
  267. package/dist/src/src.js +1 -1
  268. package/dist/src/src4.js +1 -1
  269. package/dist/src/src7.js +1 -1
  270. package/dist/src/src8.js +1 -1
  271. package/dist/src/string-enum.js +1 -1
  272. package/dist/src/surface-snapshot.js +1 -1
  273. package/dist/src/takeover.js +1 -1
  274. package/dist/src/text-entry-focus.js +1 -1
  275. package/dist/src/tool-provider-facade.js +1 -1
  276. package/dist/src/tool-provider.js +2 -2
  277. package/dist/src/tool-provider2.js +1 -1
  278. package/dist/src/touch-runtime.js +1 -1
  279. package/dist/src/transport.js +1 -1
  280. package/dist/src/tree.js +1 -1
  281. package/dist/src/tv-remote.js +1 -1
  282. package/dist/src/type-text-runtime.js +1 -1
  283. package/dist/src/verified-file.js +1 -1
  284. package/dist/src/video.js +1 -1
  285. package/dist/src/viewport.js +1 -1
  286. package/dist/src/web.js +1 -1
  287. package/dist/src/web2.js +1 -1
  288. package/dist/src/webdriver-source.js +1 -1
  289. package/package.json +1 -1
  290. package/server.json +2 -2
  291. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.13.apk.sha256 +0 -1
  292. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.13.apk +0 -0
  293. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.13.apk.sha256 +0 -1
  294. package/dist/src/absence-observation-errors.js +0 -1
  295. package/dist/src/runner-presentation.js +0 -1
  296. package/dist/src/semantic-index.js +0 -1
  297. package/dist/src/snapshot-process.js +0 -1
  298. package/dist/src/snapshot-scope.js +0 -1
@@ -1 +1 @@
1
- import{Dr as e,Er as t,Gr as n,Mr as r,Or as i}from"./sdk-batch.js";import{t as a}from"./scroll-indicator.js";function o(e){if(e.length===0)return{nodes:e,hiddenCount:0,summaryLines:[]};let{visibility:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}=c(e),a=n.size===0?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>m(e,i.directionsByContainer)),hiddenCount:n.size===0?0:e.length-a.length,summaryLines:h(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&v(e)),t)}}function s(e){if(e.length===0)return new Map;let{hintedContainers:t}=c(e);return p(t.directionsByContainer)}function c(e){let n=t(e),r=n.nodeByIndex,i=new Set,a=[];for(let t of e){if(n.isVisibleInEffectiveViewport(t)){b(t,i,r);continue}a.push(t)}return{visibility:n,visibleNodeIndexes:i,offscreenNodes:a,hintedContainers:f(e,a,i,r)}}function l(e,t){return e.hittable&&i(e.rect,t)}function u(e,t){if(!e.rect)return null;let r=t.resolveEffectiveViewport(e);if(r&&!n(e.rect,r)){let t=d(e.rect,r);if(t)return t}let a=t.resolveViewport(e.rect);if(a&&!i(e.rect,a)){let t=d(e.rect,a);if(t)return t}return null}function d(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=[{direction:`down`,amount:r-(t.y+t.height)},{direction:`up`,amount:t.y-r},{direction:`right`,amount:n-(t.x+t.width)},{direction:`left`,amount:t.x-n}],a=null;for(let e of i)e.amount>0&&(!a||e.amount>a.amount)&&(a=e);return a?.direction??null}function f(e,t,n,r){let i=new Map,a=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=x(e,n,r);if(!t?.rect)continue;let s=_(e.rect,t.rect);if(!s)continue;let c=i.get(t.index)??new Set;c.add(s),i.set(t.index,c);let l=a.get(t.index)??new Set;l.add(s),a.set(t.index,l),o.add(e.index)}return S(e,n,r,i,a),{directionsByContainer:i,coveredNodeIndexes:o}}function p(e){let t=new Map;for(let[n,r]of e){let e={};r.has(`above`)&&(e.hiddenContentAbove=!0),r.has(`below`)&&(e.hiddenContentBelow=!0),(e.hiddenContentAbove||e.hiddenContentBelow)&&t.set(n,e)}return t}function m(e,t){let n=t.get(e.index);if(!n||n.size===0)return e;let r=e.hiddenContentAbove===!0||n.has(`above`)?!0:void 0,i=e.hiddenContentBelow===!0||n.has(`below`)?!0:void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}}function h(e,t){let n=new Map;for(let r of e){let e=g(r,t);if(!e)continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return[`above`,`below`].flatMap(e=>{let t=n.get(e);if(!t||t.length===0)return[];let r=y(t).slice(0,3).map(e=>`"${e}"`),i=t.length===1?`interactive item`:`interactive items`,a=r.length>0?`: ${r.join(`, `)}`:``;return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}function g(e,t){if(!e.rect)return null;let n=t.resolveEffectiveViewport(e);return n?_(e.rect,n):null}function _(e,t){return e.y+e.height<=t.y?`above`:e.y>=t.y+t.height?`below`:null}function v(e){if(e.hittable===!0)return!0;let t=(e.type??``).toLowerCase();return t.includes(`button`)||t.includes(`link`)||t.includes(`textfield`)||t.includes(`edittext`)||t.includes(`searchfield`)||t.includes(`checkbox`)||t.includes(`radio`)||t.includes(`switch`)||t.includes(`menuitem`)||!!r(e)}function y(e){let t=new Set,n=[];for(let i of e){let e=r(i);!e||t.has(e)||(t.add(e),n.push(e))}return n}function b(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}function x(t,n,r){return e(t,r,e=>n.has(e.index))}function S(e,t,n,r,i){for(let a of e){let e=C(a);if(!e||e.size===0)continue;let o=x(a,t,n);if(!o)continue;let s=r.get(o.index)??new Set,c=i.get(o.index);for(let t of e)c&&c.size>0&&!c.has(t)||s.add(t);r.set(o.index,s)}}function C(e){let t=a(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add(`above`),t.below&&n.add(`below`),n.size>0?n:null}export{l as i,u as n,s as r,o as t};
1
+ import{Dr as e,Er as t,Mr as n,Or as r,Yr as i}from"./sdk-batch.js";import{t as a}from"./scroll-indicator.js";function o(e){if(e.length===0)return{nodes:e,hiddenCount:0,summaryLines:[]};let{visibility:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}=c(e),a=n.size===0?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>m(e,i.directionsByContainer)),hiddenCount:n.size===0?0:e.length-a.length,summaryLines:h(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&v(e)),t)}}function s(e){if(e.length===0)return new Map;let{hintedContainers:t}=c(e);return p(t.directionsByContainer)}function c(e){let n=t(e),r=n.nodeByIndex,i=new Set,a=[];for(let t of e){if(n.isVisibleInEffectiveViewport(t)){b(t,i,r);continue}a.push(t)}return{visibility:n,visibleNodeIndexes:i,offscreenNodes:a,hintedContainers:f(e,a,i,r)}}function l(e,t){return e.hittable&&r(e.rect,t)}function u(e,t){if(!e.rect)return null;let n=t.resolveEffectiveViewport(e);if(n&&!i(e.rect,n)){let t=d(e.rect,n);if(t)return t}let a=t.resolveViewport(e.rect);if(a&&!r(e.rect,a)){let t=d(e.rect,a);if(t)return t}return null}function d(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=[{direction:`down`,amount:r-(t.y+t.height)},{direction:`up`,amount:t.y-r},{direction:`right`,amount:n-(t.x+t.width)},{direction:`left`,amount:t.x-n}],a=null;for(let e of i)e.amount>0&&(!a||e.amount>a.amount)&&(a=e);return a?.direction??null}function f(e,t,n,r){let i=new Map,a=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=x(e,n,r);if(!t?.rect)continue;let s=_(e.rect,t.rect);if(!s)continue;let c=i.get(t.index)??new Set;c.add(s),i.set(t.index,c);let l=a.get(t.index)??new Set;l.add(s),a.set(t.index,l),o.add(e.index)}return S(e,n,r,i,a),{directionsByContainer:i,coveredNodeIndexes:o}}function p(e){let t=new Map;for(let[n,r]of e){let e={};r.has(`above`)&&(e.hiddenContentAbove=!0),r.has(`below`)&&(e.hiddenContentBelow=!0),(e.hiddenContentAbove||e.hiddenContentBelow)&&t.set(n,e)}return t}function m(e,t){let n=t.get(e.index);if(!n||n.size===0)return e;let r=e.hiddenContentAbove===!0||n.has(`above`)?!0:void 0,i=e.hiddenContentBelow===!0||n.has(`below`)?!0:void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}}function h(e,t){let n=new Map;for(let r of e){let e=g(r,t);if(!e)continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return[`above`,`below`].flatMap(e=>{let t=n.get(e);if(!t||t.length===0)return[];let r=y(t).slice(0,3).map(e=>`"${e}"`),i=t.length===1?`interactive item`:`interactive items`,a=r.length>0?`: ${r.join(`, `)}`:``;return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}function g(e,t){if(!e.rect)return null;let n=t.resolveEffectiveViewport(e);return n?_(e.rect,n):null}function _(e,t){return e.y+e.height<=t.y?`above`:e.y>=t.y+t.height?`below`:null}function v(e){if(e.hittable===!0)return!0;let t=(e.type??``).toLowerCase();return t.includes(`button`)||t.includes(`link`)||t.includes(`textfield`)||t.includes(`edittext`)||t.includes(`searchfield`)||t.includes(`checkbox`)||t.includes(`radio`)||t.includes(`switch`)||t.includes(`menuitem`)||!!n(e)}function y(e){let t=new Set,r=[];for(let i of e){let e=n(i);!e||t.has(e)||(t.add(e),r.push(e))}return r}function b(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}function x(t,n,r){return e(t,r,e=>n.has(e.index))}function S(e,t,n,r,i){for(let a of e){let e=C(a);if(!e||e.size===0)continue;let o=x(a,t,n);if(!o)continue;let s=r.get(o.index)??new Set,c=i.get(o.index);for(let t of e)c&&c.size>0&&!c.has(t)||s.add(t);r.set(o.index,s)}}function C(e){let t=a(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add(`above`),t.below&&n.add(`below`),n.size>0?n:null}export{l as i,u as n,s as r,o as t};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{l as t,w as n}from"./sdk-device.js";import{n as r}from"./gesture-admission.js";const i={visionos:`visionOS uses spatial input and does not support two-finger touch synthesis.`,tvos:`tvOS has no touch input — this gesture is supported on Android and the iOS simulator only.`,macos:`macOS automation has no multi-touch input — this gesture is supported on Android and the iOS simulator only.`};function a(a,s){if(!t(a.platform))throw o(s,a.platform);let c=n(a);if(c!==`ios`&&c!==`ipados`||a.kind!==`simulator`)throw c===`ios`||c===`ipados`?new e(`UNSUPPORTED_OPERATION`,`gesture ${s} is not supported on physical iOS devices`,{hint:`Two-finger gesture synthesis is iOS-simulator only — not available on physical iOS devices.`}):o(s,r[c],i[c])}function o(t,n,r){return new e(`UNSUPPORTED_OPERATION`,`gesture ${t} is not supported on ${n}`,r===void 0?void 0:{hint:r})}export{a as n,i as t};
1
+ import{A as e}from"./sdk-contracts.js";import{l as t,w as n}from"./sdk-device.js";import{n as r}from"./gesture-admission.js";const i={visionos:`visionOS uses spatial input and does not support two-finger touch synthesis.`,tvos:`tvOS has no touch input — this gesture is supported on Android and the iOS simulator only.`,macos:`macOS automation has no multi-touch input — this gesture is supported on Android and the iOS simulator only.`};function a(a,s){if(!t(a.platform))throw o(s,a.platform);let c=n(a);if(c!==`ios`&&c!==`ipados`||a.kind!==`simulator`)throw c===`ios`||c===`ipados`?new e(`UNSUPPORTED_OPERATION`,`gesture ${s} is not supported on physical iOS devices`,{hint:`Two-finger gesture synthesis is iOS-simulator only — not available on physical iOS devices.`}):o(s,r[c],i[c])}function o(t,n,r){return new e(`UNSUPPORTED_OPERATION`,`gesture ${t} is not supported on ${n}`,r===void 0?void 0:{hint:r})}export{a as n,i as t};
@@ -0,0 +1 @@
1
+ import{A as e,R as t}from"./sdk-contracts.js";import{c as n,r}from"./diagnostics.js";import{f as i,x as a}from"./owner-identity.js";import{c as o,l as s,m as c,r as l}from"./exec.js";import{n as u,t as d}from"./file.js";import"./diagnostics2.js";import"./command.js";import{n as f}from"./retry.js";import{r as p}from"./version.js";import"./process.js";import{C as ee,D as m,c as h,f as g,h as _,n as v,o as y,w as b,y as te}from"./host-file.js";import{a as x}from"./tool-provider.js";import{t as S}from"./apple-runner-platform.js";import{t as C}from"./simctl.js";import w from"node:path";import{createHash as T}from"node:crypto";import E from"node:net";function D(e){let{waitMs:t,signal:n,stop:r,cancelled:i}=e;return new Promise((e,a)=>{let o=()=>l(()=>a(i())),s=()=>l(e),c=setTimeout(()=>l(e),t);function l(e){clearTimeout(c),n?.removeEventListener(`abort`,o),r?.removeEventListener(`abort`,s),e()}n?.addEventListener(`abort`,o,{once:!0}),r?.addEventListener(`abort`,s,{once:!0}),n?.aborted?o():r?.aborted&&s()})}function O(e){let t=e.now??Date.now,n=e.waitGrant??`every-caller`,r=new Map,i=(n,i)=>{let a={status:`pending`,value:void 0,error:void 0,settledAtMs:t(),waitSpent:!1,controller:new AbortController,settled:void 0},o=()=>{};a.settled=new Promise(e=>{o=e}),r.set(n,a);let s=(i,s)=>{a.status=i,i===`ready`?a.value=s:a.error=s,a.settledAtMs=t(),(i===`ready`||e.retryAfterMs===void 0)&&r.get(n)===a&&r.delete(n),o()};try{i(a.controller.signal).then(e=>s(`ready`,e),e=>s(`failed`,e))}catch(e){s(`failed`,e)}return a},a=(n,a)=>{let o=r.get(n);if(!o)return i(n,a);if(o.status!==`failed`)return o;let s=t()-o.settledAtMs;return e.retryAfterMs===void 0||s>=e.retryAfterMs?i(n,a):o};return{value:async(t,r)=>{let i=a(t,r.start);if(i.status===`pending`&&(n===`every-caller`||!i.waitSpent)){i.waitSpent=!0;let t=new AbortController,n=r.wait(e.waitMs,t.signal);n.catch(()=>{});try{await Promise.race([i.settled,n])}finally{t.abort()}}if(i.status===`ready`)return i.value;throw i.status===`failed`?i.error:r.pending()},close:()=>{let e=[...r.values()];r.clear();for(let t of e)t.controller.abort()}}}async function k(e,t){let n=await x(`ps`,[`-p`,String(e),`-o`,`lstart=`],{allowFailure:!0,signal:t.signal,timeoutMs:t.timeoutMs});return n.exitCode===0&&n.stdout.trim()||null}const A={unsupported:`UNSUPPORTED_OPERATION`,"malformed-tree":`COMMAND_FAILED`,"stale-target":`COMMAND_FAILED`,timeout:`COMMAND_FAILED`,cancelled:`COMMAND_FAILED`,"process-crash":`COMMAND_FAILED`,"transport-failure":`COMMAND_FAILED`,preparing:`COMMAND_FAILED`};var j=class extends e{failureKind;failureCode;constructor(e,t,n=`iOS Simulator snapshot source ${e}: ${t}`,r={},i){super(A[e],n,{...r,bridgeFailure:e,bridgeFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`SnapshotSourceError`,this.failureKind=e,this.failureCode=t}};function M(e,t,n={},r){return new j(e,t,void 0,n,r)}function N(n){return n instanceof j?n:t(n)?M(`cancelled`,`abort-signal`,{},n):n instanceof e&&typeof n.details?.timeoutMs==`number`?M(`timeout`,`host-operation-timeout`,{timeoutMs:n.details.timeoutMs},n):M(`transport-failure`,`unexpected-host-error`,{error:n instanceof Error?n.message:String(n)},n)}function P(e,t,n=Date.now){if(t?.aborted)throw M(`cancelled`,`abort-signal`);return{clock:f.fromTimeoutMs(e,n()),now:n,signal:t}}function F(e,t){if(e.signal?.aborted)throw M(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw M(`timeout`,t);return Math.max(1,Math.floor(n))}async function I(e,t,n,r){await D({waitMs:Math.min(t,F(e,n)),signal:e.signal,stop:r,cancelled:()=>M(`cancelled`,`abort-signal`)})}const L=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeRuntime.h`,`SnapshotBridgeCapture.h`,`SnapshotBridgeCapture.m`],R=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeCapture.m`];async function z(e,t){let n=await V(e,`xcodebuild`,[`-version`],t),r=await V(e,`sw_vers`,[`-productVersion`],t),i=await V(e,`sw_vers`,[`-buildVersion`],t),a=await V(e,`uname`,[`-m`],t);if(a!==`arm64`&&a!==`x86_64`)throw M(`unsupported`,`simulator-architecture-unsupported`,{architecture:a});return{xcode:n,macosProductVersion:r,macosBuild:i,architecture:a}}async function B(e,t,n){let r=await z(e,n),i=t.trim();if(!i)throw M(`unsupported`,`simulator-runtime-missing`);return{...r,simulatorRuntime:i}}async function V(e,t,n,r){let i=await H(e,t,n,r);if(i.exitCode!==0)throw M(`unsupported`,`toolchain-probe-failed`,{command:t,exitCode:i.exitCode,stderr:i.stderr.slice(0,1024)});let a=(i.stdout||i.stderr).trim();if(!a)throw M(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function H(e,t,n,r){let i=[],a;for(let o=1;;o+=1){let s;try{s=Math.min(S,F(r,`toolchain-probe-deadline`))}catch(e){throw a??e}i.push(s);try{return await W(e,t,n,r,s)}catch(e){if(!l(e))throw e;if(r.signal?.aborted)throw M(`cancelled`,`abort-signal`);if(a=U(t,i,e),o>=2)throw a}}}function U(e,t,n){let r=t.length;return M(`timeout`,`toolchain-probe-stalled`,{command:e,attemptTimeoutsMs:[...t],hint:`${e} did not answer within ${t[r-1]}ms on ${r} attempt(s). A toolchain probe that cannot answer is a host condition rather than a toolchain defect: run \`${e}\` by hand until it answers, then retry.`},n)}function W(e,t,n,r,i){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:i})}const G=65536;function K(){return{projectRoot:p,homeDirectory:g,run:async(e,t,n)=>await o(e,t,n),start:q,connect:J,readText:te,readBinary:_,writeText:m,ensureDirectory:y,chmod:v,exists:h,rename:b,remove:ee,acquireLock:Y,emitDiagnostic:r,withDiagnosticTimer:n,processId:i,readTargetProcessStartTime:k}}function q(e,t,n,r={}){if(r.signal?.aborted)throw M(`cancelled`,`abort-signal`);let i=s(`xcrun`,C(e,[`spawn`,e.udid,t,`serve`,n,`--idle-timeout`,`60`,`--exit-on-disconnect`,`false`]),{allowFailure:!0,captureOutput:!1,detached:!0}),a=i.child.pid??0;if(a<=0)throw M(`transport-failure`,`bridge-process-pid-missing`);let o=``;return i.child.stderr?.setEncoding(`utf8`),i.child.stderr?.on(`data`,e=>{o=X(o,String(e))}),{pid:a,wait:i.wait,isAlive:()=>i.child.exitCode===null&&i.child.signalCode===null,signal:e=>{c(a,e)||i.child.kill(e)},readLog:()=>o}}async function J(e,t){if(t.signal?.aborted)throw M(`cancelled`,`abort-signal`);let n=Math.max(1,Math.floor(t.timeoutMs));return await new Promise((r,i)=>{let a=E.createConnection({path:e}),o=!1,s=!1,c=setTimeout(()=>{p(M(`timeout`,`bridge-connect-timeout`)),a.destroy()},n),l=()=>{p(M(`cancelled`,`abort-signal`)),a.destroy()},u=()=>{o=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`error`,d),a.off(`close`,f),a.setTimeout(0),r(a)},d=e=>{p(e),a.destroy()},f=()=>{o||p(M(`transport-failure`,`bridge-closed-before-connect`))},p=e=>{s||o||(s=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`connect`,u),a.off(`error`,d),a.off(`close`,f),i(e))};a.once(`connect`,u),a.once(`error`,d),a.once(`close`,f),t.signal?.addEventListener(`abort`,l,{once:!0}),t.signal?.aborted&&l()})}async function Y(e,t){let n=i(),r=t.deadline,o=d({lockDirPath:e,owner:{pid:n,startTime:a(n),acquiredAtMs:Date.now()},timeoutMs:F(r,`cache-lock-deadline`),pollMs:100,ownerGraceMs:5e3,description:t.description}),s=r.signal;if(!s)return await o;let c=!1,l,u=new Promise((e,t)=>{l=()=>{c=!0,t(M(`cancelled`,`abort-signal`))},s.addEventListener(`abort`,l,{once:!0}),s.aborted&&l()});try{return await Promise.race([o,u])}catch(e){throw c&&o.then(e=>e().catch(()=>void 0),()=>void 0),r.clock.isExpired()&&!(e instanceof j&&e.failureKind===`cancelled`)?M(`timeout`,`cache-lock-deadline`):e}finally{s.removeEventListener(`abort`,l)}}function X(e,t){let n=e+t;return n.length<=G?n:n.slice(n.length-G)}function Z(e,t,n){let r=T(`sha256`).update(t).digest(`hex`).slice(0,12),i=T(`sha256`).update(n).digest(`hex`).slice(0,12);return w.join(`/tmp`,`agent-device-ax-${r}-${e.processId()}-${i}`,`snapshot.sock`)}const Q=`manifest.json`;async function ne(e){let{host:t,deadline:n,cacheRoot:r,binaryFilename:i}=e,a=T(`sha256`).update(JSON.stringify(e.keyInputs)).digest(`hex`).slice(0,32),o=w.join(r,a);return await u({acquire:()=>t.acquireLock(w.join(r,`${a}.lock`),{deadline:n,description:e.lockDescription}),task:async()=>{let s=await re(t,o,i,a,n);if(s)return{path:s,cacheKey:a};F(n,`native-build-deadline`),t.exists(o)&&await t.remove(o),F(n,`native-build-deadline`),await t.ensureDirectory(r);let c=w.join(r,`.${a}.${t.processId()}.tmp`);F(n,`native-build-deadline`),await t.remove(c);try{F(n,`native-build-deadline`),await t.ensureDirectory(c);let r=w.join(c,i);await e.build(r),F(n,`native-build-deadline`),await t.chmod(r,493);let s=await $(t,r),l={...e.keyInputs,cacheKey:a,binarySha256:s};return await t.writeText(w.join(c,Q),`${JSON.stringify(l,null,2)}\n`),F(n,`native-build-deadline`),await t.rename(c,o),{path:w.join(o,i),cacheKey:a}}catch(e){throw await t.remove(c),e}}})}async function re(e,t,n,r,i){let a=w.join(t,n),o=w.join(t,Q);if(!(!e.exists(a)||!e.exists(o)))try{let t=JSON.parse(await e.readText(o));return t.cacheKey!==r||typeof t.binarySha256!=`string`?void 0:(F(i,`native-cache-hash-deadline`),await $(e,a)===t.binarySha256?a:void 0)}catch(e){if(ie(e))throw e;return}}function ie(e){return e instanceof j&&(e.failureKind===`cancelled`||e.failureKind===`timeout`)}async function $(e,t){return T(`sha256`).update(await e.readBinary(t)).digest(`hex`)}async function ae(e,t,n,r){let i=T(`sha256`);for(let a of n){let n=w.join(t,a);if(F(r,`native-source-fingerprint-deadline`),!e.exists(n))throw M(`unsupported`,`native-source-missing`,{filePath:n});i.update(a),i.update(`\0`),i.update(await e.readBinary(n)),i.update(`\0`)}return i.digest(`hex`)}async function oe(e){let t=Math.min(e.budgetMs,F(e.deadline,`native-build-deadline`));try{return await e.host.run(`xcrun`,[...e.argv],{signal:e.deadline.signal,timeoutMs:t,allowFailure:!0})}catch(n){throw l(n)?M(`timeout`,`native-build-stalled`,{timeoutMs:t,hint:`The Simulator SDK toolchain did not answer within ${t}ms, which stopped the ${e.label} build before clang reported anything. Run \`xcrun --sdk iphonesimulator clang --version\` by hand until it answers, then retry.`},n):n}}export{O as _,Z as a,z as c,F as d,I as f,k as g,M as h,K as i,B as l,N as m,oe as n,R as o,j as p,ae as r,L as s,ne as t,P as u,D as v};
@@ -1,2 +1,2 @@
1
- import{D as e}from"./sdk-contracts.js";import{n as t}from"./device-shell.js";const n=`mCurrentFocus=Window{`,r=[n,`mFocusedApp=AppWindowToken{`,`mResumedActivity:`,`ResumedActivity:`],i=[[`dumpsys`,`window`,`windows`],[`dumpsys`,`window`]],a=[[`dumpsys`,`activity`,`activities`],[`dumpsys`,`activity`]],o=RegExp(`(?:${r.map(S).join(`|`)})(.*)$`,`gm`),s=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,c=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/,l=new Set([`com.android.permissioncontroller`,`com.google.android.permissioncontroller`,`com.android.packageinstaller`,`com.google.android.packageinstaller`]),u=new Map;function d(n){return Object.freeze({readAppState:async e=>await p(n,e),readBlockingDialog:async e=>await m(n,e),async readAppFocus(e,t,r={}){let i=f(n,e);return r.requireNoBlockingDialog&&(await m(n,e,i)).status===`dialog`?!1:(await p(n,e,i)).package===t},readSnapshotNodes:async e=>await n.readSnapshotNodes(e),async tap(e,r,i){return await n.runAdb(e,t(`adb`,`shell`,[`input`,`tap`,String(Math.round(r)),String(Math.round(i))]),{allowFailure:!0})},openApp:async(e,t)=>await n.openApp(e,t),async readScreenSize(r){let i=(await n.runAdb(r,t(`adb`,`shell`,[`wm`,`size`]))).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!i)throw new e(`COMMAND_FAILED`,`Unable to read screen size`);return{width:Number(i[1]),height:Number(i[2])}},async isPermissionPackage(e){return l.has(e)}})}function f(e,n){let r=new Map;return i=>{let a=i.join(` `),o=r.get(a)??e.runAdb(n,t(`adb`,`shell`,i),{allowFailure:!0}).then(e=>(g(n,a,e.stdout),e.stdout));return r.set(a,o),o}}async function p(e,t,n=f(e,t)){for(let e of h(t,`foreground`)){let t=v(await n(e));if(t)return t}return{}}async function m(e,t,n=f(e,t)){for(let e of h(t,`blockingDialog`)){let t=y(await n(e));if(t.focus)return{status:`dialog`,focus:t.focus};if(t.focusObserved)return{status:`clear`}}return{status:`unknown`}}function h(e,t){let n=t===`foreground`?[i,a]:[i],r=u.get(e.id);return n.flatMap(e=>{if(!r)return e;let n=e=>r.get(`${t} ${e.join(` `)}`)===!1,i=e.filter(e=>!n(e));return i.length===0||i.length===e.length?e:[...i,...e.filter(n)]})}function g(e,t,i){if(!i)return;let a=u.get(e.id)??new Map;_(a,`foreground ${t}`,x(r).test(i)),_(a,`blockingDialog ${t}`,x([n]).test(i)),u.set(e.id,a)}function _(e,t,n){e.get(t)!==!0&&e.set(t,n)}function v(e){for(let t of e.matchAll(o)){let e=t[1]?.match(/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/);if(e?.[1]&&e[2])return{package:e[1],activity:e[2]}}return null}function y(e){let t=!1,i=e.split(`
1
+ import{A as e}from"./sdk-contracts.js";import{n as t}from"./device-shell.js";const n=`mCurrentFocus=Window{`,r=[n,`mFocusedApp=AppWindowToken{`,`mResumedActivity:`,`ResumedActivity:`],i=[[`dumpsys`,`window`,`windows`],[`dumpsys`,`window`]],a=[[`dumpsys`,`activity`,`activities`],[`dumpsys`,`activity`]],o=RegExp(`(?:${r.map(S).join(`|`)})(.*)$`,`gm`),s=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,c=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/,l=new Set([`com.android.permissioncontroller`,`com.google.android.permissioncontroller`,`com.android.packageinstaller`,`com.google.android.packageinstaller`]),u=new Map;function d(n){return Object.freeze({readAppState:async e=>await p(n,e),readBlockingDialog:async e=>await m(n,e),async readAppFocus(e,t,r={}){let i=f(n,e);return r.requireNoBlockingDialog&&(await m(n,e,i)).status===`dialog`?!1:(await p(n,e,i)).package===t},readSnapshotNodes:async e=>await n.readSnapshotNodes(e),async tap(e,r,i){return await n.runAdb(e,t(`adb`,`shell`,[`input`,`tap`,String(Math.round(r)),String(Math.round(i))]),{allowFailure:!0})},openApp:async(e,t)=>await n.openApp(e,t),async readScreenSize(r){let i=(await n.runAdb(r,t(`adb`,`shell`,[`wm`,`size`]))).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!i)throw new e(`COMMAND_FAILED`,`Unable to read screen size`);return{width:Number(i[1]),height:Number(i[2])}},async isPermissionPackage(e){return l.has(e)}})}function f(e,n){let r=new Map;return i=>{let a=i.join(` `),o=r.get(a)??e.runAdb(n,t(`adb`,`shell`,i),{allowFailure:!0}).then(e=>(g(n,a,e.stdout),e.stdout));return r.set(a,o),o}}async function p(e,t,n=f(e,t)){for(let e of h(t,`foreground`)){let t=v(await n(e));if(t)return t}return{}}async function m(e,t,n=f(e,t)){for(let e of h(t,`blockingDialog`)){let t=y(await n(e));if(t.focus)return{status:`dialog`,focus:t.focus};if(t.focusObserved)return{status:`clear`}}return{status:`unknown`}}function h(e,t){let n=t===`foreground`?[i,a]:[i],r=u.get(e.id);return n.flatMap(e=>{if(!r)return e;let n=e=>r.get(`${t} ${e.join(` `)}`)===!1,i=e.filter(e=>!n(e));return i.length===0||i.length===e.length?e:[...i,...e.filter(n)]})}function g(e,t,i){if(!i)return;let a=u.get(e.id)??new Map;_(a,`foreground ${t}`,x(r).test(i)),_(a,`blockingDialog ${t}`,x([n]).test(i)),u.set(e.id,a)}function _(e,t,n){e.get(t)!==!0&&e.set(t,n)}function v(e){for(let t of e.matchAll(o)){let e=t[1]?.match(/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/);if(e?.[1]&&e[2])return{package:e[1],activity:e[2]}}return null}function y(e){let t=!1,i=e.split(`
2
2
  `);for(let e of r)for(let r of i){let i=r.indexOf(e);if(i===-1)continue;e===n&&(t=!0);let a=r.trim(),o=b(r.slice(i+e.length).split(`}`)[0]?.trim()??``,a);if(o)return{focusObserved:t,focus:o}}return{focusObserved:t,focus:null}}function b(e,t){let n=s.exec(e)?.[1];if(n)return{package:n,focusedWindow:`Application Not Responding: ${n}`,raw:t};let r=e.toLowerCase();if(!r.includes(`isn't responding`)&&!r.includes(`is not responding`))return null;let i=e.trim().replaceAll(/\s+/g,` `),a=c.exec(i)?.[1];return{...a?{package:a}:{},focusedWindow:i,raw:t}}function x(e){return new RegExp(e.map(S).join(`|`))}function S(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}export{d as createAndroidObservationAdapter};
@@ -0,0 +1,3 @@
1
+ import{A as e,_ as t,j as n}from"./sdk-contracts.js";import{Ir as r,Mr as i,Zr as a,qn as o,rr as s}from"./sdk-batch.js";import{n as c}from"./scroll-indicator.js";import{a as l,n as u,o as d,t as f}from"./react-native-overlay.js";function p(e){let t=_(e.label),n=_(e.value),r=_(e.identifier),i=y(r)?r:``;return v(e.type??``)?n||t||i:t||n||i}function m(e,t){if(t===`text-view`||t===`text-field`||t===`search`)return!0;let n=r(e.type??``),i=`${e.role??``} ${e.subrole??``}`.toLowerCase();return n.includes(`textview`)||n.includes(`textarea`)||n.includes(`textfield`)||n.includes(`securetextfield`)||n.includes(`searchfield`)||n.includes(`edittext`)||i.includes(`text area`)||i.includes(`text field`)}function h(e){let t=e.replaceAll(/\s+/g,` `).trim();return t.length<=48?t:`${t.slice(0,45)}...`}function ee(e,t){let n=p(e),r=m(e,t);return{text:n,isLargeSurface:r,shouldSummarize:r&&g(n)}}function g(e){return e?e.length>80||/[\r\n]/.test(e):!1}function _(e){return typeof e==`string`?e.trim():``}function v(e){let t=r(e);return t.includes(`textfield`)||t.includes(`securetextfield`)||t.includes(`searchfield`)||t.includes(`edittext`)||t.includes(`textview`)||t.includes(`textarea`)}function y(e){return e?!/^[\w.]+:id\/[\w.-]+$/i.test(e)&&!/^_?NS:\d+$/i.test(e):!1}const b={application:`application`,navigationbar:`navigation-bar`,tabbar:`tab-bar`,button:`button`,imagebutton:`button`,link:`link`,cell:`cell`,statictext:`text`,checkedtextview:`text`,textbox:`text-field`,textfield:`text-field`,edittext:`text-field`,textarea:`text-view`,switch:`switch`,slider:`slider`,image:`image`,imageview:`image`,webview:`webview`,framelayout:`group`,linearlayout:`group`,relativelayout:`group`,constraintlayout:`group`,viewgroup:`group`,view:`group`,listview:`list`,recyclerview:`list`,collectionview:`collection`,searchfield:`search`,heading:`heading`,activityindicator:`activity-indicator`,progressindicator:`progress-indicator`,segmentedcontrol:`segmented-control`,group:`group`,window:`window`,checkbox:`checkbox`,radio:`radio`,menuitem:`menu-item`,toolbar:`toolbar`,scrollarea:`scroll-area`,scrollview:`scroll-area`,nestedscrollview:`scroll-area`,table:`table`};function te(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,a=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||``,o=T(i.type??`Element`),s=i.inheritsLabel===!0||i.inheritsIdentifier===!0;if(o===`group`&&!a&&!s)continue;for(;n.length>0&&e<=n.at(-1);)n.pop();let c=n.length;n.push(e),r.push({node:i,depth:c,type:o,text:x(i,c,!1,o,t)})}return r}function x(e,t,n,r,i={}){let a=r??T(e.type??`Element`),o=ee(e,a),s=ie(e,a,i,o),c=` `.repeat(t),l=e.ref?`@${e.ref}`:``,u=ae(e,a,i,o);!s&&(e.inheritsLabel===!0||e.inheritsIdentifier===!0)&&u.push(`same label as parent`);let d=u.map(e=>` [${e}]`).join(``),f=s?` "${s}"`:``,p=S(e);return n?`${c}${l} [${a}]${d}${p}`.trimEnd():`${c}${l} [${a}]${f}${d}${p}`.trimEnd()}function S(e){let t=e.actions?.filter(e=>e.trim().length>0);return!t||t.length===0?``:` actions: [${t.map(e=>`"${k(C(e))}"`).join(`, `)}]`}function C(e){return e.replaceAll(/\s+/g,` `).replaceAll(/[\u0000-\u001f\u007f-\u009f]/g,``).trim()}function w(e,t){let n=e.label?.trim();if(n&&re(t,n))return``;let r=e.value?.trim();if(D(t)){if(r)return r;if(n)return n}else if(n)return n;if(r)return r;let i=e.identifier?.trim();return!i||O(i)&&(t===`group`||t===`image`||t===`list`||t===`collection`)?``:i}function T(e){let t=e,n=e.replaceAll(/XCUIElementType/gi,``).toLowerCase(),r=t.includes(`.`)&&(t.startsWith(`android.`)||t.startsWith(`androidx.`)||t.startsWith(`com.`));return n.includes(`.`)&&(n=n.replace(/^android\.widget\./,``).replace(/^android\.view\./,``).replace(/^android\.webkit\./,``).replace(/^androidx\./,``).replace(/^com\.google\.android\./,``).replace(/^com\.android\./,``),r&&n.includes(`.`)&&(n=n.slice(n.lastIndexOf(`.`)+1))),n===`textview`?r?`text`:`text-view`:ne(n)||n||`element`}function E(e){let t=[];return e.enabled===!1&&t.push(`disabled`),e.selected===!0&&t.push(`selected`),e.checked!==void 0&&t.push(e.checked?`checked`:`unchecked`),t}function ne(e){return Object.prototype.hasOwnProperty.call(b,e)?b[e]:void 0}function D(e){return e===`text-field`||e===`text-view`||e===`search`}function re(e,t){return e!==`scroll-area`&&e!==`list`&&e!==`collection`&&e!==`table`?!1:c(t)}function O(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function ie(e,t,n,r){return!n.summarizeTextSurfaces||!r.shouldSummarize?w(e,t):oe(e,t,r.text)||w(e,t)}function ae(e,t,n,r){let i=[...E(e),...e.presentationHints??[]];return!n.summarizeTextSurfaces||(e.focused===!0&&i.push(`focused`),D(t)&&i.push(`editable`),se(e,t)&&i.push(`scrollable`),!r.shouldSummarize)?A(i):(i.push(`preview:"${k(h(r.text))}"`),i.push(`truncated`),A(i))}function oe(e,t,n){let r=_(e.label);if(r&&r!==n)return r;let i=_(e.identifier);if(i&&!O(i)&&i!==n)return i;switch(t){case`text`:case`text-view`:return`Text view`;case`text-field`:return`Text field`;case`search`:return`Search field`;default:return``}}function se(e,t){if(t===`scroll-area`)return!0;let n=(e.type??``).toLowerCase(),r=`${e.role??``} ${e.subrole??``}`.toLowerCase();return n.includes(`scroll`)||r.includes(`scroll`)}function k(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}function A(e){return[...new Set(e)]}const j={state:`sparse`,backend:`tree`,reason:`legacy iOS capture exposed only the application root`,reasonCode:`sparse-tree`},M={sparse:`capture was sparse`,truncated:`capture was truncated`,unsettled:`the surface was still changing after a gesture`};function N(e){return typeof e==`string`&&Object.hasOwn(M,e)}function P(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function F(e,t=`is`){let n=`${t} absent`;return e===`scope`?`${n} does not support --scope; it requires an unscoped capture`:`${n} does not support --depth; it requires a full-depth capture`}function I(e,t){let n=t[0]?z(t[0]):void 0,r=t.length;if(e.truncated===!0)return{kind:`truncated`,matches:r,...n?{firstMatch:n}:{}};let i=L(e);return i?{kind:`sparse`,matches:r,...n?{firstMatch:n}:{},quality:{state:i.state,backend:i.backend,...i.reason?{reason:i.reason}:{},...i.reasonCode?{reasonCode:i.reasonCode}:{}}}:r===0?{kind:e.postGestureOutcome?.kind===`unsettled`?`unsettled`:`absent`,matches:0}:{kind:`present`,matches:r,firstMatch:n}}function L(e){let t=e.snapshotQuality;return t?.state===`sparse`?{state:t.state,backend:t.backend,...t.reason?{reason:t.reason}:{},...t.reasonCode?{reasonCode:t.reasonCode}:{}}:R(e)?j:void 0}function R(e){return e.snapshotQuality||e.backend!==`xctest`||e.nodes.length!==1?!1:r(e.nodes[0]?.type??``)===`application`}function z(e){let t=o(e),n=s(i(e),256);return{...t,...n&&n!==t.label?{text:n}:{}}}const B={selectorNotFound:`selector_not_found`,predicateFailed:`predicate_failed`,refNotFound:`ref_not_found`,refUnlabeled:`ref_unlabeled`,targetBoundsInvalid:`target_bounds_invalid`};function V(t,n=`is`){return new e(`INVALID_ARGS`,F(t,n),{command:n,predicate:`absent`,rejectedOption:t})}function H(t,n,r=`is`){let i=`firstMatch`in n?n.firstMatch:void 0,a={command:r,reason:B.predicateFailed,predicate:`absent`,selector:t,matches:n.matches,observation:n.kind,...i?{firstMatch:i}:{},...n.kind===`sparse`?{snapshotQuality:n.quality}:{},...n.kind===`truncated`?{truncated:!0}:{}};if(n.kind===`present`){let i=n.matches>1;return new e(`COMMAND_FAILED`,`${r} absent failed for selector ${t}: ${n.matches} match${i?`es`:``} found`,{...a,...i?{hint:`Refine the selector to match no elements.`}:{}})}return new e(`COMMAND_FAILED`,`${r} absent could not prove absence for selector ${t}: ${M[n.kind]}`,{...a,hint:`Retry after the accessibility capture is complete.`})}function U(t,r,i=`is`){let a=n(r),o=typeof a.details?.reason==`string`?a.details.reason:typeof a.details?.androidSnapshotHelperFailureReason==`string`?a.details.androidSnapshotHelperFailureReason:void 0;return new e(`COMMAND_FAILED`,`${i} absent could not prove absence for selector ${t}: capture was unreadable`,{command:i,reason:B.predicateFailed,predicate:`absent`,selector:t,matches:0,observation:`unreadable`,captureErrorCode:a.code,...o?{captureErrorReason:o}:{},hint:`Retry after the accessibility capture is readable.`},a)}const W=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,G=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],K=new Set([`x`,`×`,`✕`,`✖`,`⨯`]);function ce(e){if(q(e).detected)return[`Hint: React Native warning/error overlay detected. It overlays part of the app and should be handled before interacting.`,`Run: agent-device react-native dismiss-overlay`,`The command verifies the overlay is gone. Run agent-device snapshot -i afterward only when you need fresh refs for the next action.`].join(`
2
+ `)}function q(e){let t=le(e),n=t.detected?ue(t):null;return{detected:t.detected,dismissNodes:t.dismissNodes,minimizeNodes:t.minimizeNodes,collapsedNodes:t.collapsedNodes,primaryAction:n}}function le(e){let t=e.map(de).join(`
3
+ `).toLowerCase(),n=Y(e,_e),r=Y(e,d),i=Y(e,u,xe),a=Y(e,J),o=pe(t),s=me(t);return{dismissNodes:n,minimizeNodes:r,collapsedNodes:i,detected:ge({text:t,hasReactNativeStackFrame:o,hasOverlayControl:he(t,n,r),hasControllessRedBoxText:s,collapsedNodes:i,openDebuggerWarningNodes:a})}}function ue(e){let t=Ce(e.dismissNodes);if(t)return Te(t,Ee(t));let n=De(e.collapsedNodes.filter(Se));return n?.rect?{action:`close-collapsed-banner`,point:Ae(n),rect:n.rect,ref:n.ref,label:$(n)}:null}function de(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(` `)}function fe(e){return W.test(e)}function pe(e){return G.some(t=>t.test(e))}function me(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function he(e,t,n){return t.length>0||n.length>0||/\b(reload js|copy stack)\b/.test(e)}function ge(e){return e.collapsedNodes.length>0||e.openDebuggerWarningNodes.length>0||e.hasControllessRedBoxText||e.hasOverlayControl&&(fe(e.text)||e.hasReactNativeStackFrame)}function J(e){return e.includes(`open debugger to view warnings`)||/^!,\s+open debugger\b/.test(e)}function _e(e){return l(e)||ve(e)||ye(e)}function ve(e){return/^close(?:\s*\([^)]*\))?$/i.test(e)}function ye(e){return K.has(e)}function be(e){return/^!,\s+/.test(e)}function xe(e){return!e.rect||e.rect.height<=180}function Se(e){let t=$(e)?.trim().toLowerCase()??``;return(J(t)||be(t))&&f(e)}function Y(e,t,n=()=>!0){let r=[];for(let i of e)i.ref&&n(i)&&[i.label,i.value,i.identifier].map(e=>e?.trim().toLowerCase()).filter(e=>!!e).some(e=>t(e))&&r.push(i);return r}function Ce(e){return Z(e,we)}function X(e){let t=[e.type,e.role,e.subrole].join(` `).toLowerCase();return/\b(button|menuitem|link)\b/.test(t)}function we(e){return[Q(X(e)),Q(e.hittable),-(e.rect?a(e.rect):1/0)]}function Te(e,n){if(!e.rect)throw Error(`React Native overlay target node must have rect`);return{action:n,point:t(e.rect),rect:e.rect,ref:e.ref,label:$(e)}}function Ee(e){let t=$(e)?.trim().toLowerCase();return t&&l(t)?`dismiss`:`close`}function De(e){return Z(e,Oe)}function Z(e,t){let n=e.filter(e=>e.rect);return n.length===0?null:n.sort((e,n)=>ke(t(n),t(e)))[0]??null}function Oe(e){return[Q(e.hittable),e.rect?.width??0,e.rect?.y??0]}function Q(e){return+(e===!0)}function ke(e,t){for(let n=0;n<e.length;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}function Ae(e){if(!e.rect)throw Error(`Collapsed React Native warning node must have rect`);let t=Math.min(e.rect.height,52),n=Math.min(36,Math.max(18,t*.45));return{x:Math.round(je(e.rect.x+e.rect.width-n,e.rect.x+1,e.rect.x+e.rect.width-1)),y:Math.round(e.rect.y+t/2)}}function je(e,t,n){return Math.min(n,Math.max(t,e))}function $(e){return e.label??e.value??e.identifier}export{p as _,U as a,I as c,L as d,te as f,E as g,x as h,H as i,R as l,T as m,ce as n,B as o,w as p,V as r,P as s,q as t,N as u,v};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{pn as t}from"./sdk-batch.js";import{t as n}from"./script.js";import{t as r}from"./session-paths.js";const i=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function a(t){if(t!==t.trim()||!n.test(t))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(t.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": the AD_* namespace is reserved for built-in replay variables.`);return t}function o(e){return`\${${e}}`}function ee(e){let t=i.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}function s(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const c={kind:`none`};function l(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function te(e){return e.kind===`repair`?{...e,status:`armed`}:e}function u(e){return e.kind===`none`?void 0:e.target}function d(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function f(e){return e.kind===`authoring`&&e.status===`aborted`}function p(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function m(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function h(e){return{kind:`authoring`,status:`armed`,target:l(void 0,e)}}function g(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function _(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function v(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:l(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function y(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function b(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function ne(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function re(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function ie(e){return e.kind===`repair`?e.boundary:void 0}function x(e){return e.kind===`repair`?e.sourcePath:void 0}function S(e){return e.kind===`repair`&&e.status!==`committed`}function C(e){let t=u(e);return t?.kind===`explicit`?t.path:void 0}function w(e){return u(e)?.force===!0}function T(e){return e?.scriptPublication??c}function E(e){let t=T(e);return t.kind===`authoring`&&t.status===`armed`}function D(e,t){e.scriptPublication=h({path:t.path===void 0?void 0:r(t.path),force:t.force===!0})}function O(e){e.scriptPublication=g(T(e))}function k(e){return p(T(e))}function A(e,t){if(!t.saveScript||f(T(e)))return;let n={path:typeof t.saveScript==`string`?r(t.saveScript):void 0,force:t.force===!0},i=T(e);if(i.kind===`repair`){e.scriptPublication=v(i,{requested:n,boundary:i.boundary,sourcePath:i.sourcePath});return}if(i.kind===`authoring`){e.scriptPublication={...i,target:l(i.target,n)};return}e.scriptPublication=h(n)}function j(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:l(n.target,{path:t.explicitPath===void 0?void 0:r(t.explicitPath),force:t.liveForce===!0})})}function M(e,t){e.scriptPublication=_(T(e),t)}function N(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication=_(n,t))}function P(e,t){return t===!0||w(T(e))}function F(e){return m(T(e))}const ae=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),I=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),L=new Set([`cost`,`evidence`,`resolution`,`settle`]),R=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),z=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function B(e,t,n){if(!e)return e;let r=le(e.selectorChain),i=e=>q(e,t);return{...J(e,e=>ce(e,t,n),i),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!i(e))}:{}}}function V(e,t){if(!e)return e;let n=Z(t);return J(e,e=>Q(e,n),e=>G(e,t))}function H(e,t){if(!e)return e;let n=Z(t);return{...e,...e.label===void 0?{}:{label:Q(e.label,n)},ancestry:e.ancestry.map(e=>({...e,...e.label===void 0?{}:{label:Q(e.label,n)}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===void 0?{}:{label:Q(e.scrollRegion.label,n)}}}:{}}}function U(e,t){return!!(e.label!==void 0&&W(e.label,t)||e.ancestry.some(e=>e.label&&W(e.label,t))||e.scrollRegion?.label&&W(e.scrollRegion.label,t))}function W(e,t){for(let n of t.keys())if(e.includes(n))return!0;return!1}function G(e,t){for(let n of t.keys())if(q(e,n))return!0;return!1}function K(e,t,n){return!e||!t?e:{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function q(e,n){return t(e,n)}function J(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[ae.has(e)?e:t(e),oe(r,e,t,n)]))}function oe(e,t,n,r){return typeof e==`string`&&I.has(t)?e:t===`selectorChain`&&$(e)?se(e,r):Y(e,n,r,L.has(t)?t:void 0)}function Y(e,t,n,r){if(typeof e==`string`)return r&&z.has(r)?e:t(e);if(Array.isArray(e))return e.map(e=>Y(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?R.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:t(e),Y(a,t,n,o?`${r}.${e}`:void 0)]}))}function se(e,t){return e.filter(e=>!t(e))}function ce(e,t,n){if(!t)return e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}const X=/\$\{[A-Z_][A-Z0-9_]*\}/y;function Z(e){return[...e].sort(([e],[t])=>t.length-e.length)}function Q(e,t){if(!e||t.length===0)return e;let n=``,r=0;scan:for(;r<e.length;){for(let[i,a]of t)if(e.startsWith(i,r)){n+=a,r+=i.length;continue scan}if(e[r]===`$`){X.lastIndex=r;let t=X.exec(e);if(t){n+=t[0],r+=t[0].length;continue}}n+=e[r],r+=1}return n}function $(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function le(e){return $(e)?e:void 0}export{s as A,S as C,x as D,ie as E,o as M,a as N,w as O,d as S,b as T,re as _,U as a,te as b,D as c,k as d,F as f,c as g,j as h,H as i,ee as j,C as k,P as l,N as m,K as n,O as o,M as p,V as r,A as s,B as t,E as u,v,y as w,p as x,ne as y};
1
+ import{A as e}from"./sdk-contracts.js";import{pn as t}from"./sdk-batch.js";import{t as n}from"./script.js";import{t as r}from"./session-paths.js";const i=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function a(t){if(t!==t.trim()||!n.test(t))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(t.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": the AD_* namespace is reserved for built-in replay variables.`);return t}function o(e){return`\${${e}}`}function ee(e){let t=i.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}function s(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const c={kind:`none`};function l(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function te(e){return e.kind===`repair`?{...e,status:`armed`}:e}function u(e){return e.kind===`none`?void 0:e.target}function d(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function f(e){return e.kind===`authoring`&&e.status===`aborted`}function p(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function m(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function h(e){return{kind:`authoring`,status:`armed`,target:l(void 0,e)}}function g(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function _(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function v(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:l(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function y(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function b(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function ne(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function re(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function ie(e){return e.kind===`repair`?e.boundary:void 0}function x(e){return e.kind===`repair`?e.sourcePath:void 0}function S(e){return e.kind===`repair`&&e.status!==`committed`}function C(e){let t=u(e);return t?.kind===`explicit`?t.path:void 0}function w(e){return u(e)?.force===!0}function T(e){return e?.scriptPublication??c}function E(e){let t=T(e);return t.kind===`authoring`&&t.status===`armed`}function D(e,t){e.scriptPublication=h({path:t.path===void 0?void 0:r(t.path),force:t.force===!0})}function O(e){e.scriptPublication=g(T(e))}function k(e){return p(T(e))}function A(e,t){if(!t.saveScript||f(T(e)))return;let n={path:typeof t.saveScript==`string`?r(t.saveScript):void 0,force:t.force===!0},i=T(e);if(i.kind===`repair`){e.scriptPublication=v(i,{requested:n,boundary:i.boundary,sourcePath:i.sourcePath});return}if(i.kind===`authoring`){e.scriptPublication={...i,target:l(i.target,n)};return}e.scriptPublication=h(n)}function j(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:l(n.target,{path:t.explicitPath===void 0?void 0:r(t.explicitPath),force:t.liveForce===!0})})}function M(e,t){e.scriptPublication=_(T(e),t)}function N(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication=_(n,t))}function P(e,t){return t===!0||w(T(e))}function F(e){return m(T(e))}const ae=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),I=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),L=new Set([`cost`,`evidence`,`resolution`,`settle`]),R=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),z=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function B(e,t,n){if(!e)return e;let r=le(e.selectorChain),i=e=>q(e,t);return{...J(e,e=>ce(e,t,n),i),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!i(e))}:{}}}function V(e,t){if(!e)return e;let n=Z(t);return J(e,e=>Q(e,n),e=>G(e,t))}function H(e,t){if(!e)return e;let n=Z(t);return{...e,...e.label===void 0?{}:{label:Q(e.label,n)},ancestry:e.ancestry.map(e=>({...e,...e.label===void 0?{}:{label:Q(e.label,n)}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===void 0?{}:{label:Q(e.scrollRegion.label,n)}}}:{}}}function U(e,t){return!!(e.label!==void 0&&W(e.label,t)||e.ancestry.some(e=>e.label&&W(e.label,t))||e.scrollRegion?.label&&W(e.scrollRegion.label,t))}function W(e,t){for(let n of t.keys())if(e.includes(n))return!0;return!1}function G(e,t){for(let n of t.keys())if(q(e,n))return!0;return!1}function K(e,t,n){return!e||!t?e:{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function q(e,n){return t(e,n)}function J(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[ae.has(e)?e:t(e),oe(r,e,t,n)]))}function oe(e,t,n,r){return typeof e==`string`&&I.has(t)?e:t===`selectorChain`&&$(e)?se(e,r):Y(e,n,r,L.has(t)?t:void 0)}function Y(e,t,n,r){if(typeof e==`string`)return r&&z.has(r)?e:t(e);if(Array.isArray(e))return e.map(e=>Y(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?R.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:t(e),Y(a,t,n,o?`${r}.${e}`:void 0)]}))}function se(e,t){return e.filter(e=>!t(e))}function ce(e,t,n){if(!t)return e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}const X=/\$\{[A-Z_][A-Z0-9_]*\}/y;function Z(e){return[...e].sort(([e],[t])=>t.length-e.length)}function Q(e,t){if(!e||t.length===0)return e;let n=``,r=0;scan:for(;r<e.length;){for(let[i,a]of t)if(e.startsWith(i,r)){n+=a,r+=i.length;continue scan}if(e[r]===`$`){X.lastIndex=r;let t=X.exec(e);if(t){n+=t[0],r+=t[0].length;continue}}n+=e[r],r+=1}return n}function $(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function le(e){return $(e)?e:void 0}export{s as A,S as C,x as D,ie as E,o as M,a as N,w as O,d as S,b as T,re as _,U as a,te as b,D as c,k as d,F as f,c as g,j as h,H as i,ee as j,C as k,P as l,N as m,K as n,O as o,M as p,V as r,A as s,B as t,E as u,v,y as w,p as x,ne as y};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{b as t,d as n,f as r,l as i}from"./sdk-device.js";import{sr as a}from"./sdk-batch.js";import{a as o,l as s,n as c}from"./exec.js";import"./command.js";import{t as l}from"./parser.js";import{n as u,t as d}from"./numeric.js";import{C as f,D as ee,g as te,i as ne,m as p,o as m,u as h,w as re,y as ie}from"./host-file.js";import{a as ae,o as g}from"./tool-provider.js";import{o as oe,t as se}from"./devicectl.js";import{n as ce}from"./simctl.js";import _ from"node:path";import{fileURLToPath as v}from"node:url";function y(e,t){for(let n of e){if(t(n))return n;let e=y(n.children,t);if(e)return e}}function b(e,t){let n=[];for(let r of e)t(r)&&n.push(r),n.push(...b(r.children,t));return n}function le(e,t){return e.children.find(e=>e.name===t)?.text??null}function x(e,t){let n=y(e,e=>e.name===`schema`&&e.attributes.name===t);return n?n.children.filter(e=>e.name===`col`).map(e=>le(e,`mnemonic`)??``):[]}function S(e){if(!e||e.children.some(e=>e.name===`sentinel`)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function C(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:S(e):null}function w(e,t){for(let n of e)w(n.children,t),n.attributes.id&&t.set(n.attributes.id,{numberValue:S(n),process:E(n)})}function T(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.process??null:E(e):null}function E(e){if(!e||e.children.some(e=>e.name===`sentinel`))return null;let t=S(y(e.children,e=>e.name===`pid`)),n=(e.attributes.fmt??``).trim().replace(/\s+\(\d+\)$/,``).trim();return t===null&&n.length===0?null:{pid:t??void 0,name:n.length>0?n:void 0}}function ue(e){return new Map(b(e,e=>!!e.attributes.id).flatMap(e=>{let t=e.attributes.id;return t?[[t,e]]:[]}))}function D(e,t){if(e)return e.attributes.ref?t.get(e.attributes.ref):e}function O(e,t=10){let n=l(e),r=ue(n),i=new Map,a=0,o=0;for(let e of b(n,e=>e.name===`row`)){let t=k(e,r),n=de(e,r);if(t===void 0||!n)continue;let s=n.attributes.name?.trim()||`<unknown>`,c=fe(n,r),l=`${c??``}\u0000${s}`,u=i.get(l);i.set(l,{symbol:s,binary:c,weightNs:(u?.weightNs??0)+t}),a+=1,o+=t}let s=Math.max(0,Math.floor(t)),c=[...i.values()].sort((e,t)=>t.weightNs-e.weightNs||e.symbol.localeCompare(t.symbol)).slice(0,s).map(({symbol:e,binary:t,weightNs:n})=>({symbol:e,binary:t,selfSampleMs:A(n),selfSamplePercent:o>0?u(n/o*100):0}));return{sampleCount:a,totalSampleWeightMs:A(o),topFunctions:c}}function k(e,t){let n=D(e.children.find(e=>e.name===`weight`),t);if(!n?.text)return;let r=Number(n.text);return Number.isFinite(r)&&r>0?r:void 0}function de(e,t){return D(D(e.children.find(e=>e.name===`backtrace`),t)?.children.find(e=>e.name===`frame`),t)}function fe(e,t){return D(e.children.find(e=>e.name===`binary`),t)?.attributes.name?.trim()||void 0}function A(e){return Math.round(e/1e6*1e3)/1e3}async function pe(e){let n=await _e(e.device,e.appBundleId);await m(_.dirname(e.outPath));let r=N({device:e.device,template:e.template,target:n.pids,outPath:e.outPath}),i=new Date().toISOString(),a=await P(r,e.outPath,{device:e.device,appBundleId:e.appBundleId,failureMessage:`Failed to start Apple xctrace ${e.mode} capture for ${e.appBundleId}`},async()=>{let e=s(`xcrun`,r,{allowFailure:!0}),t=await ve(e.wait);return t?{failure:t}:{recorded:e}});return{kind:`xctrace`,mode:e.mode,template:e.template,outPath:e.outPath,appBundleId:e.appBundleId,deviceId:e.device.id,platform:t(e.device),targetPids:n.pids,targetProcesses:n.processNames,startedAt:i,child:a.child,wait:a.wait}}async function me(e,t=e.outPath){t!==e.outPath&&await m(_.dirname(t));let n=o(await L(e,{failOnForcedKill:!0}),`Failed to stop Apple xctrace ${e.mode} capture`,t=>({tracePath:e.outPath,captureCleanedUp:!0,hint:B(t.stdout,t.stderr)}));return t!==e.outPath&&await re(e.outPath,t).catch(async()=>{await ne(e.outPath,t),await f(e.outPath)}),await z(t,{message:`xctrace produced no trace data`,hint:`Keep the Apple device unlocked and connected, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.deviceId,stdout:n.stdout,stderr:n.stderr}),{kind:`xctrace`,mode:e.mode,template:e.template,outPath:t,appBundleId:e.appBundleId,deviceId:e.deviceId,platform:e.platform,targetPids:e.targetPids,targetProcesses:e.targetProcesses,startedAt:e.startedAt,endedAt:new Date().toISOString()}}async function he(e){return await L(e,{failOnForcedKill:!1})}async function ge(t){let n=await p(`agent-device-xctrace-report-`),r=_.join(n,`trace-toc.xml`),i=_.join(n,`time-profile.xml`);try{let n=await M({tracePath:t.tracePath,outPath:r,query:`toc`,failureMessage:`Failed to export Apple xctrace report metadata`,failureDetails:{tracePath:t.tracePath}}),a=await M({tracePath:t.tracePath,outPath:i,query:{schema:`time-profile`},failureMessage:`Failed to export Apple xctrace Time Profiler samples`,failureDetails:{tracePath:t.tracePath}}),o=ye({...t,tocXml:n,timeProfileXml:a});if(o.summary.sampleCount===0)throw new e(`COMMAND_FAILED`,`Apple xctrace CPU report contained no samples`,{tracePath:t.tracePath,tableSchemas:o.summary.tableSchemas,hint:`Keep the app active while recording, then retry. Open the raw trace in Instruments if it still contains no Time Profiler samples.`});return await m(_.dirname(t.outPath)),await ee(t.outPath,`${JSON.stringify(o,null,2)}\n`),o}finally{await f(n).catch(()=>{})}}async function j(e){let t=N({device:e.device,template:e.template,target:e.target,timeLimit:e.timeLimit,outPath:e.tracePath}),{result:n,...r}=await P(t,e.tracePath,e,async()=>{let e=new Date().toISOString(),n=await g(t,{allowFailure:!0,timeoutMs:6e4});return n.exitCode===0?{recorded:{result:n,startedAt:e,endedAt:new Date().toISOString(),capturedAtMs:Date.now()}}:{failure:n}});return e.requireTraceData&&await z(e.tracePath,{message:`${e.failureMessage}: xctrace produced no trace data`,hint:`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:n.stdout,stderr:n.stderr}),r}async function M(e){let t=[`xctrace`,`export`,`--input`,e.tracePath,...e.query===`toc`?[`--toc`]:[`--xpath`,`/trace-toc/run/data/table[@schema="${e.query.schema}"]`],`--output`,e.outPath];return o(await g(t,{allowFailure:!0,timeoutMs:15e3}),e.failureMessage,n=>({cmd:`xcrun`,args:t,...e.failureDetails,hint:B(n.stdout,n.stderr)})),await ie(e.outPath)}async function _e(t,r){if(!i(t.platform))throw new e(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on Android.`,{platform:t.platform,hint:`Android native profiling belongs to the Android perf rollout and is not implemented under Apple xctrace.`});let{readAppleProcessSamples:o,resolveAppleExecutable:s,resolveIosDevicePerfTarget:c}=await import(`./perf-target.js`);if(n(t)&&t.kind===`device`){let e=await c(t,r);return{pids:e.map(e=>e.pid),processNames:a(e.map(e=>_.basename(v(e.executable))))}}let l=await s(t,r),u=await o(t,l);if(u.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${r}`,{appBundleId:r,deviceId:t.id,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});return{pids:u.map(e=>e.pid),processNames:[l.executableName]}}function N(e){return[`xctrace`,`record`,`--template`,e.template,...n(e.device)?[`--device`,e.device.id]:[],...e.target===`all-processes`?[`--all-processes`]:e.target.flatMap(e=>[`--attach`,String(e)]),...e.timeLimit?[`--time-limit`,e.timeLimit]:[],`--output`,e.outPath,`--quiet`,`--no-prompt`]}async function P(t,n,r,i){for(let a=1;;a+=1){await I(n,a);let o=await i();if(`recorded`in o)return o.recorded;if(a<3&&F(o.failure))continue;let{failure:s}=o;throw new e(`COMMAND_FAILED`,r.failureMessage,c(s,{cmd:`xcrun`,args:t,appBundleId:r.appBundleId,deviceId:r.device.id,hint:B(s.stdout,s.stderr)}))}}function F(e){let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`_lockkperf`)||t.includes(`could not lock kperf`)||t.includes(`likely another session just started`)}async function I(e,t){t<=1||(await f(e).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)))}async function ve(e){return await Promise.race([e,new Promise(e=>setTimeout(e,500))])}async function L(t,n){t.child.kill(`SIGINT`);let r=await R(t.wait,45e3);if(r)return r;t.child.kill(`SIGKILL`);let i=await R(t.wait,5e3);if(i&&!n.failOnForcedKill)return i;throw i?new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop`,{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,tracePath:t.outPath,captureCleanedUp:!0,forcedKill:!0,hint:`xctrace did not finish after SIGINT, so it was force-killed. Retry the perf command after confirming no other xctrace session is active.`}):new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop after SIGKILL`,{tracePath:t.outPath,captureCleanedUp:!1,forcedKill:!0,hint:`xctrace did not exit after SIGKILL. Inspect running xctrace processes before retrying.`})}async function R(e,t){return await Promise.race([e,new Promise(e=>setTimeout(e,t))])}async function z(t,n){let r=await h(t).catch(()=>null);if(!(r?.isDirectory()===!0?(await te(t).catch(()=>[])).length>0:(r?.size??0)>0))throw new e(`COMMAND_FAILED`,n.message,{tracePath:t,appBundleId:n.appBundleId,deviceId:n.deviceId,stdout:n.stdout,stderr:n.stderr,hint:n.hint})}function ye(e){let t=l(e.tocXml),n=b(t,e=>e.name===`run`),r=a(b(t,e=>e.name===`table`).map(e=>e.attributes.schema).filter(e=>typeof e==`string`&&e.length>0)).sort(),i=O(e.timeProfileXml);return{kind:`xctrace`,mode:`cpu-profile`,template:e.template,tracePath:e.tracePath,reportPath:e.outPath,appBundleId:e.appBundleId,generatedAt:new Date().toISOString(),summary:{runCount:n.length,tableSchemas:r,...i}}}function B(e,t){let n=oe(e,t);if(n)return n;let r=`${e}\n${t}`.toLowerCase();return r.includes(`no device matched`)||r.includes(`failed to find device`)?se:r.includes(`timed out`)?`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`:`Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it.`}const V=`xctrace-animation-hitches`;function be(e){let t=xe(e.frameLifetimesXml),n=Se(e.displayInfoXml),r=Ce(e.hitchesXml).filter(t=>Ee(t,e.processIds,e.processNames)),i=r.length,o=Math.max(0,Math.round(Date.parse(e.windowEndedAt)-Date.parse(e.windowStartedAt))),s=De(r,Date.parse(e.windowStartedAt));return{droppedFramePercent:t>0?u(i/t*100):0,droppedFrameCount:i,totalFrameCount:t,sampleWindowMs:o,windowStartedAt:e.windowStartedAt,windowEndedAt:e.windowEndedAt,measuredAt:e.measuredAt,method:V,matchedProcesses:a(r.map(e=>e.processName).filter(e=>typeof e==`string`&&e.length>0)),frameDeadlineMs:n===void 0?void 0:d(1e3/n),refreshRateHz:n,worstWindows:s.length>0?s:void 0}}function xe(e){return Oe(e,`hitches-frame-lifetimes`).length}function Se(e){if(!e)return;let{rows:t,schema:n}=U(e,`device-display-info`),r=n.indexOf(`max-refresh-rate`);if(r<0)return;let i=new Map;for(let e of t){w(e.children,i);let t=C(e.children[r],i);if(t!==null&&t>0)return t}}function Ce(e){let t=l(e),n=we(t);if(!n)return[];let r=new Map;return b(t,e=>e.name===`row`).map(e=>Te(e,n,r)).filter(e=>!!e)}function we(e){let t=x(e,`hitches`),n={start:t.indexOf(`start`),duration:t.indexOf(`duration`),process:t.indexOf(`process`),isSystem:t.indexOf(`is-system`)};return Object.values(n).every(e=>e>=0)?n:null}function Te(e,t,n){if(w(e.children,n),ke(e.children[t.isSystem],n)===!0)return null;let r=C(e.children[t.start],n),i=C(e.children[t.duration],n);if(r===null||i===null)return null;let a=T(e.children[t.process],n);return{startNs:r,durationNs:i,pid:a?.pid,processName:a?.name}}function Ee(e,t,n){return e.pid!==void 0&&t.includes(e.pid)?!0:e.processName?n.includes(e.processName):!1}function De(e,t){if(e.length===0)return[];let n=[...e].sort((e,t)=>e.startNs-t.startNs),r=[],i=[];for(let e of n){let t=i.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){i.push(e);continue}r.push(i),i=[e]}return i.length>0&&r.push(i),r.map(e=>H(e,t)).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}function H(e,t){let n=Math.min(...e.map(e=>e.startNs)),r=Math.max(...e.map(e=>e.startNs+e.durationNs)),i=Math.max(0,Math.round(n/1e6)),a=Math.max(i,Math.round(r/1e6));return{startOffsetMs:i,endOffsetMs:a,startAt:new Date(t+i).toISOString(),endAt:new Date(t+a).toISOString(),missedDeadlineFrameCount:e.length,worstFrameMs:d(Math.max(...e.map(e=>e.durationNs))/1e6)}}function Oe(e,t){return U(e,t).rows}function U(e,t){let n=l(e),r=x(n,t);return{rows:r.length===0?[]:b(n,e=>e.name===`row`),schema:r}}function ke(e,t){let n=C(e,t);return n===null?null:n!==0}const W=`ps-process-snapshot`,G=`xctrace-activity-monitor`,K=`leaks-output-graph`,q=12e4;async function Ae(t,r){if(n(t)&&t.kind===`device`)return await Be(t,r);let{readAppleProcessSamples:i,resolveAppleExecutable:a}=await import(`./perf-target.js`),o=await a(t,r),s=await i(t,o);if(s.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${r}`,{appBundleId:r,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});let c=new Date().toISOString();return $({residentMemoryKb:s.reduce((e,t)=>e+t.rssKb,0),measuredAt:c,matchedProcesses:[o.executableName],memoryMethod:W})}async function je(t,n,r){let i=Y(t);if(!i.memgraph)return{available:!1,kind:`memgraph`,reason:i.reason,hint:i.hint,support:i};let a=await We(t,n,i);if(a.available===!1)return a;let{process:o}=a;await m(_.dirname(r));let s=await Pe(r),l;try{l=await Me(t,r,o.pid)}catch(e){throw await J(r,s),Ne(t,n,o,r,e)}if(l.exitCode!==0)throw await J(r,s),new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,c(l,{kind:`memgraph`,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),path:r,hint:Q(t,l.stdout,l.stderr)}));let u=await h(r).catch(()=>null);if(!u?.isFile()||u.size<=0)throw await J(r,s),new e(`COMMAND_FAILED`,`Apple memgraph artifact is missing or empty`,{kind:`memgraph`,appBundleId:n,pid:o.pid,path:r,hint:`Retry with a writable --out path. If the file is still empty, run with --debug and inspect leaks output.`});return{available:!0,kind:`memgraph`,path:r,sizeBytes:u.size,measuredAt:new Date().toISOString(),method:K,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),support:i}}async function Me(e,t,n){return r(e)?await ae(`leaks`,[`--outputGraph=${t}`,String(n)],{allowFailure:!0,timeoutMs:q}):await g(ce(e,[`spawn`,e.id,`leaks`,`--outputGraph=${t}`,String(n)]),{allowFailure:!0,timeoutMs:q})}function Ne(t,n,r,i,a){if(a instanceof e){let o=a.details??{};return new e(a.code,`Failed to capture Apple memgraph for ${n}`,{...o,kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:Q(t,typeof o.stdout==`string`?o.stdout:``,typeof o.stderr==`string`&&o.stderr.length>0?o.stderr:a.message)},a)}return new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,{kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:`Retry perf memory snapshot. If it still fails, run with --debug and inspect leaks output.`},a)}async function Pe(e){return await h(e).then(e=>e.isFile()).catch(()=>!1)}async function J(e,t){t||await f(e).catch(()=>{})}async function Fe(r,i){if(!n(r)||r.kind!==`device`)throw new e(`COMMAND_FAILED`,`Apple frame-health sampling is currently available only on connected iOS devices.`,{metric:`fps`,platform:t(r),deviceKind:r.kind});let{resolveIosDevicePerfTarget:o}=await import(`./perf-target.js`),s=await o(r,i),c=await Re(r,i,s);return be({hitchesXml:c.hitchesXml,frameLifetimesXml:c.frameLifetimesXml,displayInfoXml:c.displayInfoXml,processIds:s.map(e=>e.pid),processNames:a(s.map(e=>_.basename(v(e.executable)))),windowStartedAt:c.windowStartedAt,windowEndedAt:c.windowEndedAt,measuredAt:c.windowEndedAt})}function Ie(e){return n(e)&&e.kind===`device`?{method:V,description:`Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`short 2s xctrace Animation Hitches record of the active app process`,resetsAfterRead:!1}:{method:V,description:`Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.`,unit:`percent`,primaryField:`droppedFramePercent`}}function Le(e){if(n(e)&&e.kind===`device`)return{method:G,description:`Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.`,unit:`kB`};let t=r(e)?`host ps for the running macOS app executable resolved from the bundle ID.`:`xcrun simctl spawn ps, with host ps fallback, for the running iOS simulator app executable resolved from the bundle ID.`;return{method:W,description:`Resident memory snapshot from ${t}`,unit:`kB`}}function Y(e){return n(e)&&e.kind===`device`?{platform:t(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Physical iOS device memgraph capture is not exposed through reliable local agent-device tooling.`,hint:`Use perf memory sample for a compact resident-memory reading, or reproduce on an iOS simulator/macOS target for memgraph capture.`}:n(e)&&e.kind===`simulator`?{platform:t(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`iOS simulator processes are host-visible through simctl spawn leaks.`,hint:`Keep the simulator app running in the foreground while the memgraph is captured.`}:r(e)?{platform:t(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`macOS app processes are host-visible to leaks --outputGraph.`,hint:`Grant Terminal/agent process permissions if macOS denies process inspection.`}:{platform:t(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Apple memgraph capture is available only for iOS simulator and macOS app sessions.`,hint:`Use perf memory sample on supported app sessions, or rerun against iOS simulator/macOS for memgraph capture.`}}async function Re(e,t,n){let r=await p(`agent-device-ios-frame-perf-`),i=_.join(r,`animation-hitches.trace`);try{let a=await j({device:e,appBundleId:t,tracePath:i,template:`Animation Hitches`,timeLimit:`2s`,target:n.map(e=>e.pid),requireTraceData:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`}),o={device:e,appBundleId:t,tracePath:i,tempDir:r};return{windowStartedAt:a.startedAt,windowEndedAt:a.endedAt,hitchesXml:await X(o,`hitches`),frameLifetimesXml:await X(o,`hitches-frame-lifetimes`),displayInfoXml:await X(o,`device-display-info`).catch(()=>void 0)}}finally{await f(r).catch(()=>{})}}async function X(e,t){return await M({tracePath:e.tracePath,outPath:_.join(e.tempDir,`${t}.xml`),query:{schema:t},failureMessage:`Failed to export iOS device ${t} data`,failureDetails:{appBundleId:e.appBundleId,deviceId:e.device.id}})}async function ze(t){let n=l(t),r=x(n,`activity-monitor-process-live`);if(r.length===0)throw new e(`COMMAND_FAILED`,`Failed to parse xctrace activity-monitor-process-live schema`);let i=r.indexOf(`pid`),a=r.indexOf(`process`),o=r.indexOf(`memory-real`);if(i<0||a<0||o<0)throw new e(`COMMAND_FAILED`,`xctrace activity-monitor-process-live export is missing expected columns`);let s=b(n,e=>e.name===`row`),c=[],u=new Map;for(let e of s){let t=e.children;if(t.length===0)continue;w(t,u);let n=C(t[i],u),r=T(t[a],u)?.name;n===null||!Number.isFinite(n)||!r||c.push({pid:n,processName:r,residentMemoryBytes:C(t[o],u)})}return c}async function Be(t,n){let{resolveIosDevicePerfTarget:r}=await import(`./perf-target.js`),i=await r(t,n),a=await Ve(t,n),o=He(await ze(a.xml),i,n,t);if(o.residentMemoryBytes===null)throw new e(`COMMAND_FAILED`,`Incomplete Activity Monitor sample for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});return $({residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,memoryMethod:G})}async function Ve(e,t){let n=await p(`agent-device-ios-perf-`),r=_.join(n,`sample.trace`);try{return{capturedAtMs:(await j({device:e,appBundleId:t,tracePath:r,template:`Activity Monitor`,timeLimit:`1s`,target:`all-processes`,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`})).capturedAtMs,xml:await X({device:e,appBundleId:t,tracePath:r,tempDir:n},`activity-monitor-process-live`)}}finally{await f(n).catch(()=>{})}}function He(t,n,r,i){let o=new Set(n.map(e=>e.pid)),s=new Set(n.map(e=>_.basename(v(e.executable)))),c=t.filter(e=>o.has(e.pid)||s.has(e.processName));if(c.length===0)throw new e(`COMMAND_FAILED`,`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:i.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});let l=new Map;for(let e of c){let t=l.get(e.pid);if(!t){l.set(e.pid,e);continue}l.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,residentMemoryBytes:Ke(t.residentMemoryBytes,e.residentMemoryBytes)})}let u=[...l.values()],d=u.map(e=>e.residentMemoryBytes).filter(e=>e!==null);return{residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:a(u.map(e=>e.processName))}}function Z(e){let[t=``]=e.trim().split(/\s+/,1);return t}async function Ue(t,n,r){let{readAppleProcessSamples:i}=await import(`./perf-target.js`),a=(await i(t,r)).sort((e,t)=>t.rssKb-e.rssKb)[0];if(a)return a;throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{kind:`memgraph`,appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf memory snapshot.`})}async function We(e,t,n){try{let{resolveAppleExecutable:n}=await import(`./perf-target.js`);return{available:!0,process:await Ue(e,t,await n(e,t))}}catch(t){if(Ge(e,t))return{available:!1,kind:`memgraph`,reason:`iOS simulator memgraph capture needs process tools inside simctl spawn, but this simulator runtime did not provide ps.`,hint:`Use perf memory sample when available, or retry memgraph on a simulator runtime that includes process tools such as ps and leaks.`,support:{...n,memgraph:!1}};throw t}}function Ge(t,r){if(!n(t)||t.kind!==`simulator`||!(r instanceof e))return!1;let i=r.details??{},a=Array.isArray(i.args)?i.args.join(` `):``,o=typeof i.stderr==`string`?i.stderr:``,s=`${r.message}\n${o}`.toLowerCase();return a.includes(`simctl spawn`)&&a.includes(` ps `)&&s.includes(`no such file`)}function Q(e,t,n){let i=`${t}\n${n}`.toLowerCase();return i.includes(`timed out`)||i.includes(`timeout`)?`Apple memgraph capture can take longer than metric sampling. Keep the app running and retry; if it times out again, collect a smaller reproduction before capturing leaks --outputGraph.`:i.includes(`not found`)||i.includes(`no such file`)?`Install Xcode command line tools and ensure leaks is available, then retry.`:i.includes(`permission`)||i.includes(`denied`)||i.includes(`not authorized`)?r(e)?`Grant the agent terminal process permission to inspect this macOS app, then retry.`:`Keep the simulator booted and app running; if inspection is denied, retry with a debug simulator build.`:`Keep the app process running and retry perf memory snapshot with --debug if the failure persists.`}function $(e){return{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}function Ke(e,t){return e===null?t:t===null?e:Math.max(e,t)}export{Ie as buildAppleFrameSamplingMetadata,Le as buildAppleMemorySamplingMetadata,Y as buildAppleMemorySnapshotSupport,je as captureAppleMemorySnapshot,he as cleanupAppleXctracePerfCapture,F as isRetryableIosDeviceTraceRecordFailure,B as resolveIosDevicePerfHint,Fe as sampleAppleFramePerf,Ae as sampleAppleMemoryPerf,pe as startAppleXctracePerfCapture,me as stopAppleXctracePerfCapture,ge as writeAppleXctracePerfReport};
1
+ import{A as e}from"./sdk-contracts.js";import{b as t,d as n,f as r,l as i}from"./sdk-device.js";import{sr as a}from"./sdk-batch.js";import{a as o,l as s,n as c}from"./exec.js";import"./command.js";import{t as l}from"./parser.js";import{n as u,t as d}from"./numeric.js";import{C as f,D as ee,g as te,i as ne,m as p,o as m,u as h,w as re,y as ie}from"./host-file.js";import{a as ae,o as g}from"./tool-provider.js";import{o as oe,t as se}from"./devicectl.js";import{n as ce}from"./simctl.js";import _ from"node:path";import{fileURLToPath as v}from"node:url";function y(e,t){for(let n of e){if(t(n))return n;let e=y(n.children,t);if(e)return e}}function b(e,t){let n=[];for(let r of e)t(r)&&n.push(r),n.push(...b(r.children,t));return n}function le(e,t){return e.children.find(e=>e.name===t)?.text??null}function x(e,t){let n=y(e,e=>e.name===`schema`&&e.attributes.name===t);return n?n.children.filter(e=>e.name===`col`).map(e=>le(e,`mnemonic`)??``):[]}function S(e){if(!e||e.children.some(e=>e.name===`sentinel`)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function C(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:S(e):null}function w(e,t){for(let n of e)w(n.children,t),n.attributes.id&&t.set(n.attributes.id,{numberValue:S(n),process:E(n)})}function T(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.process??null:E(e):null}function E(e){if(!e||e.children.some(e=>e.name===`sentinel`))return null;let t=S(y(e.children,e=>e.name===`pid`)),n=(e.attributes.fmt??``).trim().replace(/\s+\(\d+\)$/,``).trim();return t===null&&n.length===0?null:{pid:t??void 0,name:n.length>0?n:void 0}}function ue(e){return new Map(b(e,e=>!!e.attributes.id).flatMap(e=>{let t=e.attributes.id;return t?[[t,e]]:[]}))}function D(e,t){if(e)return e.attributes.ref?t.get(e.attributes.ref):e}const O=new Set([`backtrace`,`tagged-backtrace`]);function k(e,t=10){let n=l(e),r=ue(n),i=new Map,a=0,o=0;for(let e of b(n,e=>e.name===`row`)){let t=A(e,r),n=de(e,r);if(t===void 0||!n)continue;let s=n.attributes.name?.trim()||`<unknown>`,c=fe(n,r),l=`${c??``}\u0000${s}`,u=i.get(l);i.set(l,{symbol:s,binary:c,weightNs:(u?.weightNs??0)+t}),a+=1,o+=t}let s=Math.max(0,Math.floor(t)),c=[...i.values()].sort((e,t)=>t.weightNs-e.weightNs||e.symbol.localeCompare(t.symbol)).slice(0,s).map(({symbol:e,binary:t,weightNs:n})=>({symbol:e,binary:t,selfSampleMs:j(n),selfSamplePercent:o>0?u(n/o*100):0}));return{sampleCount:a,totalSampleWeightMs:j(o),topFunctions:c}}function A(e,t){let n=D(e.children.find(e=>e.name===`weight`),t);if(!n?.text)return;let r=Number(n.text);return Number.isFinite(r)&&r>0?r:void 0}function de(e,t){return D(D(e.children.find(e=>O.has(e.name)),t)?.children.find(e=>e.name===`frame`),t)}function fe(e,t){return D(e.children.find(e=>e.name===`binary`),t)?.attributes.name?.trim()||void 0}function j(e){return Math.round(e/1e6*1e3)/1e3}async function pe(e){let n=await _e(e.device,e.appBundleId);await m(_.dirname(e.outPath));let r=P({device:e.device,template:e.template,target:n.pids,outPath:e.outPath}),i=new Date().toISOString(),a=await F(r,e.outPath,{device:e.device,appBundleId:e.appBundleId,failureMessage:`Failed to start Apple xctrace ${e.mode} capture for ${e.appBundleId}`},async()=>{let e=s(`xcrun`,r,{allowFailure:!0}),t=await ye(e.wait);return t?{failure:t}:{recorded:e}});return{kind:`xctrace`,mode:e.mode,template:e.template,outPath:e.outPath,appBundleId:e.appBundleId,deviceId:e.device.id,platform:t(e.device),targetPids:n.pids,targetProcesses:n.processNames,startedAt:i,child:a.child,wait:a.wait}}async function me(e,t=e.outPath){t!==e.outPath&&await m(_.dirname(t));let n=o(await L(e,{failOnForcedKill:!0}),`Failed to stop Apple xctrace ${e.mode} capture`,t=>({tracePath:e.outPath,captureCleanedUp:!0,hint:B(t.stdout,t.stderr)}));return t!==e.outPath&&await re(e.outPath,t).catch(async()=>{await ne(e.outPath,t),await f(e.outPath)}),await z(t,{message:`xctrace produced no trace data`,hint:`Keep the Apple device unlocked and connected, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.deviceId,stdout:n.stdout,stderr:n.stderr}),{kind:`xctrace`,mode:e.mode,template:e.template,outPath:t,appBundleId:e.appBundleId,deviceId:e.deviceId,platform:e.platform,targetPids:e.targetPids,targetProcesses:e.targetProcesses,startedAt:e.startedAt,endedAt:new Date().toISOString()}}async function he(e){return await L(e,{failOnForcedKill:!1})}async function ge(t){let n=await p(`agent-device-xctrace-report-`),r=_.join(n,`trace-toc.xml`),i=_.join(n,`time-profile.xml`);try{let n=await N({tracePath:t.tracePath,outPath:r,query:`toc`,failureMessage:`Failed to export Apple xctrace report metadata`,failureDetails:{tracePath:t.tracePath}}),a=await N({tracePath:t.tracePath,outPath:i,query:{schema:`time-profile`},failureMessage:`Failed to export Apple xctrace Time Profiler samples`,failureDetails:{tracePath:t.tracePath}}),o=be({...t,tocXml:n,timeProfileXml:a});if(o.summary.sampleCount===0)throw new e(`COMMAND_FAILED`,`Apple xctrace CPU report contained no samples`,{tracePath:t.tracePath,tableSchemas:o.summary.tableSchemas,hint:`Keep the app active while recording, then retry. Open the raw trace in Instruments if it still contains no Time Profiler samples.`});return await m(_.dirname(t.outPath)),await ee(t.outPath,`${JSON.stringify(o,null,2)}\n`),o}finally{await f(n).catch(()=>{})}}async function M(e){let t=P({device:e.device,template:e.template,target:e.target,timeLimit:e.timeLimit,outPath:e.tracePath}),{result:n,...r}=await F(t,e.tracePath,e,async()=>{let e=new Date().toISOString(),n=await g(t,{allowFailure:!0,timeoutMs:6e4});return n.exitCode===0?{recorded:{result:n,startedAt:e,endedAt:new Date().toISOString(),capturedAtMs:Date.now()}}:{failure:n}});return e.requireTraceData&&await z(e.tracePath,{message:`${e.failureMessage}: xctrace produced no trace data`,hint:`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:n.stdout,stderr:n.stderr}),r}async function N(e){let t=[`xctrace`,`export`,`--input`,e.tracePath,...e.query===`toc`?[`--toc`]:[`--xpath`,`/trace-toc/run/data/table[@schema="${e.query.schema}"]`],`--output`,e.outPath];return o(await g(t,{allowFailure:!0,timeoutMs:15e3}),e.failureMessage,n=>({cmd:`xcrun`,args:t,...e.failureDetails,hint:B(n.stdout,n.stderr)})),await ie(e.outPath)}async function _e(t,r){if(!i(t.platform))throw new e(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on Android.`,{platform:t.platform,hint:`Android native profiling belongs to the Android perf rollout and is not implemented under Apple xctrace.`});let{readAppleProcessSamples:o,resolveAppleExecutable:s,resolveIosDevicePerfTarget:c}=await import(`./perf-target.js`);if(n(t)&&t.kind===`device`){let e=await c(t,r);return{pids:e.map(e=>e.pid),processNames:a(e.map(e=>_.basename(v(e.executable))))}}let l=await s(t,r),u=await o(t,l);if(u.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${r}`,{appBundleId:r,deviceId:t.id,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});return{pids:u.map(e=>e.pid),processNames:[l.executableName]}}function P(e){return[`xctrace`,`record`,`--template`,e.template,...n(e.device)?[`--device`,e.device.id]:[],...e.target===`all-processes`?[`--all-processes`]:e.target.flatMap(e=>[`--attach`,String(e)]),...e.timeLimit?[`--time-limit`,e.timeLimit]:[],`--output`,e.outPath,`--quiet`,`--no-prompt`]}async function F(t,n,r,i){for(let a=1;;a+=1){await ve(n,a);let o=await i();if(`recorded`in o)return o.recorded;if(a<3&&I(o.failure))continue;let{failure:s}=o;throw new e(`COMMAND_FAILED`,r.failureMessage,c(s,{cmd:`xcrun`,args:t,appBundleId:r.appBundleId,deviceId:r.device.id,hint:B(s.stdout,s.stderr)}))}}function I(e){let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`_lockkperf`)||t.includes(`could not lock kperf`)||t.includes(`likely another session just started`)}async function ve(e,t){t<=1||(await f(e).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)))}async function ye(e){return await Promise.race([e,new Promise(e=>setTimeout(e,500))])}async function L(t,n){t.child.kill(`SIGINT`);let r=await R(t.wait,45e3);if(r)return r;t.child.kill(`SIGKILL`);let i=await R(t.wait,5e3);if(i&&!n.failOnForcedKill)return i;throw i?new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop`,{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,tracePath:t.outPath,captureCleanedUp:!0,forcedKill:!0,hint:`xctrace did not finish after SIGINT, so it was force-killed. Retry the perf command after confirming no other xctrace session is active.`}):new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop after SIGKILL`,{tracePath:t.outPath,captureCleanedUp:!1,forcedKill:!0,hint:`xctrace did not exit after SIGKILL. Inspect running xctrace processes before retrying.`})}async function R(e,t){return await Promise.race([e,new Promise(e=>setTimeout(e,t))])}async function z(t,n){let r=await h(t).catch(()=>null);if(!(r?.isDirectory()===!0?(await te(t).catch(()=>[])).length>0:(r?.size??0)>0))throw new e(`COMMAND_FAILED`,n.message,{tracePath:t,appBundleId:n.appBundleId,deviceId:n.deviceId,stdout:n.stdout,stderr:n.stderr,hint:n.hint})}function be(e){let t=l(e.tocXml),n=b(t,e=>e.name===`run`),r=a(b(t,e=>e.name===`table`).map(e=>e.attributes.schema).filter(e=>typeof e==`string`&&e.length>0)).sort(),i=k(e.timeProfileXml);return{kind:`xctrace`,mode:`cpu-profile`,template:e.template,tracePath:e.tracePath,reportPath:e.outPath,appBundleId:e.appBundleId,generatedAt:new Date().toISOString(),summary:{runCount:n.length,tableSchemas:r,...i}}}function B(e,t){let n=oe(e,t);if(n)return n;let r=`${e}\n${t}`.toLowerCase();return r.includes(`no device matched`)||r.includes(`failed to find device`)?se:r.includes(`timed out`)?`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`:`Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it.`}const V=`xctrace-animation-hitches`;function xe(e){let t=Se(e.frameLifetimesXml),n=Ce(e.displayInfoXml),r=we(e.hitchesXml).filter(t=>De(t,e.processIds,e.processNames)),i=r.length,o=Math.max(0,Math.round(Date.parse(e.windowEndedAt)-Date.parse(e.windowStartedAt))),s=H(r,Date.parse(e.windowStartedAt));return{droppedFramePercent:t>0?u(i/t*100):0,droppedFrameCount:i,totalFrameCount:t,sampleWindowMs:o,windowStartedAt:e.windowStartedAt,windowEndedAt:e.windowEndedAt,measuredAt:e.measuredAt,method:V,matchedProcesses:a(r.map(e=>e.processName).filter(e=>typeof e==`string`&&e.length>0)),frameDeadlineMs:n===void 0?void 0:d(1e3/n),refreshRateHz:n,worstWindows:s.length>0?s:void 0}}function Se(e){return ke(e,`hitches-frame-lifetimes`).length}function Ce(e){if(!e)return;let{rows:t,schema:n}=U(e,`device-display-info`),r=n.indexOf(`max-refresh-rate`);if(r<0)return;let i=new Map;for(let e of t){w(e.children,i);let t=C(e.children[r],i);if(t!==null&&t>0)return t}}function we(e){let t=l(e),n=Te(t);if(!n)return[];let r=new Map;return b(t,e=>e.name===`row`).map(e=>Ee(e,n,r)).filter(e=>!!e)}function Te(e){let t=x(e,`hitches`),n={start:t.indexOf(`start`),duration:t.indexOf(`duration`),process:t.indexOf(`process`),isSystem:t.indexOf(`is-system`)};return Object.values(n).every(e=>e>=0)?n:null}function Ee(e,t,n){if(w(e.children,n),Ae(e.children[t.isSystem],n)===!0)return null;let r=C(e.children[t.start],n),i=C(e.children[t.duration],n);if(r===null||i===null)return null;let a=T(e.children[t.process],n);return{startNs:r,durationNs:i,pid:a?.pid,processName:a?.name}}function De(e,t,n){return e.pid!==void 0&&t.includes(e.pid)?!0:e.processName?n.includes(e.processName):!1}function H(e,t){if(e.length===0)return[];let n=[...e].sort((e,t)=>e.startNs-t.startNs),r=[],i=[];for(let e of n){let t=i.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){i.push(e);continue}r.push(i),i=[e]}return i.length>0&&r.push(i),r.map(e=>Oe(e,t)).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}function Oe(e,t){let n=Math.min(...e.map(e=>e.startNs)),r=Math.max(...e.map(e=>e.startNs+e.durationNs)),i=Math.max(0,Math.round(n/1e6)),a=Math.max(i,Math.round(r/1e6));return{startOffsetMs:i,endOffsetMs:a,startAt:new Date(t+i).toISOString(),endAt:new Date(t+a).toISOString(),missedDeadlineFrameCount:e.length,worstFrameMs:d(Math.max(...e.map(e=>e.durationNs))/1e6)}}function ke(e,t){return U(e,t).rows}function U(e,t){let n=l(e),r=x(n,t);return{rows:r.length===0?[]:b(n,e=>e.name===`row`),schema:r}}function Ae(e,t){let n=C(e,t);return n===null?null:n!==0}const W=`ps-process-snapshot`,G=`xctrace-activity-monitor`,K=`leaks-output-graph`,q=12e4;async function je(t,r){if(n(t)&&t.kind===`device`)return await Ve(t,r);let{readAppleProcessSamples:i,resolveAppleExecutable:a}=await import(`./perf-target.js`),o=await a(t,r),s=await i(t,o);if(s.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${r}`,{appBundleId:r,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});let c=new Date().toISOString();return $({residentMemoryKb:s.reduce((e,t)=>e+t.rssKb,0),measuredAt:c,matchedProcesses:[o.executableName],memoryMethod:W})}async function Me(t,n,r){let i=Y(t);if(!i.memgraph)return{available:!1,kind:`memgraph`,reason:i.reason,hint:i.hint,support:i};let a=await Ge(t,n,i);if(a.available===!1)return a;let{process:o}=a;await m(_.dirname(r));let s=await Fe(r),l;try{l=await Ne(t,r,o.pid)}catch(e){throw await J(r,s),Pe(t,n,o,r,e)}if(l.exitCode!==0)throw await J(r,s),new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,c(l,{kind:`memgraph`,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),path:r,hint:Q(t,l.stdout,l.stderr)}));let u=await h(r).catch(()=>null);if(!u?.isFile()||u.size<=0)throw await J(r,s),new e(`COMMAND_FAILED`,`Apple memgraph artifact is missing or empty`,{kind:`memgraph`,appBundleId:n,pid:o.pid,path:r,hint:`Retry with a writable --out path. If the file is still empty, run with --debug and inspect leaks output.`});return{available:!0,kind:`memgraph`,path:r,sizeBytes:u.size,measuredAt:new Date().toISOString(),method:K,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),support:i}}async function Ne(e,t,n){return r(e)?await ae(`leaks`,[`--outputGraph=${t}`,String(n)],{allowFailure:!0,timeoutMs:q}):await g(ce(e,[`spawn`,e.id,`leaks`,`--outputGraph=${t}`,String(n)]),{allowFailure:!0,timeoutMs:q})}function Pe(t,n,r,i,a){if(a instanceof e){let o=a.details??{};return new e(a.code,`Failed to capture Apple memgraph for ${n}`,{...o,kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:Q(t,typeof o.stdout==`string`?o.stdout:``,typeof o.stderr==`string`&&o.stderr.length>0?o.stderr:a.message)},a)}return new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,{kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:`Retry perf memory snapshot. If it still fails, run with --debug and inspect leaks output.`},a)}async function Fe(e){return await h(e).then(e=>e.isFile()).catch(()=>!1)}async function J(e,t){t||await f(e).catch(()=>{})}async function Ie(r,i){if(!n(r)||r.kind!==`device`)throw new e(`COMMAND_FAILED`,`Apple frame-health sampling is currently available only on connected iOS devices.`,{metric:`fps`,platform:t(r),deviceKind:r.kind});let{resolveIosDevicePerfTarget:o}=await import(`./perf-target.js`),s=await o(r,i),c=await ze(r,i,s);return xe({hitchesXml:c.hitchesXml,frameLifetimesXml:c.frameLifetimesXml,displayInfoXml:c.displayInfoXml,processIds:s.map(e=>e.pid),processNames:a(s.map(e=>_.basename(v(e.executable)))),windowStartedAt:c.windowStartedAt,windowEndedAt:c.windowEndedAt,measuredAt:c.windowEndedAt})}function Le(e){return n(e)&&e.kind===`device`?{method:V,description:`Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`short 2s xctrace Animation Hitches record of the active app process`,resetsAfterRead:!1}:{method:V,description:`Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.`,unit:`percent`,primaryField:`droppedFramePercent`}}function Re(e){if(n(e)&&e.kind===`device`)return{method:G,description:`Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.`,unit:`kB`};let t=r(e)?`host ps for the running macOS app executable resolved from the bundle ID.`:`xcrun simctl spawn ps, with host ps fallback, for the running iOS simulator app executable resolved from the bundle ID.`;return{method:W,description:`Resident memory snapshot from ${t}`,unit:`kB`}}function Y(e){return n(e)&&e.kind===`device`?{platform:t(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Physical iOS device memgraph capture is not exposed through reliable local agent-device tooling.`,hint:`Use perf memory sample for a compact resident-memory reading, or reproduce on an iOS simulator/macOS target for memgraph capture.`}:n(e)&&e.kind===`simulator`?{platform:t(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`iOS simulator processes are host-visible through simctl spawn leaks.`,hint:`Keep the simulator app running in the foreground while the memgraph is captured.`}:r(e)?{platform:t(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`macOS app processes are host-visible to leaks --outputGraph.`,hint:`Grant Terminal/agent process permissions if macOS denies process inspection.`}:{platform:t(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Apple memgraph capture is available only for iOS simulator and macOS app sessions.`,hint:`Use perf memory sample on supported app sessions, or rerun against iOS simulator/macOS for memgraph capture.`}}async function ze(e,t,n){let r=await p(`agent-device-ios-frame-perf-`),i=_.join(r,`animation-hitches.trace`);try{let a=await M({device:e,appBundleId:t,tracePath:i,template:`Animation Hitches`,timeLimit:`2s`,target:n.map(e=>e.pid),requireTraceData:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`}),o={device:e,appBundleId:t,tracePath:i,tempDir:r};return{windowStartedAt:a.startedAt,windowEndedAt:a.endedAt,hitchesXml:await X(o,`hitches`),frameLifetimesXml:await X(o,`hitches-frame-lifetimes`),displayInfoXml:await X(o,`device-display-info`).catch(()=>void 0)}}finally{await f(r).catch(()=>{})}}async function X(e,t){return await N({tracePath:e.tracePath,outPath:_.join(e.tempDir,`${t}.xml`),query:{schema:t},failureMessage:`Failed to export iOS device ${t} data`,failureDetails:{appBundleId:e.appBundleId,deviceId:e.device.id}})}async function Be(t){let n=l(t),r=x(n,`activity-monitor-process-live`);if(r.length===0)throw new e(`COMMAND_FAILED`,`Failed to parse xctrace activity-monitor-process-live schema`);let i=r.indexOf(`pid`),a=r.indexOf(`process`),o=r.indexOf(`memory-real`);if(i<0||a<0||o<0)throw new e(`COMMAND_FAILED`,`xctrace activity-monitor-process-live export is missing expected columns`);let s=b(n,e=>e.name===`row`),c=[],u=new Map;for(let e of s){let t=e.children;if(t.length===0)continue;w(t,u);let n=C(t[i],u),r=T(t[a],u)?.name;n===null||!Number.isFinite(n)||!r||c.push({pid:n,processName:r,residentMemoryBytes:C(t[o],u)})}return c}async function Ve(t,n){let{resolveIosDevicePerfTarget:r}=await import(`./perf-target.js`),i=await r(t,n),a=await He(t,n),o=Ue(await Be(a.xml),i,n,t);if(o.residentMemoryBytes===null)throw new e(`COMMAND_FAILED`,`Incomplete Activity Monitor sample for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});return $({residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,memoryMethod:G})}async function He(e,t){let n=await p(`agent-device-ios-perf-`),r=_.join(n,`sample.trace`);try{return{capturedAtMs:(await M({device:e,appBundleId:t,tracePath:r,template:`Activity Monitor`,timeLimit:`1s`,target:`all-processes`,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`})).capturedAtMs,xml:await X({device:e,appBundleId:t,tracePath:r,tempDir:n},`activity-monitor-process-live`)}}finally{await f(n).catch(()=>{})}}function Ue(t,n,r,i){let o=new Set(n.map(e=>e.pid)),s=new Set(n.map(e=>_.basename(v(e.executable)))),c=t.filter(e=>o.has(e.pid)||s.has(e.processName));if(c.length===0)throw new e(`COMMAND_FAILED`,`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:i.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});let l=new Map;for(let e of c){let t=l.get(e.pid);if(!t){l.set(e.pid,e);continue}l.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,residentMemoryBytes:qe(t.residentMemoryBytes,e.residentMemoryBytes)})}let u=[...l.values()],d=u.map(e=>e.residentMemoryBytes).filter(e=>e!==null);return{residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:a(u.map(e=>e.processName))}}function Z(e){let[t=``]=e.trim().split(/\s+/,1);return t}async function We(t,n,r){let{readAppleProcessSamples:i}=await import(`./perf-target.js`),a=(await i(t,r)).sort((e,t)=>t.rssKb-e.rssKb)[0];if(a)return a;throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{kind:`memgraph`,appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf memory snapshot.`})}async function Ge(e,t,n){try{let{resolveAppleExecutable:n}=await import(`./perf-target.js`);return{available:!0,process:await We(e,t,await n(e,t))}}catch(t){if(Ke(e,t))return{available:!1,kind:`memgraph`,reason:`iOS simulator memgraph capture needs process tools inside simctl spawn, but this simulator runtime did not provide ps.`,hint:`Use perf memory sample when available, or retry memgraph on a simulator runtime that includes process tools such as ps and leaks.`,support:{...n,memgraph:!1}};throw t}}function Ke(t,r){if(!n(t)||t.kind!==`simulator`||!(r instanceof e))return!1;let i=r.details??{},a=Array.isArray(i.args)?i.args.join(` `):``,o=typeof i.stderr==`string`?i.stderr:``,s=`${r.message}\n${o}`.toLowerCase();return a.includes(`simctl spawn`)&&a.includes(` ps `)&&s.includes(`no such file`)}function Q(e,t,n){let i=`${t}\n${n}`.toLowerCase();return i.includes(`timed out`)||i.includes(`timeout`)?`Apple memgraph capture can take longer than metric sampling. Keep the app running and retry; if it times out again, collect a smaller reproduction before capturing leaks --outputGraph.`:i.includes(`not found`)||i.includes(`no such file`)?`Install Xcode command line tools and ensure leaks is available, then retry.`:i.includes(`permission`)||i.includes(`denied`)||i.includes(`not authorized`)?r(e)?`Grant the agent terminal process permission to inspect this macOS app, then retry.`:`Keep the simulator booted and app running; if inspection is denied, retry with a debug simulator build.`:`Keep the app process running and retry perf memory snapshot with --debug if the failure persists.`}function $(e){return{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}function qe(e,t){return e===null?t:t===null?e:Math.max(e,t)}export{Le as buildAppleFrameSamplingMetadata,Re as buildAppleMemorySamplingMetadata,Y as buildAppleMemorySnapshotSupport,Me as captureAppleMemorySnapshot,he as cleanupAppleXctracePerfCapture,I as isRetryableIosDeviceTraceRecordFailure,B as resolveIosDevicePerfHint,Ie as sampleAppleFramePerf,je as sampleAppleMemoryPerf,pe as startAppleXctracePerfCapture,me as stopAppleXctracePerfCapture,ge as writeAppleXctracePerfReport};
@@ -1 +1 @@
1
- import{D as e,L as t}from"./sdk-contracts.js";async function n(e){try{return{available:!0,...await e}}catch(e){let n=t(e);return{available:!1,reason:n.message,error:n}}}function r(e,t){return{available:!1,reason:`No ${e} app ${t} is associated with this session. Run open <app> first.`}}function i(e,t,n,r){return{artifact:{available:!1,kind:t,reason:`${e} perf memory snapshot does not support ${t}.`,hint:r,support:n},support:n}}function a(){return new e(`INVALID_ARGS`,`perf memory snapshot requires an active app session`,{hint:`Run open <app> first so perf memory snapshot can resolve the app process.`})}function o(t){return Object.freeze({perfNativeCaptureStart:t.start,perfNativeCaptureReattach:t.reattach,perfNativeCaptureCleanup:t.cleanup,perfProfileReport:async n=>{if(n.kind!==t.expectedProfileKind)throw new e(`INVALID_ARGS`,`${t.platform} native perf requires --kind ${t.expectedProfileKind}, not ${n.kind}`);return await t.writeProfileReport(n)}})}export{i as a,n as i,r as n,a as r,o as t};
1
+ import{A as e,B as t}from"./sdk-contracts.js";async function n(e){try{return{available:!0,...await e}}catch(e){let n=t(e);return{available:!1,reason:n.message,error:n}}}function r(e,t){return{available:!1,reason:`No ${e} app ${t} is associated with this session. Run open <app> first.`}}function i(e,t,n,r){return{artifact:{available:!1,kind:t,reason:`${e} perf memory snapshot does not support ${t}.`,hint:r,support:n},support:n}}function a(){return new e(`INVALID_ARGS`,`perf memory snapshot requires an active app session`,{hint:`Run open <app> first so perf memory snapshot can resolve the app process.`})}function o(t){return Object.freeze({perfNativeCaptureStart:t.start,perfNativeCaptureReattach:t.reattach,perfNativeCaptureCleanup:t.cleanup,perfProfileReport:async n=>{if(n.kind!==t.expectedProfileKind)throw new e(`INVALID_ARGS`,`${t.platform} native perf requires --kind ${t.expectedProfileKind}, not ${n.kind}`);return await t.writeProfileReport(n)}})}export{i as a,n as i,r as n,a as r,o as t};
@@ -1 +1 @@
1
- import{D as e,L as t}from"./sdk-contracts.js";import{D as n,l as r,w as i}from"./sdk-device.js";import{Dt as a,Mt as o,Ot as s,jt as c,kt as l}from"./sdk-batch.js";import{m as u}from"./observability.js";import{r as d}from"./diagnostics.js";import{D as ee,a as f,i as p}from"./owner-identity.js";import{n as te,t as m}from"./file.js";import"./diagnostics2.js";import"./process.js";import{c as h,i as ne,l as g,r as _,s as v,t as y,u as b}from"./device-claim-inspection.js";import{l as x,u as S}from"./screen-recording-resource-recovery.js";import C from"node:path";import w from"node:fs";import re from"node:crypto";async function T(e){let t=await e.observeDeviceBoot?.observeBootTimeMs(e.device);if(t?.observed!==!0||t.bootedAtMs<=e.claim.updatedAtMs)return;let{session:n,workspace:r,stateDir:i}=e.claim;return{session:n,workspace:r,stateDir:i,bootedAtMs:t.bootedAtMs}}function E(e){d({level:`info`,phase:`device_claim_reboot_released`,data:{deviceKey:e.deviceKey,ownerSession:e.claim.session,ownerStateDir:e.claim.stateDir,ownerWorkspace:e.claim.workspace,claimUpdatedAtMs:e.claim.updatedAtMs,deviceBootedAtMs:e.bootedAtMs}})}function D(e){let t=g(e.deviceKey);w.mkdirSync(C.dirname(t),{recursive:!0,mode:448}),ee({destination:t,contents:`${JSON.stringify(e)}\n`,mode:384})}async function O(e,t){let n=f();return await te({acquire:()=>m({lockDirPath:`${g(e)}.lock`,owner:{pid:n.pid,startTime:n.startTime,acquiredAtMs:Date.now()},timeoutMs:3e4,description:`device claim for ${e}`}),task:t})}async function ie(e){let t=_(g(e.deviceKey));return t?t.claim&&M(t.claim,e.stateDir,e.owner)?(I(e.deviceKey,t.claim),{status:`available`}):t.claim&&N(t.claim,e,e.owner)?{status:`held`,ownership:ae(t.claim)}:await oe(t,e):{status:`available`}}function ae(e){if(e.updatedAtMs>=Date.now())return v(e);let t={...e,updatedAtMs:Date.now()};return D(t),v(t)}async function oe(e,t){let n=e.claim;if(!n)return P(t.deviceKey,e),{status:`conflict`,conflict:e};let r=await se({classification:e.classification,claim:n,device:t.device,observeDeviceBoot:t.observeDeviceBoot});if(!r.settles)return P(t.deviceKey,e),{status:`conflict`,conflict:e};let i=await k(n,t.reconcileOrphanedDeviceClaim);return i.status===`retained`?(P(t.deviceKey,e,i.reason),{status:`conflict`,conflict:e}):r.tookOver?(E({deviceKey:t.deviceKey,claim:n,bootedAtMs:r.tookOver.bootedAtMs}),{status:`available`,tookOver:r.tookOver}):{status:`available`}}async function se(e){if(y(e.classification))return{settles:!0};let t=await T(e);return t?{settles:!0,tookOver:t}:{settles:!1}}async function k(e,t){let n=await t(e);if(n.status===`retained`)return n;try{w.unlinkSync(g(e.deviceKey))}catch(e){if(e.code!==`ENOENT`)throw e}return{status:`reconciled`}}function A(e,t,n){return e.stateDir===t&&p({pid:e.ownerPid,startTime:e.ownerStartTime},n)}function j(e){return e.abandonedAtMs!==void 0}function M(e,t,n){return j(e)&&A(e,t,n)}function N(e,t,n){return e.session===t.session&&e.workspace===t.workspace&&A(e,t.stateDir,n)}function P(e,t,n){d({level:`warn`,phase:`device_claim_conflict`,data:{deviceKey:e,classification:t.classification,...F(t),...n?{reconciliationReason:n}:{}}})}function F(e){return e.allocatorClaim?{ownerStateDir:e.allocatorClaim.stateDir,allocatorInstanceId:e.allocatorClaim.allocator.instanceId,identityIncarnationId:e.allocatorClaim.allocator.identityIncarnationId}:{ownerSession:e.claim?.session,ownerStateDir:e.claim?.stateDir}}function I(e,t){d({level:`info`,phase:`device_claim_abandoned_superseded`,data:{deviceKey:e,abandonedSession:t.session,abandonedAtMs:t.abandonedAtMs}})}function L(e){return`transient:${e}`}async function R(e){let t=H(e.device),n=h(t);return await O(n,async()=>await B({...e,deviceKey:n,identity:t}))}async function z(e){let t=H(e.device),n=h(t);return await O(n,async()=>{let r=_(g(n));return r?.claim&&!j(r.claim)&&A(r.claim,e.stateDir,f())?{status:`covered-by-owned-claim`}:await B({device:e.device,deviceKey:n,identity:t,session:L(e.command),workspace:e.workspace,stateDir:e.stateDir,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim})})}async function B(e){let{deviceKey:t,identity:n}=e,r=f(),i=await ie({...e,owner:r});if(i.status===`conflict`)return i;if(i.status===`held`)return{status:`acquired`,ownership:i.ownership};let a=Date.now(),o={schemaVersion:2,deviceKey:t,device:{...n,name:e.device.name},session:e.session,workspace:e.workspace,stateDir:e.stateDir,ownerPid:r.pid,ownerStartTime:r.startTime,ownerToken:re.randomUUID(),createdAtMs:a,updatedAtMs:a};return D(o),{status:`acquired`,ownership:v(o),...i.tookOver?{tookOver:i.tookOver}:{}}}function V(e){let t=h(H(e)),n=_(g(t))?.claim;return n!==void 0&&n.deviceKey===t&&!j(n)&&p({pid:n.ownerPid,startTime:n.ownerStartTime},f())}function H(e){return n({...e,...r(e.platform)?{appleOs:i(e)}:{}})}async function U(e){let t=[];for(let n of ne(e.selectors))t.push(await W(n,e.reconcile));return t}async function W(e,t){let n=e.claim,r={fileName:e.fileName,classification:e.classification,...e.deviceKey?{deviceKey:e.deviceKey}:{},...n?{device:n.device,session:n.session,workspace:n.workspace,stateDir:n.stateDir}:{},...e.allocatorClaim?{device:e.allocatorClaim.device,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}:{}};if(!n||!y(e.classification))return{...r,status:`refused`,reason:K(e.classification)};if(g(n.deviceKey)!==C.join(b(),e.fileName))return{...r,status:`refused`,reason:`claim-file-name-mismatch`};let{deviceKey:i,ownerToken:a}=n;return await O(i,async()=>{let e=_(g(i));if(!e?.claim||e.claim.ownerToken!==a||!y(e.classification))return{...r,status:`changed`,reason:`claim-changed-during-release`};let o=await k(e.claim,t);return o.status===`retained`?{...r,status:`retained`,reason:o.reason}:(d({level:`info`,phase:`device_claim_stale_released`,data:{deviceKey:i,ownerSession:n.session,ownerStateDir:n.stateDir}}),{...r,status:`released`})})}const G=Object.freeze({live:`live-owner`,"owner-process-reused":`owner-pid-reused`,"owner-state-dir-gone":`owner-process-still-running`,unknown:`owner-liveness-unknown`,inconsistent:`claim-record-inconsistent`,"allocator-inconsistent":`allocator-claim-record-inconsistent`,"allocator-held":`allocator-held-owner`,"owner-process-dead":`claim-record-unreadable`,"owner-daemon-superseded":`claim-record-unreadable`});function K(e){return G[e]}async function ce(e){return e?await q(e,(e,t)=>{try{w.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)throw e;return`absent`}return`deleted`},e=>e?`ownership-changed`:`absent`):`absent`}async function le(e){return e?await q(e,e=>{let t=Date.now();return D({...e,abandonedAtMs:t,updatedAtMs:t}),`abandoned`},e=>e?`ownership-changed`:`absent`):`absent`}async function ue(e){return e?await q(e,e=>(D({...e,updatedAtMs:Date.now()}),{status:`renewed`}),e=>({status:`lost`,conflict:e})):{status:`lost`,conflict:void 0}}async function q(e,t,n){return await O(e.deviceKey,async()=>{let r=g(e.deviceKey),i=_(r);if(!i)return n(void 0);let a=i.claim;return!a||!de(a,e)?n(i):t(a,r)})}function de(e,t){return e.ownerToken===t.ownerToken&&p({pid:e.ownerPid,startTime:e.ownerStartTime},{pid:t.ownerPid,startTime:t.ownerStartTime})}async function fe(e,t){let n=b(),r;try{r=w.readdirSync(n,{withFileTypes:!0})}catch{return{examined:0,reconciled:0,retained:0,changed:0}}let i=0,a=0,o=0,s=0;for(let c of r){if(!c.isFile()||!c.name.endsWith(`.json`))continue;let r=C.join(n,c.name),l=_(r);if(!l?.claim||!J(l.classification,l.claim.stateDir,t))continue;i+=1;let{deviceKey:u,ownerToken:d}=l.claim;if(g(u)!==r){o+=1;continue}await O(u,async()=>{let n=_(r);if(!n?.claim||!J(n.classification,n.claim.stateDir,t)||n.claim.ownerToken!==d){s+=1;return}if((await k(n.claim,e)).status===`retained`){o+=1;return}a+=1})}return{examined:i,reconciled:a,retained:o,changed:s}}function J(e,t,n){return y(e)?e!==`owner-daemon-superseded`||C.resolve(t)===C.resolve(n):!1}const Y=S({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),X=x({resourceKind:`app-log`,displayName:`app-log`,store:Y,sessionSlot:{read:e=>e.appLog,replace:(e,t)=>({...e,appLog:t,appLogFailure:void 0})},completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}});function pe(e){if(e.appLog){let t=e.appLog.handle.inspect();return{active:t.state===`active`||t.state===`recovering`,...t}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint}:{active:!1,state:`inactive`}}function me(e){return X.adoptStarted(e)}function he(e){return X.finishLive(e)}function ge(e){return X.forceCleanupLive(e)}function _e(e){let n=t(e.error);return e.sessionStore.set(e.sessionName,{...e.session,appLog:void 0,appLogFailure:{backend:e.backend,code:n.code,message:n.message,hint:n.hint}}),n}function ve(e){e.sessionStore.set(e.sessionName,{...e.session,appLogFailure:void 0})}const ye=S({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),Z=x({resourceKind:`audio-probe`,displayName:`audio probe`,store:ye,sessionSlot:{read:e=>e.audioProbe,replace:(e,t)=>({...e,audioProbe:t})},completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function be(e){return Z.adoptStarted(e)}function xe(e){return Z.finishLive(e)}const Q=S({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),$=x({resourceKind:`perf-capture`,displayName:`perf capture`,store:Q,sessionSlot:{read:e=>e.perfCapture,replace:(e,t)=>({...e,perfCapture:t})},completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function Se(e){return $.adoptStarted(e)}function Ce(e){return $.finishLive(e)}function we(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:a});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:l}):Object.freeze({kind:`memory-sample`,request:e,use:s});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:c}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:c});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:o})}}function Te(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return Ee(n,t);if(r===`cpu`)return De(n,t.outPath);if(r===`trace`)return Oe(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function Ee(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!u(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function De(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function Oe(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}export{fe as C,V as S,ue as T,le as _,$ as a,ce as b,xe as c,ve as d,he as f,Y as g,_e as h,Ce as i,me as l,pe as m,we as n,be as o,ge as p,Se as r,Z as s,Te as t,X as u,R as v,U as w,H as x,z as y};
1
+ import{A as e,B as t}from"./sdk-contracts.js";import{D as n,l as r,w as i}from"./sdk-device.js";import{Dt as a,Mt as o,Ot as s,jt as c,kt as l}from"./sdk-batch.js";import{m as u}from"./observability.js";import{r as d}from"./diagnostics.js";import{D as ee,a as f,i as p}from"./owner-identity.js";import{n as te,t as m}from"./file.js";import"./diagnostics2.js";import"./process.js";import{c as h,i as ne,l as g,r as _,s as v,t as y,u as b}from"./device-claim-inspection.js";import{l as x,u as S}from"./screen-recording-resource-recovery.js";import C from"node:path";import w from"node:fs";import re from"node:crypto";async function T(e){let t=await e.observeDeviceBoot?.observeBootTimeMs(e.device);if(t?.observed!==!0||t.bootedAtMs<=e.claim.updatedAtMs)return;let{session:n,workspace:r,stateDir:i}=e.claim;return{session:n,workspace:r,stateDir:i,bootedAtMs:t.bootedAtMs}}function E(e){d({level:`info`,phase:`device_claim_reboot_released`,data:{deviceKey:e.deviceKey,ownerSession:e.claim.session,ownerStateDir:e.claim.stateDir,ownerWorkspace:e.claim.workspace,claimUpdatedAtMs:e.claim.updatedAtMs,deviceBootedAtMs:e.bootedAtMs}})}function D(e){let t=g(e.deviceKey);w.mkdirSync(C.dirname(t),{recursive:!0,mode:448}),ee({destination:t,contents:`${JSON.stringify(e)}\n`,mode:384})}async function O(e,t){let n=f();return await te({acquire:()=>m({lockDirPath:`${g(e)}.lock`,owner:{pid:n.pid,startTime:n.startTime,acquiredAtMs:Date.now()},timeoutMs:3e4,description:`device claim for ${e}`}),task:t})}async function ie(e){let t=_(g(e.deviceKey));return t?t.claim&&M(t.claim,e.stateDir,e.owner)?(I(e.deviceKey,t.claim),{status:`available`}):t.claim&&N(t.claim,e,e.owner)?{status:`held`,ownership:ae(t.claim)}:await oe(t,e):{status:`available`}}function ae(e){if(e.updatedAtMs>=Date.now())return v(e);let t={...e,updatedAtMs:Date.now()};return D(t),v(t)}async function oe(e,t){let n=e.claim;if(!n)return P(t.deviceKey,e),{status:`conflict`,conflict:e};let r=await se({classification:e.classification,claim:n,device:t.device,observeDeviceBoot:t.observeDeviceBoot});if(!r.settles)return P(t.deviceKey,e),{status:`conflict`,conflict:e};let i=await k(n,t.reconcileOrphanedDeviceClaim);return i.status===`retained`?(P(t.deviceKey,e,i.reason),{status:`conflict`,conflict:e}):r.tookOver?(E({deviceKey:t.deviceKey,claim:n,bootedAtMs:r.tookOver.bootedAtMs}),{status:`available`,tookOver:r.tookOver}):{status:`available`}}async function se(e){if(y(e.classification))return{settles:!0};let t=await T(e);return t?{settles:!0,tookOver:t}:{settles:!1}}async function k(e,t){let n=await t(e);if(n.status===`retained`)return n;try{w.unlinkSync(g(e.deviceKey))}catch(e){if(e.code!==`ENOENT`)throw e}return{status:`reconciled`}}function A(e,t,n){return e.stateDir===t&&p({pid:e.ownerPid,startTime:e.ownerStartTime},n)}function j(e){return e.abandonedAtMs!==void 0}function M(e,t,n){return j(e)&&A(e,t,n)}function N(e,t,n){return e.session===t.session&&e.workspace===t.workspace&&A(e,t.stateDir,n)}function P(e,t,n){d({level:`warn`,phase:`device_claim_conflict`,data:{deviceKey:e,classification:t.classification,...F(t),...n?{reconciliationReason:n}:{}}})}function F(e){return e.allocatorClaim?{ownerStateDir:e.allocatorClaim.stateDir,allocatorInstanceId:e.allocatorClaim.allocator.instanceId,identityIncarnationId:e.allocatorClaim.allocator.identityIncarnationId}:{ownerSession:e.claim?.session,ownerStateDir:e.claim?.stateDir}}function I(e,t){d({level:`info`,phase:`device_claim_abandoned_superseded`,data:{deviceKey:e,abandonedSession:t.session,abandonedAtMs:t.abandonedAtMs}})}function L(e){return`transient:${e}`}async function R(e){let t=H(e.device),n=h(t);return await O(n,async()=>await B({...e,deviceKey:n,identity:t}))}async function z(e){let t=H(e.device),n=h(t);return await O(n,async()=>{let r=_(g(n));return r?.claim&&!j(r.claim)&&A(r.claim,e.stateDir,f())?{status:`covered-by-owned-claim`}:await B({device:e.device,deviceKey:n,identity:t,session:L(e.command),workspace:e.workspace,stateDir:e.stateDir,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim})})}async function B(e){let{deviceKey:t,identity:n}=e,r=f(),i=await ie({...e,owner:r});if(i.status===`conflict`)return i;if(i.status===`held`)return{status:`acquired`,ownership:i.ownership};let a=Date.now(),o={schemaVersion:2,deviceKey:t,device:{...n,name:e.device.name},session:e.session,workspace:e.workspace,stateDir:e.stateDir,ownerPid:r.pid,ownerStartTime:r.startTime,ownerToken:re.randomUUID(),createdAtMs:a,updatedAtMs:a};return D(o),{status:`acquired`,ownership:v(o),...i.tookOver?{tookOver:i.tookOver}:{}}}function V(e){let t=h(H(e)),n=_(g(t))?.claim;return n!==void 0&&n.deviceKey===t&&!j(n)&&p({pid:n.ownerPid,startTime:n.ownerStartTime},f())}function H(e){return n({...e,...r(e.platform)?{appleOs:i(e)}:{}})}async function U(e){let t=[];for(let n of ne(e.selectors))t.push(await W(n,e.reconcile));return t}async function W(e,t){let n=e.claim,r={fileName:e.fileName,classification:e.classification,...e.deviceKey?{deviceKey:e.deviceKey}:{},...n?{device:n.device,session:n.session,workspace:n.workspace,stateDir:n.stateDir}:{},...e.allocatorClaim?{device:e.allocatorClaim.device,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}:{}};if(!n||!y(e.classification))return{...r,status:`refused`,reason:K(e.classification)};if(g(n.deviceKey)!==C.join(b(),e.fileName))return{...r,status:`refused`,reason:`claim-file-name-mismatch`};let{deviceKey:i,ownerToken:a}=n;return await O(i,async()=>{let e=_(g(i));if(!e?.claim||e.claim.ownerToken!==a||!y(e.classification))return{...r,status:`changed`,reason:`claim-changed-during-release`};let o=await k(e.claim,t);return o.status===`retained`?{...r,status:`retained`,reason:o.reason}:(d({level:`info`,phase:`device_claim_stale_released`,data:{deviceKey:i,ownerSession:n.session,ownerStateDir:n.stateDir}}),{...r,status:`released`})})}const G=Object.freeze({live:`live-owner`,"owner-process-reused":`owner-pid-reused`,"owner-state-dir-gone":`owner-process-still-running`,unknown:`owner-liveness-unknown`,inconsistent:`claim-record-inconsistent`,"allocator-inconsistent":`allocator-claim-record-inconsistent`,"allocator-held":`allocator-held-owner`,"owner-process-dead":`claim-record-unreadable`,"owner-daemon-superseded":`claim-record-unreadable`});function K(e){return G[e]}async function ce(e){return e?await q(e,(e,t)=>{try{w.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)throw e;return`absent`}return`deleted`},e=>e?`ownership-changed`:`absent`):`absent`}async function le(e){return e?await q(e,e=>{let t=Date.now();return D({...e,abandonedAtMs:t,updatedAtMs:t}),`abandoned`},e=>e?`ownership-changed`:`absent`):`absent`}async function ue(e){return e?await q(e,e=>(D({...e,updatedAtMs:Date.now()}),{status:`renewed`}),e=>({status:`lost`,conflict:e})):{status:`lost`,conflict:void 0}}async function q(e,t,n){return await O(e.deviceKey,async()=>{let r=g(e.deviceKey),i=_(r);if(!i)return n(void 0);let a=i.claim;return!a||!de(a,e)?n(i):t(a,r)})}function de(e,t){return e.ownerToken===t.ownerToken&&p({pid:e.ownerPid,startTime:e.ownerStartTime},{pid:t.ownerPid,startTime:t.ownerStartTime})}async function fe(e,t){let n=b(),r;try{r=w.readdirSync(n,{withFileTypes:!0})}catch{return{examined:0,reconciled:0,retained:0,changed:0}}let i=0,a=0,o=0,s=0;for(let c of r){if(!c.isFile()||!c.name.endsWith(`.json`))continue;let r=C.join(n,c.name),l=_(r);if(!l?.claim||!J(l.classification,l.claim.stateDir,t))continue;i+=1;let{deviceKey:u,ownerToken:d}=l.claim;if(g(u)!==r){o+=1;continue}await O(u,async()=>{let n=_(r);if(!n?.claim||!J(n.classification,n.claim.stateDir,t)||n.claim.ownerToken!==d){s+=1;return}if((await k(n.claim,e)).status===`retained`){o+=1;return}a+=1})}return{examined:i,reconciled:a,retained:o,changed:s}}function J(e,t,n){return y(e)?e!==`owner-daemon-superseded`||C.resolve(t)===C.resolve(n):!1}const Y=S({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),X=x({resourceKind:`app-log`,displayName:`app-log`,store:Y,sessionSlot:{read:e=>e.appLog,replace:(e,t)=>({...e,appLog:t,appLogFailure:void 0})},completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}});function pe(e){if(e.appLog){let t=e.appLog.handle.inspect();return{active:t.state===`active`||t.state===`recovering`,...t}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint}:{active:!1,state:`inactive`}}function me(e){return X.adoptStarted(e)}function he(e){return X.finishLive(e)}function ge(e){return X.forceCleanupLive(e)}function _e(e){let n=t(e.error);return e.sessionStore.set(e.sessionName,{...e.session,appLog:void 0,appLogFailure:{backend:e.backend,code:n.code,message:n.message,hint:n.hint}}),n}function ve(e){e.sessionStore.set(e.sessionName,{...e.session,appLogFailure:void 0})}const ye=S({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),Z=x({resourceKind:`audio-probe`,displayName:`audio probe`,store:ye,sessionSlot:{read:e=>e.audioProbe,replace:(e,t)=>({...e,audioProbe:t})},completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function be(e){return Z.adoptStarted(e)}function xe(e){return Z.finishLive(e)}const Q=S({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),$=x({resourceKind:`perf-capture`,displayName:`perf capture`,store:Q,sessionSlot:{read:e=>e.perfCapture,replace:(e,t)=>({...e,perfCapture:t})},completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function Se(e){return $.adoptStarted(e)}function Ce(e){return $.finishLive(e)}function we(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:a});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:l}):Object.freeze({kind:`memory-sample`,request:e,use:s});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:c}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:c});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:o})}}function Te(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return Ee(n,t);if(r===`cpu`)return De(n,t.outPath);if(r===`trace`)return Oe(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function Ee(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!u(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function De(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function Oe(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}export{fe as C,V as S,ue as T,le as _,$ as a,ce as b,xe as c,ve as d,he as f,Y as g,_e as h,Ce as i,me as l,pe as m,we as n,be as o,ge as p,Se as r,Z as s,Te as t,X as u,R as v,U as w,H as x,z as y};
@@ -1,2 +1,2 @@
1
- import{D as e}from"./sdk-contracts.js";import{O as t}from"./sdk-batch-runner.js";import{f as n}from"./sdk-device.js";import{a as r}from"./exec.js";import"./command.js";import{a as i,o as a}from"./tool-provider.js";import{t as o}from"./physical-device-control.js";import{n as s}from"./simctl.js";import{t as c}from"./plist.js";import l from"node:path";import{fileURLToPath as u}from"node:url";const d=15e3;function f(e){let n=[];for(let r of t(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[t,i,a,o]=e.slice(1);if(t===void 0||i===void 0||a===void 0||o===void 0)continue;let s=Number(t),c=Number(i),l=Number(a),u=o.trim();!Number.isFinite(s)||!Number.isFinite(c)||!Number.isFinite(l)||n.push({pid:s,cpuPercent:c,rssKb:l,command:u})}return n}async function p(t,r){let i=n(t)?await h(r):await g(t,r),a=n(t)?l.join(i,`Contents`,`Info.plist`):l.join(i,`Info.plist`),o=await c(a,`CFBundleExecutable`);if(!o)throw new e(`COMMAND_FAILED`,`Failed to resolve executable for ${r}`,{appBundleId:r,appPath:i});return{executableName:o,executablePath:n(t)?l.join(i,`Contents`,`MacOS`,o):l.join(i,o)}}async function m(t,n){let{appBundleUrl:r,processes:i}=await o(t).resolveAppProcesses(t,n),a=u(r);if(i.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,deviceId:t.id,appBundlePath:a,hint:`Run open <app> for this session again to ensure the iOS app is active, then retry perf.`});return i}async function h(t){let n=`kMDItemCFBundleIdentifier == "${t.replaceAll(`"`,String.raw`\"`)}"`,a=r(await i(`mdfind`,[n],{allowFailure:!0,timeoutMs:d}),`Failed to resolve macOS app bundle for ${t}`,{appBundleId:t}).stdout.split(`
2
- `).map(e=>e.trim()).find(e=>e.endsWith(`.app`));if(!a)throw new e(`APP_NOT_INSTALLED`,`No macOS app found for ${t}`,{appBundleId:t});return a}async function g(t,n){let i=s(t,[`get_app_container`,t.id,n,`app`]),o=r(await a(i,{allowFailure:!0,timeoutMs:d}),`Failed to resolve iOS simulator app container for ${n}`,{appBundleId:n,hint:`Ensure the iOS simulator app is installed and booted, then retry perf.`}).stdout.trim();if(o.length===0)throw new e(`APP_NOT_INSTALLED`,`No iOS simulator app container found for ${n}`,{appBundleId:n});return o}async function _(e,t){let r=n(e)?[`-axo`,`pid=,%cpu=,rss=,command=`]:s(e,[`spawn`,e.id,`ps`,`-axo`,`pid=,%cpu=,rss=,command=`]),a=n(e)?await i(`ps`,r,{timeoutMs:d}):await v(r),{matchesAppleExecutableProcess:o}=await import(`./perf-process-identity.js`);return f(a.stdout).filter(e=>o(e.command,t))}async function v(e){let t=await a(e,{allowFailure:!0,timeoutMs:d});return t.exitCode===0?t:await i(`ps`,[`-axo`,`pid=,%cpu=,rss=,command=`],{timeoutMs:d})}export{_ as readAppleProcessSamples,p as resolveAppleExecutable,m as resolveIosDevicePerfTarget};
1
+ import{A as e}from"./sdk-contracts.js";import{O as t}from"./sdk-batch-runner.js";import{f as n}from"./sdk-device.js";import{a as r}from"./exec.js";import"./command.js";import{a as i,o as a}from"./tool-provider.js";import{t as o}from"./physical-device-control.js";import{n as s}from"./simctl.js";import{t as c}from"./plist.js";import l from"node:path";import{fileURLToPath as u}from"node:url";const d=15e3;function f(e){let n=[];for(let r of t(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[t,i,a,o]=e.slice(1);if(t===void 0||i===void 0||a===void 0||o===void 0)continue;let s=Number(t),c=Number(i),l=Number(a),u=o.trim();!Number.isFinite(s)||!Number.isFinite(c)||!Number.isFinite(l)||n.push({pid:s,cpuPercent:c,rssKb:l,command:u})}return n}async function p(t,r){let i=n(t)?await h(r):await g(t,r),a=n(t)?l.join(i,`Contents`,`Info.plist`):l.join(i,`Info.plist`),o=await c(a,`CFBundleExecutable`);if(!o)throw new e(`COMMAND_FAILED`,`Failed to resolve executable for ${r}`,{appBundleId:r,appPath:i});return{executableName:o,executablePath:n(t)?l.join(i,`Contents`,`MacOS`,o):l.join(i,o)}}async function m(t,n){let{appBundleUrl:r,processes:i}=await o(t).resolveAppProcesses(t,n),a=u(r);if(i.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,deviceId:t.id,appBundlePath:a,hint:`Run open <app> for this session again to ensure the iOS app is active, then retry perf.`});return i}async function h(t){let n=`kMDItemCFBundleIdentifier == "${t.replaceAll(`"`,String.raw`\"`)}"`,a=r(await i(`mdfind`,[n],{allowFailure:!0,timeoutMs:d}),`Failed to resolve macOS app bundle for ${t}`,{appBundleId:t}).stdout.split(`
2
+ `).map(e=>e.trim()).find(e=>e.endsWith(`.app`));if(!a)throw new e(`APP_NOT_INSTALLED`,`No macOS app found for ${t}`,{appBundleId:t});return a}async function g(t,n){let i=s(t,[`get_app_container`,t.id,n,`app`]),o=r(await a(i,{allowFailure:!0,timeoutMs:d}),`Failed to resolve iOS simulator app container for ${n}`,{appBundleId:n,hint:`Ensure the iOS simulator app is installed and booted, then retry perf.`}).stdout.trim();if(o.length===0)throw new e(`APP_NOT_INSTALLED`,`No iOS simulator app container found for ${n}`,{appBundleId:n});return o}async function _(e,t){let r=n(e)?await i(`ps`,[`-axo`,`pid=,%cpu=,rss=,command=`],{timeoutMs:d}):await v(s(e,[`spawn`,e.id,`ps`,`-axo`,`pid=,%cpu=,rss=,command=`])),{matchesAppleExecutableProcess:a}=await import(`./perf-process-identity.js`);return f(r.stdout).filter(e=>a(e.command,t))}async function v(e){let t=await a(e,{allowFailure:!0,timeoutMs:d});return t.exitCode===0?t:await i(`ps`,[`-axo`,`pid=,%cpu=,rss=,command=`],{timeoutMs:d})}export{_ as readAppleProcessSamples,p as resolveAppleExecutable,m as resolveIosDevicePerfTarget};
package/dist/src/perf.js CHANGED
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{runHarmonyShell as t}from"./hdc.js";function n(e){let t=e.trim().split(/\s+/)[0];if(!t||!/^\d+$/.test(t))return;let n=Number.parseInt(t,10);return n>0?n:void 0}function r(e){let t=o(e,`VmRSS`);if(t===void 0)return;let n=o(e,`VmHWM`);return{totalRssKb:t,...n===void 0?{}:{peakRssKb:n}}}async function i(n,i){let o=await a(n,i),s=r((await t(n,[`cat`,`/proc/${o}/status`],{timeoutMs:15e3})).stdout);if(!s)throw new e(`COMMAND_FAILED`,`Could not read resident memory for ${i}`,{hint:`Verify the app is still running, then retry perf memory sample.`,details:{bundleName:i,pid:o}});return{...s,measuredAt:new Date().toISOString(),method:`hdc-shell-proc-status`,pid:o}}async function a(r,i){let a=await t(r,[`pidof`,i],{allowFailure:!0,timeoutMs:15e3}),o=a.exitCode===0?n(a.stdout):void 0;if(o!==void 0)return o;throw new e(`COMMAND_FAILED`,`Could not find a running process for ${i}`,{hint:`Open the app in this session, then retry perf memory sample.`,details:{bundleName:i}})}function o(e,t){let n=e.match(RegExp(`^${t}:\\s+(\\d+)\\s+kB$`,`m`));if(!n?.[1])return;let r=Number.parseInt(n[1],10);return Number.isFinite(r)?r:void 0}export{i as sampleHarmonyMemoryPerf};
1
+ import{A as e}from"./sdk-contracts.js";import{runHarmonyShell as t}from"./hdc.js";function n(e){let t=e.trim().split(/\s+/)[0];if(!t||!/^\d+$/.test(t))return;let n=Number.parseInt(t,10);return n>0?n:void 0}function r(e){let t=o(e,`VmRSS`);if(t===void 0)return;let n=o(e,`VmHWM`);return{totalRssKb:t,...n===void 0?{}:{peakRssKb:n}}}async function i(n,i){let o=await a(n,i),s=r((await t(n,[`cat`,`/proc/${o}/status`],{timeoutMs:15e3})).stdout);if(!s)throw new e(`COMMAND_FAILED`,`Could not read resident memory for ${i}`,{hint:`Verify the app is still running, then retry perf memory sample.`,details:{bundleName:i,pid:o}});return{...s,measuredAt:new Date().toISOString(),method:`hdc-shell-proc-status`,pid:o}}async function a(r,i){let a=await t(r,[`pidof`,i],{allowFailure:!0,timeoutMs:15e3}),o=a.exitCode===0?n(a.stdout):void 0;if(o!==void 0)return o;throw new e(`COMMAND_FAILED`,`Could not find a running process for ${i}`,{hint:`Open the app in this session, then retry perf memory sample.`,details:{bundleName:i}})}function o(e,t){let n=e.match(RegExp(`^${t}:\\s+(\\d+)\\s+kB$`,`m`));if(!n?.[1])return;let r=Number.parseInt(n[1],10);return Number.isFinite(r)?r:void 0}export{i as sampleHarmonyMemoryPerf};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import{n}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as r}from"./retry.js";import{E as i}from"./host-file.js";import{c as a}from"./config.js";import{o}from"./tool-provider.js";import{c as s,n as c,o as l,r as u,s as d,t as f}from"./devicectl.js";import{i as p,n as ee,r as m}from"./physical-device-apps.js";import"./runner.js";import{t as h}from"./runner-cache-metadata.js";const g=1e4;async function _(e,t,n={}){let r=[`device`,`process`,`launch`,`--device`,e.id,t];n.payloadUrl&&r.push(`--payload-url`,n.payloadUrl),n.launchArgs&&n.launchArgs.length>0&&r.push(`--`,...n.launchArgs),await d(r,{action:`launch iOS app`,deviceId:e.id})}async function v(t,r){try{let i=await w(t.id,15e3,3e3,r);if(i.status===`unreadable`)throw new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{kind:`probe_inconclusive`,deviceId:t.id,stdout:i.result.stdout,stderr:i.result.stderr,hint:`CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device.`});if(i.status===`reported`){let n=i.details.tunnelState?.toLowerCase();if(n===`connecting`)throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,{kind:`not_ready`,deviceId:t.id,tunnelState:n,hint:`Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry.`});return}throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,n(i.result,{kind:`not_ready`,deviceId:t.id,tunnelState:i.details.tunnelState,hint:R(i.result.stdout,i.result.stderr)}))}catch(e){throw y(t.id,e)}}function y(t,n){return!(n instanceof e)||n.code!==`COMMAND_FAILED`?x(t,n):(typeof n.details?.kind==`string`?n.details.kind:``)===`not_ready`?n:b(t,n)}function b(t,n){let r=n.details??{},i=String(r.stdout??``),a=String(r.stderr??``),o=Number(r.timeoutMs??15e3),s=`CoreDevice did not respond within ${o}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,cause:n.message,timeoutMs:o,stdout:i,stderr:a,hint:i||a?R(i,a):s},n)}function x(t,n){return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,hint:`Reconnect the device, keep it unlocked, and retry.`},n instanceof Error?n:void 0)}async function S(e,t){return(await C(e,t??g))?.tunnelIp??null}async function C(e,t,n){if(!(t>0))return null;let r=Math.max(1,Math.min(g,t));try{let t=await w(e.id,r,0,n);return t.status!==`reported`||t.details.outcome&&t.details.outcome!==`success`?null:t.details}catch{return null}}async function w(e,t,n=0,r){let i=Math.max(1,Math.ceil(t/1e3)),a=await s({jsonPrefix:`agent-device-coredevice-info`,args:[`devicectl`,`device`,`info`,`details`,`--device`,e,`--timeout`,String(i)],signal:r,timeoutMs:t+n});return a.ok?{status:`reported`,details:O(a.payload)}:a.reason===`unreadable-json`?{status:`unreadable`,result:a.result}:{status:`failed`,result:a.result,details:O(a.payload)}}function T(e){let t=e,n=D(t.device);return{connectionProperties:E(D(t.connectionProperties),D(n?.connectionProperties)),deviceProperties:E(D(t.deviceProperties),D(n?.deviceProperties))}}function E(e,t){if(!e)return t;if(!t)return e;let n={...t};for(let[t,r]of Object.entries(e))r!==void 0&&(n[t]=r);return n}function D(e){return e&&typeof e==`object`?e:void 0}function O(e){let t=D(e?.result);if(!t)return{};let{connectionProperties:n,deviceProperties:r}=T(t);return{...k(`outcome`,A(e?.info?.outcome)),...k(`tunnelState`,A(n?.tunnelState)),...k(`tunnelIp`,A(n?.tunnelIPAddress)),...k(`developerModeStatus`,A(r?.developerModeStatus)),...k(`developerDiskImageServicesAvailable`,j(r?.ddiServicesAvailable)),...k(`bootState`,A(r?.bootState))}}function k(e,t){return t===void 0?{}:{[e]:t}}function A(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function j(e){return typeof e==`boolean`?e:void 0}const M={developerModeOff:u,developerDiskImageUnavailable:c};function N(e){return e.tunnelState===`connected`&&e.bootState===`booted`}function P(e){return`The device reported its developer disk image as unavailable while it was not observable (tunnelState=${e.tunnelState??`unknown`}, bootState=${e.bootState??`unknown`}). Unlock it, keep it connected by cable until \`xcrun devicectl device info details\` reports tunnelState=connected and bootState=booted, then retry.`}async function F(e,t=1e4,n){let r=await C(e,t,n);if(!r)return{available:!1,reason:`device_readiness_unreadable`,hint:"Read the device state directly with `xcrun devicectl device info details --device <id> --json-output -`, keeping the device unlocked and connected by cable, then retry."};let i=I(r.developerModeStatus),a=L(r.developerDiskImageServicesAvailable);return a===`unavailable`&&i!==`disabled`&&!N(r)?{available:!1,reason:`device_readiness_unreadable`,hint:P(r)}:{available:!0,developerMode:i,developerDiskImage:a,remedies:M}}function I(e){let t=e?.toLowerCase();return t===`enabled`?`enabled`:t===`disabled`?`disabled`:`unknown`}function L(e){return e===!0?`available`:e===!1?`unavailable`:`unknown`}function R(e,t){return l(e,t)||(`${e}\n${t}`.toLowerCase().includes(`timed out waiting for all destinations`)?`Xcode destination did not become available in time. Keep device unlocked and retry.`:f)}async function z(t,n,i,s=a){let c=r.fromTimeoutMs(s),l={exitCode:1,stdout:``,stderr:``};for(let e of h)if(l=await o([`devicectl`,`device`,`copy`,`from`,`--device`,t.id,`--source`,n,`--destination`,i,`--domain-type`,`appDataContainer`,`--domain-identifier`,e],{allowFailure:!0,timeoutMs:B(c,s)}),l.exitCode===0)return;let u=l.stderr.trim()||l.stdout.trim()||`devicectl exited with code ${l.exitCode}`;throw new e(`COMMAND_FAILED`,`Failed to copy runner file from iOS device: ${u}`)}function B(t,n){let r=t.remainingMs();if(r>0)return r;throw new e(`COMMAND_FAILED`,`iOS runner file copy timed out after ${n}ms`,{timeoutMs:n,step:`runner file copy`})}function V(t){if(!(t instanceof e))return{reason:t instanceof Error?t.message:String(t)};let n=t.details??{},r=Array.isArray(n.args)?n.args.filter(e=>typeof e==`string`).join(` `):void 0;return{errorCode:t.code,reason:t.message,timeoutMs:typeof n.timeoutMs==`number`?n.timeoutMs:void 0,exitCode:typeof n.exitCode==`number`?n.exitCode:void 0,stderr:typeof n.stderr==`string`&&n.stderr.trim()?n.stderr:void 0,stdout:typeof n.stdout==`string`&&n.stdout.trim()?n.stdout:void 0,commandArgs:r}}function H(e){let t=e.details??{},n=typeof t.stdout==`string`?t.stdout:``,r=typeof t.stderr==`string`?t.stderr:``,i=Array.isArray(t.args)?t.args.filter(e=>typeof e==`string`).join(` `):``;return`${e.message}\n${n}\n${r}\n${i}`.toLowerCase()}async function U(e,t,n){if(!n.preferRunner)try{await d([`device`,`capture`,`screenshot`,`--device`,e.id,`--destination`,t],{action:`capture iOS screenshot`,deviceId:e.id});return}catch(t){if(!Y(t))throw t;J(e,t)}let r=await G(e,n,!1);await K(r,t)||await z(e,q(r),t)}async function W(t,n,r){if(!await K(await G(t,r,!0),n))throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: XCTest runner returned no inline image`,{deviceId:t.id,backend:`xctest`})}async function G(e,t,n){return await t.runRunnerCommand(e,{command:`screenshot`,appBundleId:t.appBundleId,fullscreen:t.fullscreen,inlineScreenshot:n},t.runnerOptions??{})}async function K(e,t){let n=e.imageBase64;return typeof n!=`string`||n.length===0?!1:(await i(t,Buffer.from(n,`base64`)),!0)}function q(t){let n=t.message;if(typeof n==`string`&&n.length>0)return n;throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: runner returned no file path`)}function J(e,n){t({level:`warn`,phase:`ios_screenshot_fallback`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:`devicectl_screenshot`,to:`runner`,...V(n)}})}function Y(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=H(t);return n.includes(`unknown option '--device'`)||n.includes(`unknown subcommand`)&&n.includes(`screenshot`)||n.includes(`unrecognized subcommand`)&&n.includes(`screenshot`)}const X={coredevice:{backend:`coredevice`,ensureReady:v,listApps:ee,launchApp:_,terminateApp:async(e,t)=>await p(e,t),resolveAppProcesses:m,captureScreenshot:U,copyRunnerFile:z,resolveTunnel:async(e,t)=>({tunnelIp:await S(e,t)}),readDeviceReadiness:F},xctest:{backend:`xctest`,ensureReady:ie,listApps:Q,launchApp:ae,terminateApp:oe,resolveAppProcesses:$,captureScreenshot:W,copyRunnerFile:re,resolveTunnel:te,readDeviceReadiness:ne}};function Z(e){return X[e.iosPhysicalDeviceBackend===`xctest`?`xctest`:`coredevice`]}async function Q(t){throw new e(`UNSUPPORTED_OPERATION`,`App inventory is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use an installed app bundle ID when opening the device.`})}async function $(t){throw new e(`UNSUPPORTED_OPERATION`,`Process lookup is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use a CoreDevice-backed iOS device for performance sampling.`})}async function te(t){throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices have no CoreDevice tunnel.`,{deviceId:t.id,backend:`xctest`,hint:`Connect the device by cable so it is reachable through usbmux.`})}async function ne(e){return{available:!1,reason:`device_readiness_unreadable`,hint:`This device is driven through XCTest (device ${e.id}), which does not report Developer Mode or developer disk image state. Check the device's own Settings if development tooling fails to start on it.`}}async function re(t){throw new e(`UNSUPPORTED_OPERATION`,`Runner file copy is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`})}async function ie(t,r){let i=[`xcdevice`,`wait`,`--both`,`--timeout=15`,t.id],a=await o(i,{allowFailure:!0,signal:r,timeoutMs:18e3});if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`iOS device is not ready for XCTest automation`,n(a,{cmd:`xcrun`,args:i,deviceId:t.id,backend:`xctest`,hint:"Keep the device unlocked, trusted, connected, and visible in `xcrun xcdevice list`, then retry."}))}async function ae(t,n,r){if(r.payloadUrl||r.launchArgs&&r.launchArgs.length>0)throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices do not support deep links or launch arguments during open.`,{deviceId:t.id,backend:`xctest`,hint:`Open the installed app by bundle ID without a URL or --launch-args.`});await r.runRunnerCommand(t,{command:`activate`,appBundleId:n},r.runnerOptions??{})}async function oe(e,t,n){await n.runRunnerCommand(e,{command:`terminate`,appBundleId:t},n.runnerOptions??{})}export{H as n,V as r,Z as t};
1
+ import{A as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import{n}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as r}from"./retry.js";import{E as i}from"./host-file.js";import{c as a}from"./config.js";import{o}from"./tool-provider.js";import{c as s,n as c,o as l,r as u,s as d,t as f}from"./devicectl.js";import{i as p,n as ee,r as m}from"./physical-device-apps.js";import"./runner.js";import{t as h}from"./runner-cache-metadata.js";const g=1e4;async function _(e,t,n={}){let r=[`device`,`process`,`launch`,`--device`,e.id,t];n.payloadUrl&&r.push(`--payload-url`,n.payloadUrl),n.launchArgs&&n.launchArgs.length>0&&r.push(`--`,...n.launchArgs),await d(r,{action:`launch iOS app`,deviceId:e.id})}async function v(t,r){try{let i=await w(t.id,15e3,3e3,r);if(i.status===`unreadable`)throw new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{kind:`probe_inconclusive`,deviceId:t.id,stdout:i.result.stdout,stderr:i.result.stderr,hint:`CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device.`});if(i.status===`reported`){let n=i.details.tunnelState?.toLowerCase();if(n===`connecting`)throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,{kind:`not_ready`,deviceId:t.id,tunnelState:n,hint:`Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry.`});return}throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,n(i.result,{kind:`not_ready`,deviceId:t.id,tunnelState:i.details.tunnelState,hint:R(i.result.stdout,i.result.stderr)}))}catch(e){throw y(t.id,e)}}function y(t,n){return!(n instanceof e)||n.code!==`COMMAND_FAILED`?x(t,n):(typeof n.details?.kind==`string`?n.details.kind:``)===`not_ready`?n:b(t,n)}function b(t,n){let r=n.details??{},i=String(r.stdout??``),a=String(r.stderr??``),o=Number(r.timeoutMs??15e3),s=`CoreDevice did not respond within ${o}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,cause:n.message,timeoutMs:o,stdout:i,stderr:a,hint:i||a?R(i,a):s},n)}function x(t,n){return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,hint:`Reconnect the device, keep it unlocked, and retry.`},n instanceof Error?n:void 0)}async function S(e,t){return(await C(e,t??g))?.tunnelIp??null}async function C(e,t,n){if(!(t>0))return null;let r=Math.max(1,Math.min(g,t));try{let t=await w(e.id,r,0,n);return t.status!==`reported`||t.details.outcome&&t.details.outcome!==`success`?null:t.details}catch{return null}}async function w(e,t,n=0,r){let i=Math.max(1,Math.ceil(t/1e3)),a=await s({jsonPrefix:`agent-device-coredevice-info`,args:[`devicectl`,`device`,`info`,`details`,`--device`,e,`--timeout`,String(i)],signal:r,timeoutMs:t+n});return a.ok?{status:`reported`,details:O(a.payload)}:a.reason===`unreadable-json`?{status:`unreadable`,result:a.result}:{status:`failed`,result:a.result,details:O(a.payload)}}function T(e){let t=e,n=D(t.device);return{connectionProperties:E(D(t.connectionProperties),D(n?.connectionProperties)),deviceProperties:E(D(t.deviceProperties),D(n?.deviceProperties))}}function E(e,t){if(!e)return t;if(!t)return e;let n={...t};for(let[t,r]of Object.entries(e))r!==void 0&&(n[t]=r);return n}function D(e){return e&&typeof e==`object`?e:void 0}function O(e){let t=D(e?.result);if(!t)return{};let{connectionProperties:n,deviceProperties:r}=T(t);return{...k(`outcome`,A(e?.info?.outcome)),...k(`tunnelState`,A(n?.tunnelState)),...k(`tunnelIp`,A(n?.tunnelIPAddress)),...k(`developerModeStatus`,A(r?.developerModeStatus)),...k(`developerDiskImageServicesAvailable`,j(r?.ddiServicesAvailable)),...k(`bootState`,A(r?.bootState))}}function k(e,t){return t===void 0?{}:{[e]:t}}function A(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function j(e){return typeof e==`boolean`?e:void 0}const M={developerModeOff:u,developerDiskImageUnavailable:c};function N(e){return e.tunnelState===`connected`&&e.bootState===`booted`}function P(e){return`The device reported its developer disk image as unavailable while it was not observable (tunnelState=${e.tunnelState??`unknown`}, bootState=${e.bootState??`unknown`}). Unlock it, keep it connected by cable until \`xcrun devicectl device info details\` reports tunnelState=connected and bootState=booted, then retry.`}async function F(e,t=1e4,n){let r=await C(e,t,n);if(!r)return{available:!1,reason:`device_readiness_unreadable`,hint:"Read the device state directly with `xcrun devicectl device info details --device <id> --json-output -`, keeping the device unlocked and connected by cable, then retry."};let i=I(r.developerModeStatus),a=L(r.developerDiskImageServicesAvailable);return a===`unavailable`&&i!==`disabled`&&!N(r)?{available:!1,reason:`device_readiness_unreadable`,hint:P(r)}:{available:!0,developerMode:i,developerDiskImage:a,remedies:M}}function I(e){let t=e?.toLowerCase();return t===`enabled`?`enabled`:t===`disabled`?`disabled`:`unknown`}function L(e){return e===!0?`available`:e===!1?`unavailable`:`unknown`}function R(e,t){return l(e,t)||(`${e}\n${t}`.toLowerCase().includes(`timed out waiting for all destinations`)?`Xcode destination did not become available in time. Keep device unlocked and retry.`:f)}async function z(t,n,i,s=a){let c=r.fromTimeoutMs(s),l={exitCode:1,stdout:``,stderr:``};for(let e of h)if(l=await o([`devicectl`,`device`,`copy`,`from`,`--device`,t.id,`--source`,n,`--destination`,i,`--domain-type`,`appDataContainer`,`--domain-identifier`,e],{allowFailure:!0,timeoutMs:B(c,s)}),l.exitCode===0)return;let u=l.stderr.trim()||l.stdout.trim()||`devicectl exited with code ${l.exitCode}`;throw new e(`COMMAND_FAILED`,`Failed to copy runner file from iOS device: ${u}`)}function B(t,n){let r=t.remainingMs();if(r>0)return r;throw new e(`COMMAND_FAILED`,`iOS runner file copy timed out after ${n}ms`,{timeoutMs:n,step:`runner file copy`})}function V(t){if(!(t instanceof e))return{reason:t instanceof Error?t.message:String(t)};let n=t.details??{},r=Array.isArray(n.args)?n.args.filter(e=>typeof e==`string`).join(` `):void 0;return{errorCode:t.code,reason:t.message,timeoutMs:typeof n.timeoutMs==`number`?n.timeoutMs:void 0,exitCode:typeof n.exitCode==`number`?n.exitCode:void 0,stderr:typeof n.stderr==`string`&&n.stderr.trim()?n.stderr:void 0,stdout:typeof n.stdout==`string`&&n.stdout.trim()?n.stdout:void 0,commandArgs:r}}function H(e){let t=e.details??{},n=typeof t.stdout==`string`?t.stdout:``,r=typeof t.stderr==`string`?t.stderr:``,i=Array.isArray(t.args)?t.args.filter(e=>typeof e==`string`).join(` `):``;return`${e.message}\n${n}\n${r}\n${i}`.toLowerCase()}async function U(e,t,n){if(!n.preferRunner)try{await d([`device`,`capture`,`screenshot`,`--device`,e.id,`--destination`,t],{action:`capture iOS screenshot`,deviceId:e.id});return}catch(t){if(!Y(t))throw t;J(e,t)}let r=await G(e,n,!1);await K(r,t)||await z(e,q(r),t)}async function W(t,n,r){if(!await K(await G(t,r,!0),n))throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: XCTest runner returned no inline image`,{deviceId:t.id,backend:`xctest`})}async function G(e,t,n){return await t.runRunnerCommand(e,{command:`screenshot`,appBundleId:t.appBundleId,fullscreen:t.fullscreen,inlineScreenshot:n},t.runnerOptions??{})}async function K(e,t){let n=e.imageBase64;return typeof n!=`string`||n.length===0?!1:(await i(t,Buffer.from(n,`base64`)),!0)}function q(t){let n=t.message;if(typeof n==`string`&&n.length>0)return n;throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: runner returned no file path`)}function J(e,n){t({level:`warn`,phase:`ios_screenshot_fallback`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:`devicectl_screenshot`,to:`runner`,...V(n)}})}function Y(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=H(t);return n.includes(`unknown option '--device'`)||n.includes(`unknown subcommand`)&&n.includes(`screenshot`)||n.includes(`unrecognized subcommand`)&&n.includes(`screenshot`)}const X={coredevice:{backend:`coredevice`,ensureReady:v,listApps:ee,launchApp:_,terminateApp:async(e,t)=>await p(e,t),resolveAppProcesses:m,captureScreenshot:U,copyRunnerFile:z,resolveTunnel:async(e,t)=>({tunnelIp:await S(e,t)}),readDeviceReadiness:F},xctest:{backend:`xctest`,ensureReady:ie,listApps:Q,launchApp:ae,terminateApp:oe,resolveAppProcesses:$,captureScreenshot:W,copyRunnerFile:re,resolveTunnel:te,readDeviceReadiness:ne}};function Z(e){return X[e.iosPhysicalDeviceBackend===`xctest`?`xctest`:`coredevice`]}async function Q(t){throw new e(`UNSUPPORTED_OPERATION`,`App inventory is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use an installed app bundle ID when opening the device.`})}async function $(t){throw new e(`UNSUPPORTED_OPERATION`,`Process lookup is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use a CoreDevice-backed iOS device for performance sampling.`})}async function te(t){throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices have no CoreDevice tunnel.`,{deviceId:t.id,backend:`xctest`,hint:`Connect the device by cable so it is reachable through usbmux.`})}async function ne(e){return{available:!1,reason:`device_readiness_unreadable`,hint:`This device is driven through XCTest (device ${e.id}), which does not report Developer Mode or developer disk image state. Check the device's own Settings if development tooling fails to start on it.`}}async function re(t){throw new e(`UNSUPPORTED_OPERATION`,`Runner file copy is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`})}async function ie(t,r){let i=[`xcdevice`,`wait`,`--both`,`--timeout=15`,t.id],a=await o(i,{allowFailure:!0,signal:r,timeoutMs:18e3});if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`iOS device is not ready for XCTest automation`,n(a,{cmd:`xcrun`,args:i,deviceId:t.id,backend:`xctest`,hint:"Keep the device unlocked, trusted, connected, and visible in `xcrun xcdevice list`, then retry."}))}async function ae(t,n,r){if(r.payloadUrl||r.launchArgs&&r.launchArgs.length>0)throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices do not support deep links or launch arguments during open.`,{deviceId:t.id,backend:`xctest`,hint:`Open the installed app by bundle ID without a URL or --launch-args.`});await r.runRunnerCommand(t,{command:`activate`,appBundleId:n},r.runnerOptions??{})}async function oe(e,t,n){await n.runRunnerCommand(e,{command:`terminate`,appBundleId:t},n.runnerOptions??{})}export{H as n,V as r,Z as t};
@@ -1 +1 @@
1
- import{c as e,h as t}from"./exec.js";import"./command.js";import{r as n,t as r}from"./device-shell.js";import{t as i}from"./platform-runtime-android-mechanics.js";import a from"node:path";import{constants as o}from"node:fs";import s from"node:os";import{access as c,mkdtemp as l,readFile as u,rm as d,writeFile as f}from"node:fs/promises";function p(){return Object.freeze({isXcrunAvailable:async e=>{let{resolveAppleToolProvider:t}=await m(async()=>await import(`./tool-provider-facade.js`),e),n=t();return await m(async()=>await n.whichCommand(`xcrun`),e)},run:async(e,t)=>{let{runXcrun:n}=await m(async()=>await import(`./tool-provider-facade.js`),t),r=await m(async()=>await n([e.tool,...e.args],{allowFailure:e.allowFailure,signal:t,timeoutMs:e.timeoutMs}),t);return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}})}async function m(e,t){t?.throwIfAborted();try{let n=await e();return t?.throwIfAborted(),n}catch(e){throw t?.throwIfAborted(),e}}function h(){return Object.freeze({prepare:async e=>{if(e===`android`){let{ensureAndroidSdkPathConfigured:e}=await i();await e(process.env);return}if(e===`harmonyos`){let{ensureHarmonyToolchainPathConfigured:e}=await import(`./src4.js`).then(e=>e.b);await e()}}})}function g(e){let t=n(e.executable);return t&&r(e.args,t),e.args}function _(){return Object.freeze({commands:Object.freeze({which:async e=>await t(e)?e:void 0,run:async(t,n)=>{let r=await e(t.executable,g(t),{allowFailure:t.allowFailure,cwd:t.cwd,env:t.env?{...process.env,...t.env}:void 0,signal:n,timeoutMs:t.timeoutMs});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}}),appleTools:p(),toolchains:h(),files:Object.freeze({isExecutable:async e=>await y(e),createTemporaryTextFile:async e=>await b(e)}),hostOs:v(process.platform),hostName:s.hostname(),homeDirectory:s.homedir(),observations:Object.freeze({deviceBooted:async e=>{let{markSimulatorBooted:t}=await import(`./simulator-facade.js`);t(e)}})})}function v(e){return e===`darwin`||e===`linux`||e===`win32`?e:`other`}async function y(e){try{return await c(e,o.X_OK),!0}catch{return!1}}async function b(e){let t=await l(a.join(s.tmpdir(),e.prefix)),n=a.join(t,`value${e.suffix}`),r=!1;return{path:n,readText:async()=>await u(n,`utf8`),writeText:async e=>await f(n,e,`utf8`),[Symbol.asyncDispose]:async()=>{r||(r=!0,await d(t,{recursive:!0,force:!0}))}}}export{_ as createDeviceInventoryHost,b as createTemporaryTextFile,h as n,p as r,g as t};
1
+ import{c as e,h as t}from"./exec.js";import"./command.js";import{r as n,t as r}from"./device-shell.js";import{t as i}from"./platform-runtime-android-mechanics.js";import a from"node:path";import{constants as o}from"node:fs";import s from"node:os";import{access as c,mkdtemp as l,readFile as u,rm as d,writeFile as f}from"node:fs/promises";function p(){return Object.freeze({isXcrunAvailable:async e=>{let{resolveAppleToolProvider:t}=await m(async()=>await import(`./tool-provider-facade.js`),e),n=t();return await m(async()=>await n.whichCommand(`xcrun`),e)},run:async(e,t)=>{let{resolveAppleToolProvider:n,runXcrun:r}=await m(async()=>await import(`./tool-provider-facade.js`),t),i={allowFailure:e.allowFailure,signal:t,timeoutMs:e.timeoutMs},a=await m(async()=>e.tool===`simctl`?await n().simctl.run(e.args,i):await r([e.tool,...e.args],i),t);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}})}async function m(e,t){t?.throwIfAborted();try{let n=await e();return t?.throwIfAborted(),n}catch(e){throw t?.throwIfAborted(),e}}function h(){return Object.freeze({prepare:async e=>{if(e===`android`){let{ensureAndroidSdkPathConfigured:e}=await i();await e(process.env);return}if(e===`harmonyos`){let{ensureHarmonyToolchainPathConfigured:e}=await import(`./src4.js`).then(e=>e.b);await e()}}})}function g(e){let t=n(e.executable);return t&&r(e.args,t),e.args}function _(){return Object.freeze({commands:Object.freeze({which:async e=>await t(e)?e:void 0,run:async(t,n)=>{let r=await e(t.executable,g(t),{allowFailure:t.allowFailure,cwd:t.cwd,env:t.env?{...process.env,...t.env}:void 0,signal:n,timeoutMs:t.timeoutMs});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}}),appleTools:p(),toolchains:h(),files:Object.freeze({isExecutable:async e=>await y(e),createTemporaryTextFile:async e=>await b(e)}),hostOs:v(process.platform),hostName:s.hostname(),homeDirectory:s.homedir(),observations:Object.freeze({deviceBooted:async e=>{let{markSimulatorBooted:t}=await import(`./simulator-facade.js`);t(e)}})})}function v(e){return e===`darwin`||e===`linux`||e===`win32`?e:`other`}async function y(e){try{return await c(e,o.X_OK),!0}catch{return!1}}async function b(e){let t=await l(a.join(s.tmpdir(),e.prefix)),n=a.join(t,`value${e.suffix}`),r=!1;return{path:n,readText:async()=>await u(n,`utf8`),writeText:async e=>await f(n,e,`utf8`),[Symbol.asyncDispose]:async()=>{r||(r=!0,await d(t,{recursive:!0,force:!0}))}}}export{_ as createDeviceInventoryHost,b as createTemporaryTextFile,h as n,p as r,g as t};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-contracts.js";import{en as t}from"./sdk-batch.js";import{n}from"./scoped-provider.js";import{r,t as i}from"./platform-runtime-unavailable.js";import{a,t as o}from"./managed-device-scope.js";const s={ensureReady:`both`,deployApp:`both`,materializeAppSource:`both`,deployMaterializedApp:`both`,sendPushNotification:`both`,setSetting:`both`,readSetting:`both`,readClipboard:`both`,writeClipboard:`both`,captureScreenshot:`android`},c=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`This operation has no verified managed-device automation path.`});function l(s){return Object.freeze({owner:s.owner,ownsDevice:()=>!1,inspectFacts:async e=>r(e,s.owner,i(c)),bind:async r=>{if(r.intent.kind!==`exact-owner`||!t(r.intent.owner,s.owner))throw new e(`COMMAND_FAILED`,`A managed local owner binds only under an exact-owner intent naming it`,{reason:`runtime-contract-invalid`});let i=r.scope.managedDevice;if(!i||!t(i.owner,s.owner)||i.fence.token!==r.intent.fence.token||i.fence.generation!==r.intent.fence.generation)throw new e(`COMMAND_FAILED`,`Managed automation requires its exact request authority.`,{reason:`runtime-contract-invalid`});o(i,r.device);let c=e=>i.run(()=>a(i,e)),l=await s.loadLocal(r.device.platform),f=await c(()=>l.bind({device:r.device,intent:{kind:`ordinary`},scope:r.scope})),p=u(f.facts);return Object.freeze({device:f.device,owner:s.owner,facts:p,operations:d(n({...f.operations},e=>c(async()=>(r.scope.signal.throwIfAborted(),await i.admit(async()=>(r.scope.signal.throwIfAborted(),await e()))))),p),[Symbol.asyncDispose]:async()=>await c(async()=>await f[Symbol.asyncDispose]())})},shutdown:async()=>void 0})}function u(e){let t=Object.fromEntries(Object.entries(e.operations).map(([t,n])=>{let r=s[t];return[t,(e.device.family===`android`||e.device.family===`apple`&&e.device.appleOs===`ios`)&&(r===`both`||r===e.device.family)?n:c]}));return Object.freeze({device:e.device,operations:Object.freeze(t)})}function d(e,t){let n={};for(let[r,i]of Object.entries(e))t.operations[r]?.available===!0&&(n[r]=i);return Object.freeze(n)}export{l as createManagedLocalRuntimeOwner};
1
+ import{A as e}from"./sdk-contracts.js";import{en as t}from"./sdk-batch.js";import{n}from"./scoped-provider.js";import{r,t as i}from"./platform-runtime-unavailable.js";import{a,t as o}from"./managed-device-scope.js";const s={ensureReady:`both`,deployApp:`both`,materializeAppSource:`both`,deployMaterializedApp:`both`,sendPushNotification:`both`,setSetting:`both`,readSetting:`both`,readClipboard:`both`,writeClipboard:`both`,captureScreenshot:`android`},c=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`This operation has no verified managed-device automation path.`});function l(s){return Object.freeze({owner:s.owner,ownsDevice:()=>!1,inspectFacts:async e=>r(e,s.owner,i(c)),bind:async r=>{if(r.intent.kind!==`exact-owner`||!t(r.intent.owner,s.owner))throw new e(`COMMAND_FAILED`,`A managed local owner binds only under an exact-owner intent naming it`,{reason:`runtime-contract-invalid`});let i=r.scope.managedDevice;if(!i||!t(i.owner,s.owner)||i.fence.token!==r.intent.fence.token||i.fence.generation!==r.intent.fence.generation)throw new e(`COMMAND_FAILED`,`Managed automation requires its exact request authority.`,{reason:`runtime-contract-invalid`});o(i,r.device);let c=e=>i.run(()=>a(i,e)),l=await s.loadLocal(r.device.platform),f=await c(()=>l.bind({device:r.device,intent:{kind:`ordinary`},scope:r.scope})),p=u(f.facts);return Object.freeze({device:f.device,owner:s.owner,facts:p,operations:d(n({...f.operations},e=>c(async()=>(r.scope.signal.throwIfAborted(),await i.admit(async()=>(r.scope.signal.throwIfAborted(),await e()))))),p),[Symbol.asyncDispose]:async()=>await c(async()=>await f[Symbol.asyncDispose]())})},shutdown:async()=>void 0})}function u(e){let t=Object.fromEntries(Object.entries(e.operations).map(([t,n])=>{let r=s[t];return[t,(e.device.family===`android`||e.device.family===`apple`&&e.device.appleOs===`ios`)&&(r===`both`||r===e.device.family)?n:c]}));return Object.freeze({device:e.device,operations:Object.freeze(t)})}function d(e,t){let n={};for(let[r,i]of Object.entries(e))t.operations[r]?.available===!0&&(n[r]=i);return Object.freeze(n)}export{l as createManagedLocalRuntimeOwner};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{D as t}from"./sdk-contracts.js";import{a as n,i as r,o as i,r as a}from"./sdk-batch-runner.js";import{f as o,l as s}from"./sdk-device.js";import{n as c}from"./session.js";import{t as l}from"./platform-runtime-android-mechanics.js";var u=e({resolveRequestedOpenSurface:()=>f,resolveSessionAppBundleIdForTarget:()=>C,validateOpenRelaunchTarget:()=>_});const d=new Set([`app`,`desktop`,`frontmost-app`]);function f(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return t.platform===`linux`?p(n,r,i):o(t)?m(n,r,i):h(n)}function p(e,n,r){if(!e)return r??`app`;let i=c(e);if(!d.has(i))throw new t(`INVALID_ARGS`,`Linux supports --surface app, desktop, and frontmost-app (got "${e}")`);return g(i,n),i}function m(e,t,n){if(!e)return n??`app`;let r=c(e);return r!==`app`&&r!==`menubar`&&g(r,t),r}function h(e){if(e)throw new t(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}function g(e,n){if(e!==`app`&&e!==`menubar`&&n)throw new t(`INVALID_ARGS`,`open --surface ${e} does not accept an app target`)}async function _(e){let{target:t,platform:n,surface:i}=e;if(t&&r(t))return`open --relaunch does not support URL targets.`;if(i!==void 0&&i!==`app`)return`open --relaunch is supported only for app surfaces.`;if(n===`android`&&t){let{classifyAndroidAppTarget:e,formatAndroidInstalledPackageRequiredMessage:n}=await l();if(e(t)===`binary`)return n(t)}}async function v(e,t,c){if(!(!s(e.platform)||!t))return r(t)?o(e)?void 0:e.kind===`device`?i(c,t):n(t)?a:c??await y(e,t):await b(e,t)}async function y(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}catch{return}}async function b(e,t){try{let{resolveIosApp:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}catch{return}}function x(e,t){return e.platform===`android`&&!!(t&&r(t))}function S(e){let t=e?.trim();if(!(!t||r(t)||!t.includes(`.`)))return t}async function C(e,t,n){return e.platform===`harmonyos`?S(t)??n:await v(e,t,n)??await w(e,t)??(x(e,t)?n:void 0)}async function w(e,t){if(!(e.platform!==`android`||!t))try{let{resolveAndroidPackageForOpen:n}=await l();return await n(e,t)}catch{return}}export{_ as i,f as n,C as r,u as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{A as t}from"./sdk-contracts.js";import{a as n,i as r,o as i,r as a}from"./sdk-batch-runner.js";import{f as o,l as s}from"./sdk-device.js";import{i as c}from"./session.js";import{t as l}from"./platform-runtime-android-mechanics.js";var u=e({resolveRequestedOpenSurface:()=>f,resolveSessionAppBundleIdForTarget:()=>C,validateOpenRelaunchTarget:()=>_});const d=new Set([`app`,`desktop`,`frontmost-app`]);function f(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return t.platform===`linux`?p(n,r,i):o(t)?m(n,r,i):h(n)}function p(e,n,r){if(!e)return r??`app`;let i=c(e);if(!d.has(i))throw new t(`INVALID_ARGS`,`Linux supports --surface app, desktop, and frontmost-app (got "${e}")`);return g(i,n),i}function m(e,t,n){if(!e)return n??`app`;let r=c(e);return r!==`app`&&r!==`menubar`&&g(r,t),r}function h(e){if(e)throw new t(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}function g(e,n){if(e!==`app`&&e!==`menubar`&&n)throw new t(`INVALID_ARGS`,`open --surface ${e} does not accept an app target`)}async function _(e){let{target:t,platform:n,surface:i}=e;if(t&&r(t))return`open --relaunch does not support URL targets.`;if(i!==void 0&&i!==`app`)return`open --relaunch is supported only for app surfaces.`;if(n===`android`&&t){let{classifyAndroidAppTarget:e,formatAndroidInstalledPackageRequiredMessage:n}=await l();if(e(t)===`binary`)return n(t)}}async function v(e,t,c){if(!(!s(e.platform)||!t))return r(t)?o(e)?void 0:e.kind===`device`?i(c,t):n(t)?a:c??await y(e,t):await b(e,t)}async function y(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}catch{return}}async function b(e,t){try{let{resolveIosApp:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}catch{return}}function x(e,t){return e.platform===`android`&&!!(t&&r(t))}function S(e){let t=e?.trim();if(!(!t||r(t)||!t.includes(`.`)))return t}async function C(e,t,n){return e.platform===`harmonyos`?S(t)??n:await v(e,t,n)??await w(e,t)??(x(e,t)?n:void 0)}async function w(e,t){if(!(e.platform!==`android`||!t))try{let{resolveAndroidPackageForOpen:n}=await l();return await n(e,t)}catch{return}}export{_ as i,f as n,C as r,u as t};