agent-device 0.21.29 → 0.21.30

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 (177) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.apk → agent-device-android-ime-helper-0.21.30.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.manifest.json → agent-device-android-ime-helper-0.21.30.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.29.manifest.json → agent-device-android-snapshot-helper-0.21.30.manifest.json} +7 -7
  7. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +4 -2
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +2 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +12 -0
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +25 -0
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +8 -1
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +9 -6
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +3 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +35 -9
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +44 -26
  16. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -1
  17. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +4 -3
  18. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +4 -2
  19. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +20 -2
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/agent-browser-lifecycle.js +1 -1
  22. package/dist/src/agent-browser-process-record.js +1 -1
  23. package/dist/src/agent-browser-provider.js +1 -1
  24. package/dist/src/agent-device-client.js +1 -1
  25. package/dist/src/alert2.js +1 -1
  26. package/dist/src/android.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-runtime2.js +3 -3
  29. package/dist/src/auth.js +1 -1
  30. package/dist/src/automation-helper.js +1 -1
  31. package/dist/src/back-mode.js +1 -1
  32. package/dist/src/cli-config.js +1 -1
  33. package/dist/src/cli-help.js +13 -10
  34. package/dist/src/cli.js +3 -3
  35. package/dist/src/client-types.d.ts +82 -13
  36. package/dist/src/cloud-artifacts.d.ts +99 -3
  37. package/dist/src/command-metadata.js +42 -42
  38. package/dist/src/composed-inventory-gateways.js +1 -1
  39. package/dist/src/connection-runtime.js +1 -1
  40. package/dist/src/connection.js +1 -1
  41. package/dist/src/contract.d.ts +2 -2
  42. package/dist/src/contracts.d.ts +1 -1
  43. package/dist/src/daemon-client-ensure.js +1 -1
  44. package/dist/src/daemon-client-ensuring.js +1 -1
  45. package/dist/src/daemon-client-lease-beat.js +1 -1
  46. package/dist/src/daemon-client-lifecycle.js +1 -1
  47. package/dist/src/daemon-client.js +2 -2
  48. package/dist/src/daemon-lifecycle-errors.js +1 -1
  49. package/dist/src/daemon-registration-owner.js +3 -3
  50. package/dist/src/daemon-registration.js +1 -1
  51. package/dist/src/daemon-resolution.js +1 -1
  52. package/dist/src/daemon-shutdown-report.js +1 -1
  53. package/dist/src/daemon-startup-diagnostics.js +1 -1
  54. package/dist/src/daemon.js +3 -3
  55. package/dist/src/device-claim-recovery.js +1 -1
  56. package/dist/src/durable-capture-resource.js +1 -1
  57. package/dist/src/durable-resource.js +1 -1
  58. package/dist/src/ended-lease.js +1 -1
  59. package/dist/src/find.js +1 -1
  60. package/dist/src/finders.js +1 -1
  61. package/dist/src/gesture-plan-types.d.ts +14 -4
  62. package/dist/src/gesture-plan.js +1 -1
  63. package/dist/src/gesture-runtime.js +1 -1
  64. package/dist/src/host4.js +1 -1
  65. package/dist/src/index.d.ts +3 -3
  66. package/dist/src/input-actions.js +1 -1
  67. package/dist/src/input-actions2.js +1 -1
  68. package/dist/src/interaction-positionals.js +1 -1
  69. package/dist/src/interaction.js +1 -1
  70. package/dist/src/interaction2.js +1 -1
  71. package/dist/src/interactor-operation-catalog.js +1 -1
  72. package/dist/src/interactor.js +5 -5
  73. package/dist/src/interactor3.js +1 -1
  74. package/dist/src/interactor4.js +1 -1
  75. package/dist/src/internal/bin.js +1 -1
  76. package/dist/src/internal/daemon.js +1 -1
  77. package/dist/src/internal/png-worker.js +1 -1
  78. package/dist/src/inventory6.js +1 -1
  79. package/dist/src/ios-node-interpretation.js +1 -1
  80. package/dist/src/ios-snapshot-acquisition.js +1 -1
  81. package/dist/src/ios-snapshot-engine.js +1 -1
  82. package/dist/src/ios-snapshot-runtime.js +1 -1
  83. package/dist/src/keyboard-occlusion.js +1 -1
  84. package/dist/src/launch-confirmation.js +1 -1
  85. package/dist/src/lease-context.js +1 -1
  86. package/dist/src/lease-registry-scope.js +1 -1
  87. package/dist/src/lease.js +1 -1
  88. package/dist/src/local-interactor-operation-set.js +1 -1
  89. package/dist/src/mechanics.js +12 -12
  90. package/dist/src/metro-session-hints.js +1 -1
  91. package/dist/src/mobile-snapshot-semantics.js +1 -1
  92. package/dist/src/observability.js +1 -1
  93. package/dist/src/observation.js +1 -1
  94. package/dist/src/parameterized-recorded-fill.js +1 -1
  95. package/dist/src/perf-facade.js +1 -1
  96. package/dist/src/platform-runtime-operation-host.js +1 -1
  97. package/dist/src/platform-runtime-unavailable.js +1 -1
  98. package/dist/src/platform-runtime.js +1 -1
  99. package/dist/src/platform-runtime2.js +1 -1
  100. package/dist/src/plugins2.js +1 -1
  101. package/dist/src/png-resize.js +1 -1
  102. package/dist/src/png-worker-client.js +1 -1
  103. package/dist/src/png-worker-contract.js +1 -1
  104. package/dist/src/provider-device-runtime.d.ts +20 -1
  105. package/dist/src/provider-plugin.d.ts +1 -1
  106. package/dist/src/react-native-overlay2.js +1 -1
  107. package/dist/src/record-runtime.js +1 -1
  108. package/dist/src/replay-maestro-backend.js +3 -3
  109. package/dist/src/replay-script-selection.js +1 -1
  110. package/dist/src/replay.d.ts +1 -1
  111. package/dist/src/request-runtime-binding.js +1 -1
  112. package/dist/src/result-serialization.js +1 -1
  113. package/dist/src/runner-error-classification.js +1 -1
  114. package/dist/src/runtime-admission.js +1 -1
  115. package/dist/src/runtime-deployment.js +1 -1
  116. package/dist/src/runtime-factory.js +1 -1
  117. package/dist/src/runtime-session.js +1 -1
  118. package/dist/src/runtime.js +5 -5
  119. package/dist/src/runtime10.js +2 -2
  120. package/dist/src/runtime3.js +5 -5
  121. package/dist/src/runtime5.js +1 -1
  122. package/dist/src/runtime6.js +1 -1
  123. package/dist/src/runtime7.js +1 -1
  124. package/dist/src/runtime8.js +1 -1
  125. package/dist/src/runtime9.js +2 -2
  126. package/dist/src/screenshot-image-size.js +1 -0
  127. package/dist/src/screenshot-image.js +1 -1
  128. package/dist/src/screenshot-runtime.js +1 -1
  129. package/dist/src/screenshot3.js +2 -2
  130. package/dist/src/sdk-batch.js +1 -1
  131. package/dist/src/sdk-contracts.d.ts +7 -1
  132. package/dist/src/sdk-finders.js +1 -1
  133. package/dist/src/sdk-selectors.d.ts +1 -1
  134. package/dist/src/sdk-selectors.js +1 -1
  135. package/dist/src/selection.js +0 -0
  136. package/dist/src/selector-pipeline-policy.js +1 -1
  137. package/dist/src/selector-runtime.js +1 -1
  138. package/dist/src/selectors.js +1 -1
  139. package/dist/src/server-startup.js +1 -1
  140. package/dist/src/session-replay-vars.js +1 -1
  141. package/dist/src/session-store.js +2 -2
  142. package/dist/src/session.js +1 -1
  143. package/dist/src/session2.js +5 -5
  144. package/dist/src/settle-observation-capture.js +1 -1
  145. package/dist/src/snapshot-capture-annotations.js +1 -1
  146. package/dist/src/snapshot-chrome.js +1 -1
  147. package/dist/src/snapshot-desktop-projection.js +1 -1
  148. package/dist/src/snapshot-helper-install.js +7 -5
  149. package/dist/src/snapshot-node-lookup.js +1 -1
  150. package/dist/src/snapshot-occlusion.js +1 -1
  151. package/dist/src/snapshot-runtime-binding.js +1 -1
  152. package/dist/src/snapshot-runtime-capture-input.js +1 -1
  153. package/dist/src/snapshot-runtime.js +1 -1
  154. package/dist/src/snapshot-state.js +1 -1
  155. package/dist/src/snapshot.js +1 -1
  156. package/dist/src/src.js +1 -1
  157. package/dist/src/src3.js +1 -1
  158. package/dist/src/src4.js +1 -1
  159. package/dist/src/tap-keyboard-occlusion.js +1 -1
  160. package/dist/src/target-evidence-tree.js +1 -1
  161. package/dist/src/target-evidence.js +1 -1
  162. package/dist/src/telephony-runtime.js +1 -1
  163. package/dist/src/text-entry-focus.js +1 -1
  164. package/dist/src/touch-reference-frame.js +1 -1
  165. package/dist/src/touch-runtime2.js +1 -1
  166. package/dist/src/tree.js +1 -1
  167. package/dist/src/tv-remote-runtime.js +1 -1
  168. package/dist/src/tv-remote.js +2 -2
  169. package/dist/src/type-text-runtime.js +1 -1
  170. package/dist/src/video.js +1 -1
  171. package/dist/src/webdriver-source.js +1 -1
  172. package/package.json +1 -1
  173. package/server.json +2 -2
  174. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.29.apk.sha256 +0 -1
  175. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk +0 -0
  176. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk.sha256 +0 -1
  177. package/dist/src/daemon-client-lifecycle-request.js +0 -1
@@ -1,5 +1,5 @@
1
- import{B as e,R as t,V as n,Z as r,et as i}from"./sdk-contracts.js";import{v as a,w as o}from"./tv-remote.js";import{a as s,b as c,i as l,v as u}from"./sdk-batch-runner.js";import{G as d,J as f,K as p,L as m,T as ee,bt as te,ht as h,j as ne,y as re}from"./sdk-io.js";import"./diagnostics.js";import{C as ie,F as ae,_ as g,g as oe,j as _,p as se,u as ce,v}from"./sdk-device.js";import{Zt as le,an as ue,in as y,nn as de,rn as b}from"./sdk-batch.js";import{n as fe,r as pe}from"./session.js";import{a as me,t as he}from"./file.js";import"./command.js";import{r as ge}from"./version.js";import"./retry.js";import{i as _e,n as ve,r as ye}from"./ios-snapshot-planning.js";import{i as be,n as xe}from"./durable-resource.js";import{n as Se}from"./screen-recording-runtime.js";import{t as Ce}from"./request.js";import{n as we,r as Te,t as Ee}from"./application-lifecycle-runtime.js";import{n as De,t as Oe}from"./async-lifecycle.js";import{i as ke,t as Ae}from"./touch-runtime.js";import{t as je}from"./ios-system-surface.js";import{r as Me}from"./gesture-admission.js";import{A as Ne,B as Pe,D as Fe,F as Ie,G as Le,H as Re,J as ze,K as Be,L as Ve,M as He,N as Ue,O as We,S as Ge,T as Ke,U as qe,X as Je,Y as Ye,_ as Xe,b as Ze,g as Qe,j as $e,l as et,o as tt,p as nt,r as rt,w as it,z as at}from"./tv-remote-runtime.js";import{n as ot,o as st,s as ct,u as lt}from"./application-lifecycle-interaction.js";import{t as ut}from"./interactor-operation-catalog.js";import{a as dt,i as ft,n as pt,o as mt,r as ht,s as gt,t as _t}from"./network-traffic.js";import{a as vt,i as yt,r as bt}from"./src4.js";import{n as xt,t as St}from"./screen-recording-completion.js";import{a as Ct,c as wt,i as Tt,l as Et,n as Dt,o as Ot,r as kt,s as At,t as jt}from"./device-readiness-runtime.js";import{a as Mt,i as Nt,n as Pt,r as Ft,t as It}from"./perf-runtime-operation-builder.js";import{t as Lt}from"./app-log-runtime.js";import{n as Rt}from"./artifact-paths.js";import{O as zt,T as Bt,b as Vt,c as Ht,f as Ut,g as Wt,n as Gt,o as Kt,w as qt}from"./host-file.js";import{a as Jt,o as Yt,s as Xt}from"./config.js";import{a as Zt,o as Qt}from"./tool-provider.js";import{o as $t}from"./devicectl.js";import{t as en}from"./physical-device-apps.js";import{t as tn}from"./apple-runner-platform.js";import{a as nn,c as rn,n as an,o as on,s as x,u as sn}from"./simctl.js";import{r as cn}from"./simulator.js";import{r as ln}from"./display-inventory.js";import{n as un,t as dn}from"./app-backend.js";import{t as fn}from"./simulator-state.js";import{createHash as pn,randomUUID as mn}from"node:crypto";import S from"node:path";function hn(e,t){return Object.freeze({appState:async n=>{if(t.signal.throwIfAborted(),!await e.appleApplications.hasLiveRunnerSession(t.device,{}))return{};let r=await t.resolveInteractor(t.device,{appBundleId:n?.appBundleId,signal:t.signal});if(typeof r.appState!=`function`)throw ue(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function gn(e){return Ot(e)?Object.freeze({available:!0}):v(e)||g(e)&&e.kind===`simulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio is supported for macOS sessions and iOS simulators on macOS hosts; physical iOS devices expose no host audio tap.`})}function _n(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...It({platform:`Apple`,expectedProfileKind:`xctrace`,start:async e=>await t().start(n,r,e),reattach:async e=>await t().reattach(n,e),cleanup:async e=>await t().cleanup(n,e),writeProfileReport:async e=>await t().writeProfileReport(e)}),perfFrames:async({appId:e})=>({metric:e?await Nt(t().sampleFrames(n,e)):Pt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await Nt(t().sampleMemory(n,e)):Pt(`Apple`,`bundle ID`),sampling:await t().memorySampling(n)}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`memgraph`,s={...await t().memorySnapshotSupport(n),androidHprof:!1,heapprofd:!1};if(o!==`memgraph`)return Mt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw Ft();let c=i??S.join(a,`memory-memgraph-${vn()}.memgraph`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`xcrun memgraph`,description:`Native Apple memory graph captured for offline inspection.`,defaultKind:`memgraph`,artifactOnly:!0}}}})}function vn(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const C=Object.freeze({available:!0}),w=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),T=xn(`Gestures are supported only for Apple simulators and devices.`),yn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Me}),bn=xn(`scroll is supported only for Apple simulators and devices.`);function xn(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Sn(e){return{...Le({unsupported:Cn(e),plan:wn(e),directionalFling:wn(e),multiTouch:Tn(e),targetAuthoredDrag:En(e),viewport:Dn(e)}),...Re({scroll:On(e)})}}function Cn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?w:T}function wn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?w:E(e)?C:T}function Tn(e){if(e.appleOs===`watchos`)return w;if(!E(e))return T;let t=_(e);if(t!==`ios`&&t!==`ipados`){let e=un[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return C}function En(e){return E(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?C:yn:T}function Dn(e){return e.appleOs===`watchos`?w:E(e)?C:T}function On(e){return E(e)?C:bn}function E(e){return e.kind===`simulator`||e.kind===`device`}const D=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function O(e){return v(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const kn=Object.freeze({resourceKind:Lt,version:1,encode:e=>({...e}),decode:e=>!jn(e.transport)||!Mn(e.backend)||!In(e.outputPath)||!Pn(e.pidPath)||!Nn(e.transport,e.backend)?An():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function An(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function jn(e){return e===`apple-log-stream`||e===`coredevice-console`}function Mn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Nn(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function Pn(e){return e===void 0||In(e)}function Fn(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return xe({resourceKind:Lt,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:be(kn,e.descriptor)})}function In(e){return typeof e==`string`&&e.trim().length>0}const Ln={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},Rn={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function zn(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function Bn(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(v(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await Et(async()=>wt(await e.appleTools.run({tool:`simctl`,args:rn(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(D);else{i.devicectlAvailable=await Et(async()=>wt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await zn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?Ln:Rn;a.push(`${e.message} ${e.hint}`)}}return{backend:O(t),checks:i,notes:a}}function Vn(e,t){let n=Wn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=Wn(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function Hn(e,t){return an(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,Vn(t.appBundleId,t.executableName)])}function Un(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function Wn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function Gn(e,t,n,r,i){Kn(t),ft(e,n);let a=O(t),o=await Jn(e,t,n.appBundleId,i),s=new Oe,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await qn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=Xn(e,u,l,a,n.outputPath),f={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},p=gt(d,Fn({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function Kn(e){if(e.appleOs===`watchos`)throw new t(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new t(`UNSUPPORTED_OPERATION`,D,{hint:D})}async function qn(e,n,r,i,a,o){if(g(n)&&n.kind===`device`){let n=await zn(e,o);if(!n.supported){let e=n.reason===`unsupported`?Ln:Rn;throw new t(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,e.message,{backend:`ios-device`,hint:e.hint,stderr:n.stderr})}}return o?.throwIfAborted(),await e.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function Jn(e,t,n,r){return v(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,Vn(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:Un(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:Hn(t,{appBundleId:n,executableName:await Yn(e,t,n,r)}),allowFailure:!0}}async function Yn(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:x(t,[`get_app_container`,t.id,n,`app`]),allowFailure:!0,timeoutMs:4e3},r),a=i.exitCode===0?i.stdout.trim():``;if(!a)return;let o=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,S.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function Xn(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return dt({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Zn([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function Zn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const k=le(`apple`),Qn=Object.freeze({available:!0});function $n(e){return Object.freeze({owner:k,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>tr(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!de(n.intent.owner,k))throw new t(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return er(e,n.device,n.scope.signal)},shutdown:async()=>void 0})}function er(e,n,r){if(n.platform!==`apple`)throw new t(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=mt({codec:kn,reattach:async(t,r)=>t.backend!==O(n)||!ht(e,r.sessionId,t)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await yt(e,t.pidPath),cleanup:async(t,r)=>t.backend===O(n)&&ht(e,r.sessionId,t)?await bt(e,t.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:O(n)}),appLogDoctor:async({appBundleId:t})=>await Bn(e,n,t,r),appLogStart:async t=>await Gn(e,n,t,k,r),...i});return Object.freeze({device:n,owner:k,facts:tr(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function tr(e){if(e.appleOs===`watchos`)return nr(e);let t=g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:D}:Qn;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:Qn,appLogCleanup:Qn}})}function nr(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function rr(e,t,n,r){let i=O(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=pt(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(ar(t,n,o.dump)){let i=await or(e,t,n,a.path,r);i&&(o=ir(s,o,i,n.maxEntries))}return lr(s,t,n),cr(s,o.dump),o.dump.entries.length===0&&s.push(ur(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function ir(e,t,n,r){let i=n.scan.dump.entries.length;return i===0&&(n.scan.dump.unnamedRequests??0)===0?(n.lineCount>0&&e.push(`Recovered ${n.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`),t):(i>0&&e.push(`Recovered ${i} iOS simulator HTTP entr${i===1?`y`:`ies`} from simctl log show (${n.lineCount} app log lines scanned).`),_t(n.scan,t,r))}function ar(e,t,n){return g(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function or(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=x(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,sr(n.appBundleId),...typeof a==`number`&&Number.isFinite(a)&&a>0?[`--start`,`@${Math.floor(a/1e3)}`]:[`--last`,`5m`]]),s=await e.appleTools.run({tool:`simctl`,args:o,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
2
- `).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:pt(`${c.join(`
3
- `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function sr(e){let t=e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function cr(e,t){let n=t.entries.filter(e=>e.pathUnavailable).length,r=t.unnamedRequests??0,i=n+r;if(i===0)return;let a=[`${i} request${i===1?``:`s`} reused a keep-alive connection, so CFNetwork logged no request URL.`];n>0&&a.push(`${n} listed against the origin the connection was opened for, without a path.`),r>0&&a.push(`${r} opened before this scan window and are missing from the entries entirely; scan more lines, or run logs clear --restart before the repro.`),a.push(`Absence of an endpoint in this dump does not prove it was not called.`),e.push(a.join(` `))}function lr(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(g(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function ur(e){return g(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:g(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function dr(t){let{host:n,snapshot:r,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=t,s=r.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:t.stopObservation;if(r.invalidatedReason&&!r.showTouches)throw Error(`recording invalidated: ${r.invalidatedReason}`);let c;try{c=await n.screenRecording.finalize.complete({outputPath:r.outPath,showTouches:!r.invalidatedReason&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,...r.fps===void 0?{}:{fps:r.fps},targetLabel:i})}catch(t){throw e(t,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return St(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function fr(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await pr(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function pr(t){try{return await t()}catch(t){throw e(t,`COMMAND_FAILED`)}}const mr=[`outPath`,`startedAt`,`clientOutPath`,...Tt],hr=Object.freeze({resourceKind:Se,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>Dr(e)});function gr(e){let{device:t,owner:n,input:r,descriptor:i}=e;return xe({resourceKind:Se,sessionId:r.sessionId,device:ae(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:be(hr,i)})}function _r(e){let t={};for(let n of mr)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function vr(e,t,n,r){let i=hr.decode(n);return i.status!==`decoded`||!Lr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await yr(e,i.descriptor.processes,r):await xr(e,t,i.descriptor)}async function yr(e,t,n){let r=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(r.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(r.every(e=>e===`missing`))return n!==void 0&&e.screenRecording.ownedProcesses.clear(br(n)),{status:`already-missing`};let i=await Promise.all(t.flatMap((t,n)=>r[n]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return i.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(n!==void 0&&e.screenRecording.ownedProcesses.clear(br(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function br(e){return{kind:`session`,sessionId:e}}async function xr(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function Sr(e){let{host:t,device:n,envelope:r}=e,i=hr.decode(r.descriptor.body);return i.status===`decoded`?Lr(n,i.descriptor)?i.descriptor.backend===`simctl`?await Cr(e,i.descriptor):await Tr(t,n,i.descriptor):A(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):A(`descriptor-invalid`,i.message)}async function Cr(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return A(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=wr(kt(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await Er(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await yr(e.host,t.processes,e.envelope.sessionId)}}function wr(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function Tr(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:A(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function Er(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function A(e,t){return{status:`unreattachable`,reason:e,message:t}}function Dr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?M():e.backend===`simctl`?Or(e,e.outputPath):e.backend===`runner`?jr(e,e.outputPath):M()}function Or(e,t){let n=Rr(e.processes),r=kr(e.recording);return!n||r===`invalid`?M():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function kr(e){if(e!==void 0)return u(e)&&Ar(e)?Object.freeze(e):`invalid`}function Ar(e){return j(e.outPath)&&Nr(e.startedAt)&&Mr(e.clientOutPath)&&Ct(e)}function jr(e,t){return!j(e.appBundleId)||!j(e.runnerSessionId)||!Pr(e.runnerAuthority)||!Fr(e.remotePath)?M():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function j(e){return typeof e==`string`&&e.length>0}function Mr(e){return e===void 0||j(e)}function Nr(e){return typeof e==`number`&&Number.isFinite(e)}function Pr(e){return e===`local-lease`||e===`scoped-provider`}function Fr(e){return e===void 0||Ir(e)}function Ir(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Lr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:g(e)?t.remotePath!==void 0&&Ir(t.remotePath):t.remotePath===void 0:!1}function Rr(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function M(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function zr(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const Br=`iOS recording`,Vr=`simctl recordVideo`;function Hr(e){return e.appleOs===`watchos`?b(`unsupported-platform-leaf`,`watchOS recording is not supported.`):g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?b(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function Ur(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Wr({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await Sr({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:Kr({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await vr(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Wr(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Gr(e):await Jr(e)}async function Gr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await zr(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=Rt(i.outputPath);await t.screenRecording.outputs.prepare(s);let c=await t.screenRecording.apple.startSimulator(n,s,a),l=c.markers;if(!l||l.length===0)throw await $r(c).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted(),t.screenRecording.ownedProcesses.replace({kind:`session`,sessionId:i.sessionId},l.map(e=>({...e,purpose:`simctl-screen-recording`})))}catch(e){try{t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId})}catch{}throw await $r(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Xr(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=ni(i,Vr,{},o);return ti({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:_r(p)},snapshot:p,finish:(e,n)=>Dt({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await qr(t,s,e)}catch(e){throw Zr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await fr({host:t,snapshot:e,targetLabel:Br,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Zr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await ei(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function Kr(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:Vr,gestureEvents:[]});return xt(a,{finish:(e,i)=>Dt({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await qr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await fr({host:t,snapshot:e,targetLabel:Br,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function qr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Jr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>(l??=Yr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!Qr(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return ti({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:ni(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await dr({host:t,snapshot:e,targetLabel:n.appleOs===`macos`?`macOS recording`:`iOS recording`,stopObservation:{recorder:`confirmed`},...s.remotePath===void 0?{}:{nativePathDisposition:`retirable`}})),cleanup:async()=>(await u(),{status:`cleaned`})})}async function Yr(t){try{return await t()}catch(t){throw e(t,`COMMAND_FAILED`)}}function Xr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Zr(n,r,i){let a=e(n,`COMMAND_FAILED`);return r===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?n:new t(a.code,`${a.message}; ${r}`,d(i,{...a.details??{},...i.signal===void 0?{}:{signal:i.signal},retriable:!1,hint:`The recorder exited before record stop, so the next record stop reads the same file. Close this session to release the device, then record again.`}))}function Qr(e,t){return e.appleOs===`macos`||!g(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function $r(e){return await e.terminate(),await e.wait}async function ei(e){try{return await $r(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function ti(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=xt(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new De(c),envelope:gr({device:t,owner:n,input:r,descriptor:i})})}function ni(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}async function N(e,t,n,r={}){return n.throwIfAborted(),v(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await ri(e,t)?`Booted`:await li(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await ii(e,t,n,r.deadlineAtMs),await ui(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function ri(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function ii(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await ai(e,t,n,r),await oi(e,t,n,r)}catch(a){throw i&&n.aborted&&di(e,t),n.throwIfAborted(),Date.now()>=r?ci(t,a):a}}async function ai(e,n,r,i){let a=await e.appleTools.run({tool:`simctl`,args:x(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:si(i,n)},r),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new t(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function oi(e,n,r,i){Ce({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await e.appleTools.run({tool:`simctl`,args:x(n,[`bootstatus`,n.id,`-b`]),allowFailure:!0,timeoutMs:si(i,n)},r);if(a.exitCode!==0)throw new t(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(r.throwIfAborted(),Date.now()>=i)throw ci(n)}function si(e,t){let n=e-Date.now();if(n<=0)throw ci(t);return n}function ci(e,n){return new t(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:jt,deviceId:e.id,hint:`The Simulator keeps booting in the background; a first boot can take several minutes. Retry once it is up, or pass a larger --timeout.`},n instanceof Error?n:void 0)}async function li(e,t,n){return await fn(e.appleTools,t,n,15e3)}async function ui(e,t){await e.commands.run({executable:`open`,args:[`-g`,`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function di(e,t){e.appleTools.run({tool:`simctl`,args:x(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const fi=Object.freeze({resolveOpenTarget:`simulator`,prepareApplicationOpen:`simulator`,openApplication:`simulator`,applyRuntimeHints:`simulator`,clearRuntimeHints:`simulator`,closeApplication:`simulator`,finalizeApplicationClose:`simulator`,prepareAppleRunner:`runner`,configureProviderPortReverse:`simulator`,ensureReady:`simulator`,bootTarget:`simulator`,bootTargetHeadless:`simulator`,shutdownTarget:`simulator`,listApps:`simulator`,deployApp:`simulator`,materializeAppSource:`simulator`,deployMaterializedApp:`simulator`,sendPushNotification:`simulator`,uninstallApp:`simulator`,appState:`simulator`,appLogStart:`simulator`,appLogInspect:`simulator`,appLogDoctor:`simulator`,appLogReattach:`simulator`,appLogCleanup:`simulator`,networkDump:`simulator`,audioProbeStart:`simulator`,audioProbeQuery:`simulator`,audioProbeReattach:`simulator`,audioProbeCleanup:`simulator`,readClipboard:`simulator`,writeClipboard:`runner`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`simulator`,sendTelephonyEvent:`simulator`,unlockOrientation:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`runner`,querySelector:`runner`,readTextAtPoint:`runner`,tapPoint:`runner`,tapRef:`runner`,tapElementSelector:`runner`,fillPoint:`runner`,fillRef:`runner`,longPressPoint:`runner`,hoverPoint:`runner`,hoverRef:`runner`,focusPoint:`runner`,typeText:`runner`,scrollDirection:`runner`,performGesturePlan:`runner`,performMultiTouchGesturePlan:`runner`,performTargetAuthoredDrag:`runner`,performDirectionalFlingPlan:`runner`,gestureViewport:`runner`,setViewport:`runner`,back:`runner`,home:`runner`,setOrientation:`runner`,appSwitcher:`runner`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function pi(e){return e===void 0?`possible`:e.some(e=>fi[e]===`runner`)?`required`:`none`}function mi(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 hi(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 gi(e,t){let n=await Zt(`ps`,[`-p`,String(e),`-o`,`lstart=`],{allowFailure:!0,signal:t.signal,timeoutMs:t.timeoutMs});return n.exitCode===0&&n.stdout.trim()||null}const _i=3e3,vi=`simulator-target-discovery-pending`,yi=`simulator-target-unavailable`;function bi(){let e=new Map,t=new Map,n=hi({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);if(c&&o!==`refresh`){let e=await gi(c.pid,{signal:a,timeoutMs:_i});if(a.throwIfAborted(),e===c.processStartTime)return c}return e.delete(s),await n.value(s,{start:async()=>{let n=await wi(r,i,t);return e.set(s,n),n},wait:(e,t)=>mi({waitMs:e,signal:a,stop:t,cancelled:()=>xi(a)}),pending:()=>P(vi,r,i)})}}function xi(e){return n({readinessPhase:`target-discovery`},e.reason)}function Si(e){return e instanceof t&&e.details?.reason===vi}function Ci(e){return e instanceof t&&e.details?.reason===yi}async function wi(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([on(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:Di(r)}),Ti(e,n,r)]);if(i.status===`rejected`)throw i.reason;if(a.status===`rejected`)throw a.reason;let o=i.value,s=a.value;if(o.exitCode!==0)throw P(`simulator-target-probe-failed`,e,t);let c=Ei(o.stdout,t);if(!c)throw P(yi,e,t);let l=await gi(c.pid,{timeoutMs:Math.min(_i,Di(r))});if(!l)throw P(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:sn(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Ti(e,t,n){let r=t.get(e.id);if(r)return await r;let i=on(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:Di(n)}).then(t=>{if(t.exitCode!==0)throw P(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(nn(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw P(`simulator-runtime-unavailable`,e,``);return n});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Ei(e,t){for(let n of e.split(`
4
- `)){let[e,,r]=n.trim().split(/\s+/);if(!e||!r||!r.startsWith(`UIKitApplication:${t}[`))continue;let i=Number(e);if(Number.isSafeInteger(i)&&i>0)return{pid:i,label:r}}}function Di(e){return Math.max(1,e-Date.now())}function P(e,n,r){return new t(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:n.id,appBundleId:r})}function Oi(e){return e?.observation===`unobservable`&&e.proof===`no-running-process`}const ki=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function F(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function Ai(e){let t=_e(ye({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!F(n))return{observation:`not-eligible`};let a;for(;;){let o=await Mi(e.resolveTarget,n,r,i);if(`verdict`in o)return o.verdict;let{target:s}=o;if(e.isBridgeDisabled(s))return h({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:s.generation}}),ji({source:`circuit`});let c=await e.source.acquire({target:s,hint:t,signal:i});if(c.stage!==`failed`)return{observation:`observable`};i.throwIfAborted();let{kind:l,code:u}=c.failure,d=ki.get(u);if(d===void 0)return ji({source:`bridge`,kind:l,code:u});let f=e.clock.now();if(a=Math.min(a??1/0,f+d),f>=a)return{observation:`unobservable`,proof:`launch-transition`};await e.clock.sleep(Math.min(150,a-f),i)}}})}function ji(e){return{observation:`probe-failed`,failure:e}}async function Mi(e,t,n,r){for(;;)try{return{target:await e(t,n,r)}}catch(e){if(r.throwIfAborted(),Si(e))continue;if(Ci(e))return{verdict:{observation:`unobservable`,proof:`no-running-process`}};let{code:t,details:n}=i(e),a=n?.reason;return{verdict:ji(typeof a==`string`?{source:`target`,code:t,reason:a}:{source:`target`,code:t})}}}function Ni(e,t,n){let r=n&&F(e),i=r?pi(t.execution.plannedOperations):void 0,a=g(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function Pi(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function Fi(e,n,r,i,a,o){let s=Date.now(),c=async()=>await Hi(n,r,i,a.observation),l=await c(),u,d,f=a.answerConfirmation,p=f&&l?.observation!==`observable`?await Ii(f,a.redispatchLaunchUrl,c,l):void 0;if(p&&(o.runnerDemand=`required`,u=p.report,d=p.probeFailure,l=p.observed,p.unanswered))throw new t(`COMMAND_FAILED`,`The Simulator has not completed the launch URL for ${r.appBundleId}.`,{reason:`launch_confirmation_unanswered`,appBundleId:r.appBundleId,hint:`iOS may still be holding an "Open in" prompt, or the answer died with the runner session that raised it. Inspect the current alert before deciding on another action.`});if(i&&l?.observation!==`observable`&&await e.clock.sleep(300,n.signal),l&&(o.postOpenObservation=l.observation,l.observation===`probe-failed`&&(o.postOpenObservationFailure=l.failure)),o.postOpenSettleDurationMs=Math.max(0,Date.now()-s),u)return u;if(d)return{launchConfirmationProbeFailure:d}}async function Ii(e,t,n,r){let i={observed:r,acceptAttempted:!1,confirmationStillPresent:!1};for(let r=0;r<2;r+=1){i=await Li(e,n,i);let a=r===1;if(i.confirmationStillPresent||a||!Bi(i)||!t)break;await t()}return{observed:i.observed,report:i.report,probeFailure:i.probeFailure,unanswered:Bi(i)||i.confirmationStillPresent}}async function Li(e,t,n){let r=await e(),i=r.outcome===`unanswered`&&r.reason===`alert-still-present`,a=n.acceptAttempted||Vi(r),o=zi(n,r);return a?{observed:await t(),...o,acceptAttempted:a,confirmationStillPresent:i}:{observed:n.observed,...o,acceptAttempted:a,confirmationStillPresent:i}}function Ri(e){switch(e.outcome){case`accepted`:return{seen:{launchConfirmation:`accepted`}};case`absent`:return{};case`unreadable`:return e.step===`url-owner`?{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:`url-owner-unresolved`}}:{probeFailure:e.step};case`unanswered`:return e.reason===`alert-still-present`?{}:{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:e.reason}}}}function zi(e,t){let n=Ri(t);return`seen`in n?{report:n.seen,probeFailure:void 0}:`probeFailure`in n?{report:void 0,probeFailure:n.probeFailure}:{report:e.report,probeFailure:void 0}}function Bi(e){return e.acceptAttempted&&Oi(e.observed)}function Vi(e){return e.outcome===`accepted`||e.outcome===`unanswered`&&e.reason===`alert-still-present`||e.outcome===`unreadable`&&e.step===`alert-accept`}async function Hi(e,t,n,r){if(!(!n||!F(e.device))&&!(!r||!t.appBundleId))return await r.awaitObservable(e.device,t.appBundleId,e.signal)}let Ui;const Wi=()=>Ui??=import(`./launch-confirmation.js`);let Gi;const Ki=()=>Gi??=import(`./expo-dev-client-launch.js`);function qi(e){let t=t=>ot({device:t,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve}),n=e.device,r=t(n),i=e=>{n=e,r=t(e)};return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(n,t),prepareApplicationOpen:async t=>{let r=await N(e.host,n,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(n,t.execution,e.signal).catch(()=>{})}:void 0});i(r)},openApplication:async t=>await Ji(e.host,r,t,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(n,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(n,t),closeApplication:async t=>{t.ensureReady&&i(await N(e.host,n,e.signal)),await sa(e.host,r,t)},finalizeApplicationClose:async t=>await ca(e.host,n,e.signal,t),prepareAppleRunner:async t=>{let r=await la(e.host,n,e.signal,t);return i(r.readied),r.prepared},configureProviderPortReverse:ha})}async function Ji(e,t,n,r){let i={},a=I(t.device),o=ua(e,t,n,i),s=Ni(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),Pi(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=oa(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Yi(e,t,n,a,l,i);let u=await Xi(t,n,a,i),d=fa(t.device,u?{...n,runtimeLaunchUrl:u}:n,a);await Zi(o,c,n.prewarmRunnerBeforeOpen);let f=o.wasAwaited();await Qi(t,n,d,a,i),await ra(o,c,s.awaitPrewarmAfterOpen),await ia(e,t,n,a,f,l);let p=await Fi(e,t,n,a,{observation:r,answerConfirmation:ta(t,n,d),redispatchLaunchUrl:na(t,n,d)},i);return{appBundleId:n.appBundleId,timing:i,...p??{}}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Yi(e,t,n,r,i,a){if(!aa(n,r)||!n.target)return;let o=Date.now();se(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await st({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=L(o)}async function Xi(e,n,r,i){if(!Te(n.runtimeHints))return;let a=Date.now(),o=r?await(await Ki()).resolveExpoDevClientLaunchUrl(e.device,n):void 0;if(!o){if(!n.applyRuntimeHints)throw new t(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await n.applyRuntimeHints({appId:n.appBundleId,values:n.runtimeHints})}return i.runtimeHintsDurationMs=L(a),o}async function Zi(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Qi(e,t,n,r,i){let a=Date.now();await ct({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:n.positionals,appBundleId:t.appBundleId,execution:t.execution,...r&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),i.openDispatchDurationMs=L(a),await $i(e,t,n.followUpUrl,i)}async function $i(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i=Date.now();await ea(e,t,n),r.launchUrlDurationMs=L(i)}async function ea(e,t,n){let r={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0};await ct({device:e.device,interactor:await e.resolveInteractor(r,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:r})}function ta(e,t,{confirmation:n}){if(n)return async()=>{let{answerSimulatorLaunchConfirmation:r}=await Wi();return await r(e.device,n,e.resolveInteractor(t.execution,n.appBundleId),e.signal)}}function na(e,t,{confirmation:n}){if(n)return async()=>{await ea(e,t,n.url)}}async function ra(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function ia(e,t,n,r,i,a){!g(t.device)||!r&&!a||!n.relaunch&&!i||r&&!i&&!await e.appleApplications.hasLiveRunnerSession(t.device,n.execution)||await e.appleApplications.notifyRunnerAppRelaunched(t.device,n.execution,t.signal)}function aa(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function oa(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&aa(t,n)}async function sa(e,t,n){se(t.device.platform)&&!I(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await st({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),I(t.device)&&await e.clock.sleep(300,t.signal)}async function ca(e,t,n,r){r.daemonShutdown||await e.appleApplications.releaseRunnerOnClose(t.id,{retain:r.retainRunner}),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{});let i=r.shutdownTarget&&I(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function la(e,t,n,r){let i=Date.now()+r.timeoutMs,a=performance.now();return await te(`prepare_apple_runner`,async()=>{let o=await N(e,t,n,{deadlineAtMs:i}),s=Math.max(1,i-Date.now());return h({phase:`prepare_apple_runner`,durationMs:performance.now()-a,data:{event:`runner_start`,timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}}),{readied:o,prepared:await e.appleApplications.prepareRunner(o,{...r,timeoutMs:s},n)}},()=>({timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}),`readiness_start`)}function ua(e,t,n,r){let i,a=!1,o=da(t.device,n)?{healthCheck:!1}:void 0;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,o?e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a,o):e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=L(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function da(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function fa(e,t,n){let r=t.runtimeLaunchUrl?.trim(),i=t.positionals.length===1?t.positionals[0]?.trim():void 0;if(!r||!i||l(i))return{positionals:t.positionals};let a=pa(e,t.appBundleId,r),o=a?{confirmation:a}:{};return n&&!ma(t)?{positionals:[i,r],...o}:{positionals:t.positionals,followUpUrl:r,...o}}function pa(e,t,n){if(e.appleOs===`ios`&&e.kind===`simulator`&&!(t===void 0||s(n)))return{url:n,appBundleId:t}}function ma(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function I(e){return g(e)&&e.kind===`simulator`}function L(e){return Math.max(0,Date.now()-e)}async function ha(){throw new t(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const ga=Object.freeze({available:!0}),_a=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`}),va=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),ya=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ba=Object.freeze({available:!1,reason:`unsupported-device-kind`});function xa(e){let t=Aa(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:ja(e),uninstallApp:t})}function Sa(e){let{host:t,device:n,signal:r}=e,i=xa(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await Ca(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Ta(t,n,e,r),uninstallApp:async e=>await wa(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Oa(t,n,e,r),{})}:{}})}async function Ca(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Da(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Ea(e,t,a.installablePath,r),{bundleId:i,launchTarget:i}}finally{await a.cleanup()}});let i=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Ta(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function wa(e,n,r,i){return await e.appleDeployment.withInvalidatedAppResolutionCache(n,async()=>{await N(e,n,i);let a;try{a=await e.appleDeployment.resolveAppBundleId(n,r.app,{installedOnly:!0})}catch(e){if(e instanceof t&&e.code===`APP_NOT_INSTALLED`&&r.app.trim().includes(`.`))return{wasInstalled:!1};throw e}return await Da(e,n,a,i),{wasInstalled:!0,bundleId:a}})}async function Ta(e,t,n,r){return await Ea(e,t,n.artifact.installablePath,r),{...n.artifact.bundleId?{bundleId:n.artifact.bundleId}:{},...n.artifact.appName?{appName:n.artifact.appName}:{},...n.artifact.bundleId?{launchTarget:n.artifact.bundleId}:{}}}async function Ea(e,t,n,r){await N(e,t,r),await ka(e,t.kind===`simulator`?{tool:`simctl`,args:x(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:Jt},r,`Apple app install failed`)}async function Da(e,t,n,r){await N(e,t,r),await ka(e,t.kind===`simulator`?{tool:`simctl`,args:x(t,[`uninstall`,t.id,n])}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n]},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>en(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function Oa(e,n,r,i){if(n.kind!==`simulator`)throw new t(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await N(e,n,i);let a=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),await ka(e,{tool:`simctl`,args:x(n,[`push`,n.id,r.appId,a.path])},i,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}async function ka(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:f(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:$t(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function Aa(e){return Ma(e)?e.kind!==`simulator`&&e.kind!==`device`?ba:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?_a:ga:ya}function ja(e){return Ma(e)?e.kind===`simulator`?ga:va:ya}function Ma(e){return g(e)&&e.appleOs!==`watchos`}const R=Object.freeze({available:!0}),Na=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),Pa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Fa(e){return e.kind!==`simulator`&&e.kind!==`device`?Na:_(e)===`watchos`?Pa:R}const Ia=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),La=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ra=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function za(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=_(e);return n===`macos`||n===`watchos`?La:R}function z(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=_(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const Ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),Va=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ha(e){return e.kind!==`simulator`&&e.kind!==`device`?Ba:z(e)?R:Va}const Ua=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function Wa(e){return(e.kind===`simulator`||e.kind===`device`)&&ie(e)?R:Ua}const B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ga=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS`});function Ka(e){return z(e)?Ga:B}function qa(e){return z(e)?R:B}function Ja(e){return z(e)?R:B}const Ya=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Xa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),Za=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.`});function Qa(e){return e.kind!==`simulator`&&e.kind!==`device`?Xa:ce(e)?R:Za}function $a(e){return Object.freeze({...Ge({back:Fa(e)}),...Qe({unsupported:Ya,home:za(e,Ia),appSwitcher:za(e,Ra),actionButton:Qa(e)}),...tt({orientation:Ha(e)}),...rt({tvRemote:Wa(e)}),...et({unsupported:B,status:Ka(e),dismiss:qa(e),enter:Ja(e)})})}function eo(e){let{host:t,device:n,signal:r,admitted:i}=e,a=Object.keys($a(n));return ut({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Object.fromEntries(a.map(e=>[e,i[e]]))})}const V=Object.freeze({available:!0}),to=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),no=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),ro=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`settings is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),io=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Run `agent-device settings --help` for the settings each target serves."}),ao=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The macOS host supports settings appearance and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>.`}),oo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Select a booted iPhone or iPad simulator: this setting runs only there.`}),so=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`clipboard is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),co=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function lo(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=_(e);return r===`watchos`?co:e.kind===`simulator`||r===`macos`?V:n}function uo(e){return lo(e,to,so)}const fo=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),po=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),mo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function ho(e){if(e.kind!==`simulator`&&e.kind!==`device`)return po;let t=_(e);return t===`watchos`?co:e.kind===`simulator`||t===`ios`||t===`macos`?V:mo}function go(e){return e.kind!==`simulator`&&e.kind!==`device`?fo:_(e)===`watchos`?co:V}function _o(e){let t=uo(e);return t.available?so:t}function vo(e){let t=lo(e,no,ro);if(v(e))return lt({target:t,unsupported:ao,write:{appearance:V,permission:V}});let n=oe(e)?V:oo;return lt({target:t,unsupported:io,write:{wifi:V,airplane:V,location:V,appearance:V,"clear-app-state":V,"reset-keychain":V,permission:V,"text-size":n,faceid:n,touchid:n},read:{"text-size":n}})}function yo(e){let t=uo(e),n=ho(e);return Object.freeze({...nt({unsupported:_o(e),read:t,write:t}),...Ze({read:n,wait:n,accept:n,dismiss:n}),...Xe({triggerAppEvent:go(e)}),...vo(e)})}function bo(e){let{host:t,device:n,signal:r}=e;return ut({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:yo(n)})}const xo=/Angle:\s*(-?\d+(?:[.,]\d+)?)\s*°/g;async function So(e,n={}){let r=[`devicectl`,`device`,`motion`,`hinge-angle`,`--device`,e.id,`--session-timeout`,`1`,`--timeout`,`5`],i=await Qt(r,{allowFailure:!0,signal:n.signal,timeoutMs:Xt}),a=Co(i.stdout)??Co(i.stderr);if(a!==void 0)return a;throw new t(`COMMAND_FAILED`,`CoreDevice reported no hinge angle sample`,d(i,{cmd:`xcrun`,args:r,stdout:i.stdout,stderr:i.stderr,deviceId:e.id,reason:`fold-hinge-angle-no-sample`,hint:`'devicectl device motion hinge-angle' printed no sample, and foldable poses can be verified only through that stream. The stderr in the details names the cause, such as a devicectl without the subcommand or a device CoreDevice cannot reach.`}))}function Co(e){let t;for(let n of e.matchAll(xo)){let e=Number.parseFloat(n[1].replace(`,`,`.`));Number.isFinite(e)&&(t=e)}return t}var H=class extends t{buildFailureKind;buildFailureCode;buildDetails;constructor(e,t,n=`native build ${e}: ${t}`,r={},i){super(`COMMAND_FAILED`,n,{...r,nativeBuildFailure:e,nativeBuildFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`NativeBuildError`,this.buildFailureKind=e,this.buildFailureCode=t,this.buildDetails=r}};function U(e,t,n={},r){return new H(e,t,void 0,n,r)}function wo(e,t,n=Date.now){if(t?.aborted)throw U(`cancelled`,`abort-signal`);return{clock:m.fromTimeoutMs(e,n()),now:n,signal:t}}function W(e,t){if(e.signal?.aborted)throw U(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw U(`timeout`,t);return Math.max(1,Math.floor(n))}function To(e){return{run:e,readText:Vt,readBinary:Wt,writeText:zt,ensureDirectory:Kt,chmod:Gt,exists:Ht,rename:Bt,remove:qt,acquireLock:Eo,processId:re,cpuArch:ee}}async function Eo(e,t){let n=re(),r=t.deadline,i=he({lockDirPath:e,owner:{pid:n,startTime:ne(n),acquiredAtMs:Date.now()},timeoutMs:W(r,`cache-lock-deadline`),pollMs:100,description:t.description}),a=r.signal;if(!a)try{return await i}catch(e){throw Do(e,r)}let o=!1,s,c=new Promise((e,t)=>{s=()=>{o=!0,t(U(`cancelled`,`abort-signal`))},a.addEventListener(`abort`,s,{once:!0}),a.aborted&&s()});try{return await Promise.race([i,c])}catch(e){throw o&&i.then(e=>e().catch(()=>void 0),()=>void 0),Do(e,r)}finally{a.removeEventListener(`abort`,s)}}function Do(e,t){return t.clock.isExpired()&&!(e instanceof H&&e.buildFailureKind===`cancelled`)?U(`timeout`,`cache-lock-deadline`):e}async function Oo(e,t){let n=await Ao(e,`xcodebuild`,[`-version`],t),r=await Ao(e,`sw_vers`,[`-productVersion`],t),i=await Ao(e,`sw_vers`,[`-buildVersion`],t),a=await ko(e,t);if(a!==`arm64`&&a!==`x86_64`)throw U(`unsupported`,`simulator-architecture-unsupported`,{architecture:a});return{xcode:n,macosProductVersion:r,macosBuild:i,architecture:a}}async function ko(e,t){let n=W(t,`host-arch-deadline`),r=t.signal,i,a,o=new Promise((e,t)=>{i=setTimeout(()=>t(U(`timeout`,`host-arch-deadline`)),n),i.unref?.(),a=()=>t(U(`cancelled`,`abort-signal`)),r?.addEventListener(`abort`,a,{once:!0})});try{return await Promise.race([e.cpuArch(),o])}finally{clearTimeout(i),a&&r?.removeEventListener(`abort`,a)}}async function Ao(e,t,n,r){let i=await jo(e,t,n,r);if(i.exitCode!==0)throw U(`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 U(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function jo(e,t,n,r){let i=[],a;for(let o=1;;o+=1){let s;try{s=Math.min(tn,W(r,`toolchain-probe-deadline`))}catch(e){throw a??e}i.push(s);try{return await Po(e,t,n,r,s)}catch(e){if(a=Mo(e,t,r,i),o>=2)throw a}}}function Mo(e,t,n,i){if(r(e))throw U(`cancelled`,`abort-signal`,{},e);if(!p(e))throw e;if(n.signal?.aborted)throw U(`cancelled`,`abort-signal`);return No(t,i,e)}function No(e,t,n){let r=t.length;return U(`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 Po(e,t,n,r,i){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:i})}const Fo=`manifest.json`;async function Io(e){let{host:t,deadline:n,cacheRoot:r,binaryFilename:i}=e,a=pn(`sha256`).update(JSON.stringify(e.keyInputs)).digest(`hex`).slice(0,32),o=S.join(r,a);return await me({acquire:()=>t.acquireLock(S.join(r,`${a}.lock`),{deadline:n,description:e.lockDescription}),task:async()=>{let s=await Lo(t,o,i,a,n);if(s)return{path:s,cacheKey:a};W(n,`native-build-deadline`),t.exists(o)&&await t.remove(o),W(n,`native-build-deadline`),await t.ensureDirectory(r);let c=S.join(r,`.${a}.${t.processId()}.tmp`);W(n,`native-build-deadline`),await t.remove(c);try{W(n,`native-build-deadline`),await t.ensureDirectory(c);let r=S.join(c,i);await e.build(r),W(n,`native-build-deadline`),await t.chmod(r,493);let s=await zo(t,r),l={...e.keyInputs,cacheKey:a,binarySha256:s};return await t.writeText(S.join(c,Fo),`${JSON.stringify(l,null,2)}\n`),W(n,`native-build-deadline`),await t.rename(c,o),{path:S.join(o,i),cacheKey:a}}catch(e){throw await t.remove(c),e}}})}async function Lo(e,t,n,r,i){let a=S.join(t,n),o=S.join(t,Fo);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:(W(i,`native-cache-hash-deadline`),await zo(e,a)===t.binarySha256?a:void 0)}catch(e){if(Ro(e))throw e;return}}function Ro(e){return e instanceof H&&(e.buildFailureKind===`cancelled`||e.buildFailureKind===`timeout`)}async function zo(e,t){return pn(`sha256`).update(await e.readBinary(t)).digest(`hex`)}async function Bo(e,t,n,r){let i=pn(`sha256`);for(let a of n){let n=S.join(t,a);if(W(r,`native-source-fingerprint-deadline`),!e.exists(n))throw U(`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 Vo(e){let t=Math.min(e.budgetMs,W(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 p(n)?U(`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}}const Ho=`Fold.m`,Uo=3e4,Wo=tn+Uo;async function Go(e={}){let t=e.host??Ko(),n=wo(Wo,e.signal);try{let r=e.sourceRoot??S.join(ge(),`apple`,`fold-helper`),i=await Bo(t,r,[Ho],n),a=await Oo(t,n);return await Io({host:t,deadline:n,lockDescription:`iOS Simulator fold helper cache`,cacheRoot:e.cacheRoot??S.join(Ut(),`.agent-device`,`fold-helper`),binaryFilename:`fold-helper`,keyInputs:{schemaVersion:1,sourceHash:i,toolchain:a,compileArgv:qo({sourceRoot:``,outputPath:``})},build:e=>Jo(t,n,r,e)})}catch(e){throw Yo(e)}}function Ko(){return To(Zt)}function qo(e){return[`--sdk`,`iphonesimulator`,`clang`,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`IOKit`,S.join(e.sourceRoot,Ho),`-o`,e.outputPath]}async function Jo(e,t,n,r){let i=await Vo({host:e,deadline:t,argv:qo({sourceRoot:n,outputPath:r}),budgetMs:Uo,label:`fold helper`});if(i.exitCode!==0||!e.exists(r))throw Xo(d(i))}function Yo(e){return!(e instanceof H)||e.buildFailureKind===`cancelled`?e:Xo({...e.buildDetails,cause:e.buildFailureCode},e)}function Xo(e,n){return new t(`COMMAND_FAILED`,`Unable to build the simulator fold helper`,{hint:`Select an Xcode with the iOS simulator SDK and foldable HID support using DEVELOPER_DIR.`,...e,reason:`fold-helper-build-failed`},n)}async function Zo(e,n,r){r?.throwIfAborted();let i=await Go({signal:r});r?.throwIfAborted();let a=typeof n==`string`?0:n.at(-1).atMs,o=typeof n==`string`?n:JSON.stringify(n),s=await on(e,[`spawn`,e.id,i.path,o],{signal:r,timeoutMs:a+1e4,kill:{signal:`SIGTERM`,graceMs:1e3},allowFailure:!0});if(s.exitCode!==0)throw new t(`COMMAND_FAILED`,`Unable to send the simulator hinge pose`,d(s,{reason:`fold-hid-dispatch-failed`,deviceId:e.id}))}async function Qo(e,t,n={}){n.signal?.throwIfAborted(),cn(e,`fold`);let r=t,i=r.keyframes?.at(-1)?.angle,a=r.pose??o(i);ts(e,await ln(e,{signal:n.signal})),await Zo(e,r.keyframes??a,n.signal),h({level:`info`,phase:`apple_fold_pose_dispatched`,data:{deviceId:e.id,pose:a}});let s=await ns(e,a,n.signal,i),c=await ds(e,n.signal);return{pose:o(s),hingeAngleDegrees:s,...c?{screen:fs(c)}:{}}}function $o(e){return e instanceof t&&e.details?.reason===`fold-hinge-angle-no-sample`}async function es(e,n,r,i,a){let o=await ds(e,r);return new t(`COMMAND_FAILED`,`${e.name} received the ${n} pose request, but the first hinge-angle read returned no sample to verify it`,{deviceId:e.id,requestedPose:n,...i===void 0?{}:{targetAngleDegrees:i},reason:`fold-pose-dispatched-unverified`,...o?{screen:fs(o)}:{},...a instanceof t?{hingeReadFailure:a.details}:{},hint:`The pose request was sent and the device may have followed it, but the first hinge-angle read returned no sample, so fold cannot confirm it. Take a screenshot or snapshot to see which panel is lit; hingeReadFailure names why the read failed.`},a)}function ts(e,n){if(n.unresolved)throw new t(`COMMAND_FAILED`,`CoreDevice reported no display table for this simulator`,{deviceId:e.id,hint:`fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.`});if(!n.multiScreen)throw new t(`UNSUPPORTED_OPERATION`,`${e.name} is not a foldable simulator: fold requires more than one integrated panel`,{deviceId:e.id,reason:`single-panel-device`,hint:`fold sets the hinge angle of a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.`})}async function ns(e,t,n,r){let i,a;for(let o=1;o<=4;o+=1){n?.throwIfAborted(),a=i;try{i=await So(e,{signal:n})}catch(a){throw i!==void 0||!$o(a)?a:await es(e,t,n,r,a)}if(rs(i,a,t,r))return i}throw os(e,t,i,a,r)}function rs(e,t,n,r){return r===void 0?o(e)===n?n!==`half-open`||t!==void 0&&ss(e,t):!1:is(e,t,r)}function is(e,t,n){return as(e,n)?n===0||n===180||t!==void 0&&as(t,n)&&Math.abs(e-t)<=.5:!1}function as(e,t){return t===void 0||e!==void 0&&Math.abs(e-t)<=.5}function os(e,n,r,i,a){return as(r,a)?a!==void 0&&r!==void 0?us(e,o(r),r,i):r!==void 0&&n===`half-open`&&o(r)===n?us(e,n,r,i):ls(e,n,r):new t(`COMMAND_FAILED`,`The hinge did not reach the final keyframe angle`,{reason:`fold-angle-unverified`,targetAngleDegrees:a,hingeAngleDegrees:r,deviceId:e.id})}function ss(e,t){return o(e)===`half-open`&&o(t)===`half-open`&&Math.abs(e-t)<=.5}function cs(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:o(n),hingeAngleDegrees:n}}function ls(e,n,r){return new t(`COMMAND_FAILED`,`${e.name} did not reach the ${n} pose: CoreDevice still reports a hinge angle of ${r}°`,{...cs(e,n,r),reason:`fold-pose-unverified`,hint:`The simulator HID command completed, but the hinge did not follow. Verify that the selected Xcode and simulator runtime support foldable HID control, then retry.`})}function us(e,n,r,i){return new t(`COMMAND_FAILED`,`${e.name} was observed ${n} at ${r}° but did not settle: 4 hinge reads never held two consecutive angles within ${Yt}° of each other`,{...cs(e,n,r),reason:`fold-pose-unsettled`,...i===void 0?{}:{previousHingeAngleDegrees:i},hint:`The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.`})}async function ds(e,t){let n=await ln(e,{signal:t});if(!(n.unresolved||n.ambiguous))return n.activeDisplay}function fs(e){return{display:e.name,coordinateSpace:a,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const ps=Object.freeze({available:!0}),ms=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold is supported on foldable iPhone simulators controlled through simulator HID; a physical device is folded by hand.`}),hs=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.`});function gs(e){return{available:!1,reason:`unsupported-device-scope`,hint:`fold cannot resolve a simulator scoped to the set at "${e}": CoreDevice's display inventory and hinge-angle readback need a simulator in the default set, so the pose could not be verified. Run fold without --ios-simulator-device-set.`}}function _s(e){if(e.kind!==`simulator`)return ms;let t=_(e);return t!==`ios`&&t!==`ipados`?hs:e.simulatorSetPath?gs(e.simulatorSetPath):ps}function vs(e){return At({fold:_s(e)})}function ys(e){let{device:t,signal:n}=e;return y(vs(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await Qo(t,e,{signal:n}))}))}function bs(e,t,n){let r=We({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(i.options?.observeOnly===!0)return await r.captureSnapshot(i);let a=v(t.device)?fe(i.options?.surface,t.appBackend):void 0;if(a)return await e.snapshot.captureSurface(t.device,{...i.options,surface:a},Ne(t.signal,i));if(!n)return await r.captureSnapshot(i);let o=Ne(t.signal,i);return await n.capture(t.device,i,o,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function xs(e,t){return Object.freeze({findText:async n=>{let r=await Ss(e,t,n);if(!r)return{found:!1};let i=await e.localInteractors.resolve(t.device,{...n.execution,...r});return i.findText?await i.findText(n.text,r):{found:!1}}})}async function Ss(e,t,n){let r=n.options?.appBundleId;if(r===void 0||v(t.device)&&pe(n.options?.surface,t.appBackend)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await Cs(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function Cs(e,t,n){return!F(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function ws(e){return Object.freeze({querySelector:async t=>{let n=t.signal?AbortSignal.any([e.signal,t.signal]):e.signal;n.throwIfAborted();let r={...t.execution,signal:n},{queryAppleRunnerSelector:i}=await import(`./runner-selector-query.js`),a=await i(e.device,t.selector,t.options?.appBundleId,r),o=Ts(a);return Object.freeze({found:a.found===!0,...o?{node:o}:{}})}})}function Ts(e){let t=e.nodes;if(!Array.isArray(t))return;let n=t[0];if(!n||typeof n!=`object`)return;let r=c(n.rect);if(r)return Object.freeze({rect:r,hittable:n.hittable===!0})}const G=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.`});function Es(e,t){return!v(e)||t!==`native`?{}:Object.freeze({screenRecordingStart:G,screenRecordingReattach:G,prepareAppleRunner:G,longPressPoint:G,...Ge({back:G}),...Le({unsupported:G})})}function Ds(e){let t,n=!1,r=async()=>(t??=import(`./host2.js`).then(e=>e.t).then(({createSnapshotSourceHost:t})=>import(`./adapter.js`).then(({createSimulatorSnapshotSource:n})=>n({host:t(e)}))),await t);return{acquire:async e=>n?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await r()).acquire(e),close:async()=>{n=!0,t&&await(await t).close()}}}function Os(e=Date.now){let t=new Map;return async(n,r)=>{if(n.kind!==`simulator`)return`absent`;let i=t.get(n.id);if(i!==void 0&&e()-i.at<1e3)return{kind:`present`,host:i.host};t.delete(n.id);let a=await ks(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function ks(e,t){let n=await Promise.all(je.map(async e=>({host:e,pids:await As(e.processExecutable,t)}))),r=!1;for(let{host:i,pids:a}of n){if(a===`unknown`){r=!0;continue}for(let n of a){let a=await js(n,e.id,t);if(a===`unknown`)r=!0;else if(a)return{kind:`present`,host:i}}}return r?`unknown`:`absent`}async function As(e,t){let n=await Ms(`pgrep`,[`-f`,e],t);return n===`unknown`?`unknown`:n.exitCode===1?[]:n.exitCode===0?n.stdout.split(`
5
- `).map(e=>Number.parseInt(e.trim(),10)).filter(e=>Number.isSafeInteger(e)&&e>0):`unknown`}async function js(e,t,n){let r=await Ms(`ps`,[`eww`,`-p`,String(e),`-o`,`command=`],n);return r===`unknown`||r.exitCode!==0?`unknown`:r.stdout.includes(`SIMULATOR_UDID=${t}`)?!0:!r.stdout.includes(`SIMULATOR_UDID=`)&&`unknown`}async function Ms(e,t,n){try{let r=await Zt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Ns=`system-surface-presented`,Ps=`system-surface-host-lingering`,Fs=`window-coordinate-space-unresolved`;function Is(e,n={}){let r=n.source??Ds(e.hostEnvironment),i=n.resolveTarget??bi(),a=n.systemSurfacePresent??Os(),o=new Set,s=new Map,c=e=>(Zs(e,s,o),o.has(Qs(e))),l=Ai({source:r,resolveTarget:i,clock:e.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(n,s,l,u)=>{if(!zs(n,s))return await Us(n,s,u);let d=await a(n,l);if(d===`unknown`)return await K(n.id,s,u,Gs(n.id,s),q(s),`system-surface-probe-unavailable`,[Xs()]);if(d!==`absent`)return await Hs(n,s,u,d.host.bundleId);let f;try{f=await Ls(e,i,n,s,l)}catch(e){return Rs(l,e),J(`target-resolution-failed`,n,void 0,e),await K(n.id,s,u,Gs(n.id,s),q(s),`target-resolution-failed`,[Xs()])}if(c(f))return J(`circuit-disabled`,n,f.generation),await K(n.id,s,u,f,q(s),`circuit-disabled`);let p=q(s),m=await r.acquire({target:f,hint:_e(p),signal:l});if(m.stage===`failed`){if(m.failure.kind===`cancelled`)throw l.throwIfAborted(),new t(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:m.failure.code,...m.failure.details});let e=await Ys(m.failure,f,n,s.options.appBundleId,l,i);return await Bs(s,u,f,e,p,m.failure,o)}try{return await te(`ios.snapshot-source.present`,async()=>await e.snapshot.presentIosAcquisition(m,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await Bs(s,u,f,{lineage:f,residue:[]},p,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Ls(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!Si(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function Rs(e,t){if(e.aborted)throw r(t)?t:e.reason}function zs(e,t){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&!!t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0}async function Bs(e,t,n,r,i,a,o,s){return Vs(a)&&o.add(Qs(n)),J(a.code,{id:n.simulator.udid},n.generation,s,a.details),await K(n.simulator.udid,e,t,r.lineage,i,a.code,r.residue)}function Vs(e){return e.kind!==`preparing`&&e.code!==Fs}async function K(e,t,n,r,i,a,o=[]){return Ws(e,await n(t),r,i,a,o)}async function Hs(e,t,n,r){let i=await n(t),a=i.systemSurface?Ns:Ps;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),Ws(e.id,i,Gs(e.id,t),q(t),a)}async function Us(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:qs(Ks(e.id,i.bundleId),q(t),[])}:r}function Ws(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:qs(o?Ks(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],Js(i,n,o!==void 0)]}}function Gs(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function Ks(e,t){return{targetId:`${e}:${t}`}}function qs(e,t,n){return Object.freeze({producer:`apple-runner`,intent:t.acquisitionIntent,lineage:Object.freeze({...e.targetId?{targetId:e.targetId}:{},...e.generation?{generation:e.generation}:{}}),presentationKey:ve(t),residue:Object.freeze([...n])})}function Js(e,t,n){return e===Ns?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Ps?`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`:n?`Simulator AX snapshot unavailable (${e}); used XCTest, which read the system surface presented over the app.`:e===`bridge-preparation-pending`?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture while the bridge is still being prepared.`:e===Fs?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture, which reports captured geometry in the app's own orientation space.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function Ys(e,t,n,r,i,a){if(e.kind!==`stale-target`)return{lineage:t,residue:[]};try{return{lineage:await a(n,r,i,`refresh`),residue:[]}}catch(e){return i.throwIfAborted(),J(`fallback-target-resolution-failed`,n,void 0,e),{lineage:{targetId:t.targetId},residue:[Xs()]}}}function Xs(){return{kind:`unknown-generation`,captureId:mn()}}function q(e){return ye({raw:e.options?.raw,interactiveOnly:e.options?.interactiveOnly,depth:e.options?.depth,scope:e.options?.scope,customActions:e.options?.customActions,acquisitionIntent:e.options?.acquisitionIntent})}function Zs(e,t,n){let r=t.get(e.targetId);r&&r!==e.generation&&n.delete(`${e.targetId}:${r}`),t.set(e.targetId,e.generation)}function Qs(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){h({level:`debug`,phase:`ios_snapshot_route_fallback`,data:{reason:e,deviceId:t.id,...n?{generation:n}:{},...r?{error:r instanceof Error?r.message:String(r)}:{},...i?{details:i}:{}}})}const Y=le(`apple`),X=Object.freeze({available:!0}),Z=b(`unsupported-platform-leaf`),$s=b(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`),ec=b(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`),tc=b(`unsupported-device-backend`,`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`),nc=b(`unsupported-device-kind`,`focus is supported on Apple simulators and physical devices.`),rc=b(`unsupported-platform-leaf`,`telephony simulates calls and SMS through the Android emulator console; Apple simulators and devices expose no host control that injects a call or text message.`),ic=b(`unsupported-platform-leaf`,`Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`);function ac(e){return!g(e)||e.appleOs===`watchos`?ic:e.kind===`simulator`||e.kind===`device`?X:ic}const oc=b(`unsupported-provider-mode`,`Headless boot is supported only for local Android emulators.`),sc=b(`unsupported-platform-leaf`,`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`),cc=b(`unsupported-device-kind`),lc=b(`unsupported-platform-leaf`,`watchOS open is not supported because XCUITest cannot drive watchOS UI.`),uc=b(`unsupported-platform-leaf`,`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`),dc=b(`unsupported-platform-leaf`,`watchOS close is not supported because XCUITest cannot drive watchOS UI.`),fc=b(`unsupported-device-kind`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),pc=Q(`open is supported only for Apple simulators and devices.`),mc=Q(`prepare is supported only for Apple simulators and devices.`),hc=Q(`close is supported only for Apple simulators and devices.`),gc=b(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),_c=b(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),vc=Q(`snapshot is supported only for Apple simulators and devices.`),yc=b(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),bc=b(`unsupported-platform-leaf`,`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`),xc=Q(`screenshot is supported only for Apple simulators and devices.`),Sc=b(`owner-capability-missing`,`Open the app under test before capturing its snapshot.`);function Q(e){return b(`unsupported-device-kind`,e)}function Cc(e){return!g(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:_c}function wc(e){let t=Tc(e),n=Ec(e),r=Dc(e),i=Oc(e);return Ee({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:gc})}function Tc(e){return _(e)===`watchos`?lc:e.kind===`simulator`||e.kind===`device`?X:pc}function Ec(e){return _(e)===`watchos`?uc:e.kind===`simulator`||e.kind===`device`?X:mc}function Dc(e){return _(e)===`watchos`?dc:e.kind===`simulator`||e.kind===`device`?X:hc}function Oc(e){return _(e)!==`watchos`&&g(e)&&e.kind===`simulator`?X:fc}function kc(e){return e.appleOs===`watchos`?b(`unsupported-platform-leaf`,`watchOS app inventory is not supported.`):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?b(`unsupported-device-backend`,`App inventory is available only on CoreDevice-backed physical iOS devices.`):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:nc}function Ac(e){let t=$n(e),n=Is(e),r,i=t=>v(t)?r??=dn(e.hostEnvironment.env):`xctest`,a=async n=>{let r=await t.inspectFacts(n),a=xa(n),o=Hr(n),s=o.available?await e.screenRecording.apple.availability(n):void 0,c=o.available&&s?.available===!1?b(`unsupported-provider-mode`,s.hint):o,l=n.appleOs===`watchos`?Z:X,u=v(n)||n.appleOs===`watchos`?Z:X,d=kc(n);return Object.freeze({device:r.device,operations:{...r.operations,...a,appState:ac(n),networkDump:X,screenRecordingStart:c,screenRecordingReattach:c,screenRecordingCleanup:c,...Fc(n),...Ie({capture:Pc(n)}),...He({findText:Nc(n),querySelector:g(n)?$(n):Z}),...it({setViewport:$s}),...ze({focus:$(n)}),...Sn(n),...Fe({type:$(n)}),...ke({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...g(n)?{tapElementSelector:$(n)}:{}}),...Je({readTextAtPoint:Mc(n)}),...$a(n),...vs(n),sendTelephonyEvent:rc,...yo(n),...at({capture:gn(n),query:ec}),...Ve(jc(n)),ensureReady:l,bootTarget:u,bootTargetHeadless:oc,listApps:d,...wc(n),shutdownTarget:Cc(n),...Es(n,i(n))}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:a,bind:async r=>{let o=await t.bind(r),s=await a(r.device),c=s.operations.screenRecordingStart,l=y(s.operations.appState,()=>hn(e,{device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),u=y(s.operations.querySelector,()=>ws({device:r.device,signal:r.scope.signal})),d={...l,...u,...o.operations,...Sa({host:e,device:r.device,signal:r.scope.signal}),networkDump:async t=>await rr(e,r.device,t,r.scope.signal),...y(c,()=>Ur({host:e,device:r.device,owner:Y,signal:r.scope.signal})),...y(s.operations.audioProbeStart,()=>vt({host:e.audioProbe.hostCapture,device:r.device,owner:Y})),...y(s.operations.perfFrames,()=>_n({resolveHost:()=>e.perf.apple,device:r.device,owner:Y})),...y(s.operations.captureSnapshot,()=>bs(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)},n)),...y(s.operations.captureScreenshot,()=>Ue({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...y(s.operations.focusPoint,()=>Be({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...qe({device:r.device,signal:r.scope.signal,facts:s.operations,resolveInteractor:e.localInteractors.resolve}),...y(s.operations.scrollDirection,()=>Pe({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...y(s.operations.typeText,()=>Ke({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...y(s.operations.tapPoint,()=>Ae({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:s.operations,pause:async t=>await e.clock.sleep(t,r.scope.signal)})),...y(s.operations.readTextAtPoint,()=>Ye({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...y(s.operations.findText,()=>xs(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)})),...eo({host:e,device:r.device,signal:r.scope.signal,admitted:s.operations}),...bo({host:e,device:r.device,signal:r.scope.signal}),...ys({device:r.device,signal:r.scope.signal}),...y(s.operations.ensureReady,()=>({ensureReady:async()=>await N(e,r.device,r.scope.signal)})),...y(s.operations.bootTarget,()=>({bootTarget:async t=>await N(e,r.device,r.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...y(s.operations.listApps,()=>({listApps:async e=>{r.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...we(qi({host:e,device:r.device,signal:r.scope.signal,observation:n}),s.operations),...y(s.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(r.device,r.scope.signal)}))};return Object.freeze({device:o.device,owner:Y,facts:s,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function jc(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&_(e)!==`watchos`?X:tc;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Mc(e){return _(e)===`watchos`?sc:e.kind===`simulator`||e.kind===`device`?X:cc}function Nc(e){return _(e)===`watchos`?vc:e.kind===`simulator`||e.kind===`device`?X:vc}function Pc(e){return _(e)===`watchos`?bc:e.kind===`simulator`||e.kind===`device`?X:xc}function Fc(e){let t=Nc(e);return $e({capture:t,customActions:t.available&&g(e)&&e.kind===`simulator`?X:yc,withoutActiveApp:g(e)?Sc:t})}export{To as a,H as c,Ac as createApplePlatformRuntime,mi as d,Oo as i,gi as l,Vo as n,wo as o,Bo as r,W as s,Io as t,hi as u};
1
+ import{B as e,R as t,V as n,Z as r,et as i}from"./sdk-contracts.js";import{A as a,l as o,x as s}from"./tv-remote.js";import{a as c,b as l,i as u,v as d}from"./sdk-batch-runner.js";import{G as f,J as p,K as m,L as ee,T as te,bt as ne,ht as h,j as re,y as ie}from"./sdk-io.js";import"./diagnostics.js";import{C as ae,F as oe,_ as g,g as se,j as _,p as ce,u as le,v}from"./sdk-device.js";import{an as ue,cn as de,en as fe,on as y,sn as b}from"./sdk-batch.js";import{n as pe,r as me}from"./session.js";import{a as he,t as ge}from"./file.js";import"./command.js";import{r as _e}from"./version.js";import"./retry.js";import{i as ve,n as ye,r as be}from"./ios-snapshot-planning.js";import{i as xe,n as Se}from"./durable-resource.js";import{n as Ce}from"./screen-recording-runtime.js";import{t as we}from"./request.js";import{n as Te,r as Ee,t as De}from"./application-lifecycle-runtime.js";import{n as Oe,t as ke}from"./async-lifecycle.js";import{i as Ae,t as je}from"./touch-runtime.js";import{t as Me}from"./ios-system-surface.js";import{r as Ne}from"./gesture-admission.js";import{B as Pe,C as Fe,E as Ie,I as Le,K as Re,M as ze,N as Be,O as Ve,P as He,R as Ue,T as We,U as Ge,V as Ke,W as qe,X as Je,Y as Ye,Z as Xe,_ as Ze,j as Qe,k as $e,l as et,o as tt,p as nt,q as rt,r as it,v as at,x as ot}from"./tv-remote-runtime.js";import{n as st,o as ct,s as lt,u as ut}from"./application-lifecycle-interaction.js";import{t as dt}from"./interactor-operation-catalog.js";import{a as ft,i as pt,n as mt,o as ht,r as gt,s as _t,t as vt}from"./network-traffic.js";import{a as yt,i as bt,r as xt}from"./src4.js";import{n as St,t as Ct}from"./screen-recording-completion.js";import{a as wt,c as Tt,i as Et,l as Dt,n as Ot,o as kt,r as At,s as jt,t as Mt}from"./device-readiness-runtime.js";import{a as Nt,i as Pt,n as Ft,r as It,t as Lt}from"./perf-runtime-operation-builder.js";import{t as Rt}from"./app-log-runtime.js";import{n as zt}from"./artifact-paths.js";import{O as Bt,T as Vt,b as Ht,c as Ut,f as Wt,g as Gt,n as Kt,o as qt,w as Jt}from"./host-file.js";import{a as Yt,o as Xt,s as Zt}from"./config.js";import{a as Qt,o as $t}from"./tool-provider.js";import{o as en}from"./devicectl.js";import{t as tn}from"./physical-device-apps.js";import{t as nn}from"./apple-runner-platform.js";import{a as rn,c as an,n as on,o as sn,s as x,u as cn}from"./simctl.js";import{r as ln}from"./simulator.js";import{r as un}from"./display-inventory.js";import{n as dn,t as fn}from"./app-backend.js";import{t as pn}from"./simulator-state.js";import{createHash as mn,randomUUID as hn}from"node:crypto";import S from"node:path";function gn(e,t){return Object.freeze({appState:async n=>{if(t.signal.throwIfAborted(),!await e.appleApplications.hasLiveRunnerSession(t.device,{}))return{};let r=await t.resolveInteractor(t.device,{appBundleId:n?.appBundleId,signal:t.signal});if(typeof r.appState!=`function`)throw de(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function _n(e){return kt(e)?Object.freeze({available:!0}):v(e)||g(e)&&e.kind===`simulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio is supported for macOS sessions and iOS simulators on macOS hosts; physical iOS devices expose no host audio tap.`})}function vn(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Lt({platform:`Apple`,expectedProfileKind:`xctrace`,start:async e=>await t().start(n,r,e),reattach:async e=>await t().reattach(n,e),cleanup:async e=>await t().cleanup(n,e),writeProfileReport:async e=>await t().writeProfileReport(e)}),perfFrames:async({appId:e})=>({metric:e?await Pt(t().sampleFrames(n,e)):Ft(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await Pt(t().sampleMemory(n,e)):Ft(`Apple`,`bundle ID`),sampling:await t().memorySampling(n)}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`memgraph`,s={...await t().memorySnapshotSupport(n),androidHprof:!1,heapprofd:!1};if(o!==`memgraph`)return Nt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw It();let c=i??S.join(a,`memory-memgraph-${yn()}.memgraph`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`xcrun memgraph`,description:`Native Apple memory graph captured for offline inspection.`,defaultKind:`memgraph`,artifactOnly:!0}}}})}function yn(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const C=Object.freeze({available:!0}),w=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),T=Sn(`Gestures are supported only for Apple simulators and devices.`),bn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Ne}),xn=Sn(`scroll is supported only for Apple simulators and devices.`);function Sn(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Cn(e){return{...Re({unsupported:wn(e),plan:Tn(e),directionalFling:Tn(e),multiTouch:En(e),targetAuthoredDrag:Dn(e),viewport:On(e)}),...Ge({scroll:kn(e)})}}function wn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?w:T}function Tn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?w:E(e)?C:T}function En(e){if(e.appleOs===`watchos`)return w;if(!E(e))return T;let t=_(e);if(t!==`ios`&&t!==`ipados`){let e=dn[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return C}function Dn(e){return E(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?C:bn:T}function On(e){return e.appleOs===`watchos`?w:E(e)?C:T}function kn(e){return E(e)?C:xn}function E(e){return e.kind===`simulator`||e.kind===`device`}const D=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function O(e){return v(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const An=Object.freeze({resourceKind:Rt,version:1,encode:e=>({...e}),decode:e=>!Mn(e.transport)||!Nn(e.backend)||!Ln(e.outputPath)||!Fn(e.pidPath)||!Pn(e.transport,e.backend)?jn():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function jn(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function Mn(e){return e===`apple-log-stream`||e===`coredevice-console`}function Nn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Pn(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function Fn(e){return e===void 0||Ln(e)}function In(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return Se({resourceKind:Rt,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:xe(An,e.descriptor)})}function Ln(e){return typeof e==`string`&&e.trim().length>0}const Rn={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},zn={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function Bn(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function Vn(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(v(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await Dt(async()=>Tt(await e.appleTools.run({tool:`simctl`,args:an(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(D);else{i.devicectlAvailable=await Dt(async()=>Tt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await Bn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?Rn:zn;a.push(`${e.message} ${e.hint}`)}}return{backend:O(t),checks:i,notes:a}}function Hn(e,t){let n=Gn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=Gn(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function Un(e,t){return on(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,Hn(t.appBundleId,t.executableName)])}function Wn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function Gn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function Kn(e,t,n,r,i){qn(t),pt(e,n);let a=O(t),o=await Yn(e,t,n.appBundleId,i),s=new ke,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await Jn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=Zn(e,u,l,a,n.outputPath),f={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},p=_t(d,In({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function qn(e){if(e.appleOs===`watchos`)throw new t(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new t(`UNSUPPORTED_OPERATION`,D,{hint:D})}async function Jn(e,n,r,i,a,o){if(g(n)&&n.kind===`device`){let n=await Bn(e,o);if(!n.supported){let e=n.reason===`unsupported`?Rn:zn;throw new t(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,e.message,{backend:`ios-device`,hint:e.hint,stderr:n.stderr})}}return o?.throwIfAborted(),await e.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function Yn(e,t,n,r){return v(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,Hn(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:Wn(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:Un(t,{appBundleId:n,executableName:await Xn(e,t,n,r)}),allowFailure:!0}}async function Xn(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:x(t,[`get_app_container`,t.id,n,`app`]),allowFailure:!0,timeoutMs:4e3},r),a=i.exitCode===0?i.stdout.trim():``;if(!a)return;let o=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,S.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function Zn(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return ft({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Qn([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function Qn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const k=fe(`apple`),$n=Object.freeze({available:!0});function er(e){return Object.freeze({owner:k,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>nr(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!ue(n.intent.owner,k))throw new t(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return tr(e,n.device,n.scope.signal)},shutdown:async()=>void 0})}function tr(e,n,r){if(n.platform!==`apple`)throw new t(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=ht({codec:An,reattach:async(t,r)=>t.backend!==O(n)||!gt(e,r.sessionId,t)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await bt(e,t.pidPath),cleanup:async(t,r)=>t.backend===O(n)&&gt(e,r.sessionId,t)?await xt(e,t.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:O(n)}),appLogDoctor:async({appBundleId:t})=>await Vn(e,n,t,r),appLogStart:async t=>await Kn(e,n,t,k,r),...i});return Object.freeze({device:n,owner:k,facts:nr(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function nr(e){if(e.appleOs===`watchos`)return rr(e);let t=g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:D}:$n;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:$n,appLogCleanup:$n}})}function rr(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function ir(e,t,n,r){let i=O(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=mt(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(or(t,n,o.dump)){let i=await sr(e,t,n,a.path,r);i&&(o=ar(s,o,i,n.maxEntries))}return ur(s,t,n),lr(s,o.dump),o.dump.entries.length===0&&s.push(dr(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function ar(e,t,n,r){let i=n.scan.dump.entries.length;return i===0&&(n.scan.dump.unnamedRequests??0)===0?(n.lineCount>0&&e.push(`Recovered ${n.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`),t):(i>0&&e.push(`Recovered ${i} iOS simulator HTTP entr${i===1?`y`:`ies`} from simctl log show (${n.lineCount} app log lines scanned).`),vt(n.scan,t,r))}function or(e,t,n){return g(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function sr(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=x(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,cr(n.appBundleId),...typeof a==`number`&&Number.isFinite(a)&&a>0?[`--start`,`@${Math.floor(a/1e3)}`]:[`--last`,`5m`]]),s=await e.appleTools.run({tool:`simctl`,args:o,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
2
+ `).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:mt(`${c.join(`
3
+ `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function cr(e){let t=e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function lr(e,t){let n=t.entries.filter(e=>e.pathUnavailable).length,r=t.unnamedRequests??0,i=n+r;if(i===0)return;let a=[`${i} request${i===1?``:`s`} reused a keep-alive connection, so CFNetwork logged no request URL.`];n>0&&a.push(`${n} listed against the origin the connection was opened for, without a path.`),r>0&&a.push(`${r} opened before this scan window and are missing from the entries entirely; scan more lines, or run logs clear --restart before the repro.`),a.push(`Absence of an endpoint in this dump does not prove it was not called.`),e.push(a.join(` `))}function ur(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(g(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function dr(e){return g(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:g(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function fr(t){let{host:n,snapshot:r,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=t,s=r.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:t.stopObservation;if(r.invalidatedReason&&!r.showTouches)throw Error(`recording invalidated: ${r.invalidatedReason}`);let c;try{c=await n.screenRecording.finalize.complete({outputPath:r.outPath,showTouches:!r.invalidatedReason&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,...r.fps===void 0?{}:{fps:r.fps},targetLabel:i})}catch(t){throw e(t,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return Ct(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function pr(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await mr(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function mr(t){try{return await t()}catch(t){throw e(t,`COMMAND_FAILED`)}}const hr=[`outPath`,`startedAt`,`clientOutPath`,...Et],gr=Object.freeze({resourceKind:Ce,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>Or(e)});function _r(e){let{device:t,owner:n,input:r,descriptor:i}=e;return Se({resourceKind:Ce,sessionId:r.sessionId,device:oe(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:xe(gr,i)})}function vr(e){let t={};for(let n of hr)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function yr(e,t,n,r){let i=gr.decode(n);return i.status!==`decoded`||!Rr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await br(e,i.descriptor.processes,r):await Sr(e,t,i.descriptor)}async function br(e,t,n){let r=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(r.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(r.every(e=>e===`missing`))return n!==void 0&&e.screenRecording.ownedProcesses.clear(xr(n)),{status:`already-missing`};let i=await Promise.all(t.flatMap((t,n)=>r[n]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return i.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(n!==void 0&&e.screenRecording.ownedProcesses.clear(xr(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function xr(e){return{kind:`session`,sessionId:e}}async function Sr(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function Cr(e){let{host:t,device:n,envelope:r}=e,i=gr.decode(r.descriptor.body);return i.status===`decoded`?Rr(n,i.descriptor)?i.descriptor.backend===`simctl`?await wr(e,i.descriptor):await Er(t,n,i.descriptor):A(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):A(`descriptor-invalid`,i.message)}async function wr(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return A(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=Tr(At(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await Dr(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await br(e.host,t.processes,e.envelope.sessionId)}}function Tr(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function Er(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:A(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function Dr(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function A(e,t){return{status:`unreattachable`,reason:e,message:t}}function Or(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?M():e.backend===`simctl`?kr(e,e.outputPath):e.backend===`runner`?Mr(e,e.outputPath):M()}function kr(e,t){let n=zr(e.processes),r=Ar(e.recording);return!n||r===`invalid`?M():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function Ar(e){if(e!==void 0)return d(e)&&jr(e)?Object.freeze(e):`invalid`}function jr(e){return j(e.outPath)&&Pr(e.startedAt)&&Nr(e.clientOutPath)&&wt(e)}function Mr(e,t){return!j(e.appBundleId)||!j(e.runnerSessionId)||!Fr(e.runnerAuthority)||!Ir(e.remotePath)?M():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function j(e){return typeof e==`string`&&e.length>0}function Nr(e){return e===void 0||j(e)}function Pr(e){return typeof e==`number`&&Number.isFinite(e)}function Fr(e){return e===`local-lease`||e===`scoped-provider`}function Ir(e){return e===void 0||Lr(e)}function Lr(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Rr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:g(e)?t.remotePath!==void 0&&Lr(t.remotePath):t.remotePath===void 0:!1}function zr(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function M(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Br(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const Vr=`iOS recording`,Hr=`simctl recordVideo`;function Ur(e){return e.appleOs===`watchos`?y(`unsupported-platform-leaf`,`watchOS recording is not supported.`):g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?y(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function Wr(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Gr({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await Cr({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:qr({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await yr(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Gr(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Kr(e):await Yr(e)}async function Kr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Br(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=zt(i.outputPath);await t.screenRecording.outputs.prepare(s);let c=await t.screenRecording.apple.startSimulator(n,s,a),l=c.markers;if(!l||l.length===0)throw await ei(c).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted(),t.screenRecording.ownedProcesses.replace({kind:`session`,sessionId:i.sessionId},l.map(e=>({...e,purpose:`simctl-screen-recording`})))}catch(e){try{t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId})}catch{}throw await ei(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Zr(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=ri(i,Hr,{},o);return ni({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:vr(p)},snapshot:p,finish:(e,n)=>Ot({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await Jr(t,s,e)}catch(e){throw Qr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await pr({host:t,snapshot:e,targetLabel:Vr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Qr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await ti(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function qr(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:Hr,gestureEvents:[]});return St(a,{finish:(e,i)=>Ot({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await Jr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await pr({host:t,snapshot:e,targetLabel:Vr,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function Jr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Yr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>(l??=Xr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!$r(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return ni({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:ri(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await fr({host:t,snapshot:e,targetLabel:n.appleOs===`macos`?`macOS recording`:`iOS recording`,stopObservation:{recorder:`confirmed`},...s.remotePath===void 0?{}:{nativePathDisposition:`retirable`}})),cleanup:async()=>(await u(),{status:`cleaned`})})}async function Xr(t){try{return await t()}catch(t){throw e(t,`COMMAND_FAILED`)}}function Zr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Qr(n,r,i){let a=e(n,`COMMAND_FAILED`);return r===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?n:new t(a.code,`${a.message}; ${r}`,f(i,{...a.details??{},...i.signal===void 0?{}:{signal:i.signal},retriable:!1,hint:`The recorder exited before record stop, so the next record stop reads the same file. Close this session to release the device, then record again.`}))}function $r(e,t){return e.appleOs===`macos`||!g(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function ei(e){return await e.terminate(),await e.wait}async function ti(e){try{return await ei(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function ni(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=St(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new Oe(c),envelope:_r({device:t,owner:n,input:r,descriptor:i})})}function ri(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}async function N(e,t,n,r={}){return n.throwIfAborted(),v(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await ii(e,t)?`Booted`:await ui(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await ai(e,t,n,r.deadlineAtMs),await di(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function ii(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function ai(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await oi(e,t,n,r),await si(e,t,n,r)}catch(a){throw i&&n.aborted&&fi(e,t),n.throwIfAborted(),Date.now()>=r?li(t,a):a}}async function oi(e,n,r,i){let a=await e.appleTools.run({tool:`simctl`,args:x(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:ci(i,n)},r),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new t(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function si(e,n,r,i){we({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await e.appleTools.run({tool:`simctl`,args:x(n,[`bootstatus`,n.id,`-b`]),allowFailure:!0,timeoutMs:ci(i,n)},r);if(a.exitCode!==0)throw new t(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(r.throwIfAborted(),Date.now()>=i)throw li(n)}function ci(e,t){let n=e-Date.now();if(n<=0)throw li(t);return n}function li(e,n){return new t(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:Mt,deviceId:e.id,hint:`The Simulator keeps booting in the background; a first boot can take several minutes. Retry once it is up, or pass a larger --timeout.`},n instanceof Error?n:void 0)}async function ui(e,t,n){return await pn(e.appleTools,t,n,15e3)}async function di(e,t){await e.commands.run({executable:`open`,args:[`-g`,`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function fi(e,t){e.appleTools.run({tool:`simctl`,args:x(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const pi=Object.freeze({resolveOpenTarget:`simulator`,prepareApplicationOpen:`simulator`,openApplication:`simulator`,applyRuntimeHints:`simulator`,clearRuntimeHints:`simulator`,closeApplication:`simulator`,finalizeApplicationClose:`simulator`,prepareAppleRunner:`runner`,configureProviderPortReverse:`simulator`,ensureReady:`simulator`,bootTarget:`simulator`,bootTargetHeadless:`simulator`,shutdownTarget:`simulator`,listApps:`simulator`,deployApp:`simulator`,materializeAppSource:`simulator`,deployMaterializedApp:`simulator`,sendPushNotification:`simulator`,uninstallApp:`simulator`,appState:`simulator`,appLogStart:`simulator`,appLogInspect:`simulator`,appLogDoctor:`simulator`,appLogReattach:`simulator`,appLogCleanup:`simulator`,networkDump:`simulator`,audioProbeStart:`simulator`,audioProbeQuery:`simulator`,audioProbeReattach:`simulator`,audioProbeCleanup:`simulator`,readClipboard:`simulator`,writeClipboard:`runner`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`simulator`,sendTelephonyEvent:`simulator`,unlockOrientation:`simulator`,power:`simulator`,volumeDown:`simulator`,volumeUp:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`runner`,querySelector:`runner`,readTextAtPoint:`runner`,tapPoint:`runner`,tapRef:`runner`,tapElementSelector:`runner`,fillPoint:`runner`,fillRef:`runner`,longPressPoint:`runner`,hoverPoint:`runner`,hoverRef:`runner`,focusPoint:`runner`,typeText:`runner`,scrollDirection:`runner`,performGesturePlan:`runner`,performMultiTouchGesturePlan:`runner`,performTargetAuthoredDrag:`runner`,performDirectionalFlingPlan:`runner`,gestureViewport:`runner`,setViewport:`runner`,back:`runner`,home:`runner`,setOrientation:`runner`,appSwitcher:`runner`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function mi(e){return e===void 0?`possible`:e.some(e=>pi[e]===`runner`)?`required`:`none`}function hi(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 gi(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 _i(e,t){let n=await Qt(`ps`,[`-p`,String(e),`-o`,`lstart=`],{allowFailure:!0,signal:t.signal,timeoutMs:t.timeoutMs});return n.exitCode===0&&n.stdout.trim()||null}const vi=3e3,yi=`simulator-target-discovery-pending`,bi=`simulator-target-unavailable`;function xi(){let e=new Map,t=new Map,n=gi({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);if(c&&o!==`refresh`){let e=await _i(c.pid,{signal:a,timeoutMs:vi});if(a.throwIfAborted(),e===c.processStartTime)return c}return e.delete(s),await n.value(s,{start:async()=>{let n=await Ti(r,i,t);return e.set(s,n),n},wait:(e,t)=>hi({waitMs:e,signal:a,stop:t,cancelled:()=>Si(a)}),pending:()=>P(yi,r,i)})}}function Si(e){return n({readinessPhase:`target-discovery`},e.reason)}function Ci(e){return e instanceof t&&e.details?.reason===yi}function wi(e){return e instanceof t&&e.details?.reason===bi}async function Ti(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([sn(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:Oi(r)}),Ei(e,n,r)]);if(i.status===`rejected`)throw i.reason;if(a.status===`rejected`)throw a.reason;let o=i.value,s=a.value;if(o.exitCode!==0)throw P(`simulator-target-probe-failed`,e,t);let c=Di(o.stdout,t);if(!c)throw P(bi,e,t);let l=await _i(c.pid,{timeoutMs:Math.min(vi,Oi(r))});if(!l)throw P(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:cn(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Ei(e,t,n){let r=t.get(e.id);if(r)return await r;let i=sn(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:Oi(n)}).then(t=>{if(t.exitCode!==0)throw P(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(rn(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw P(`simulator-runtime-unavailable`,e,``);return n});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Di(e,t){for(let n of e.split(`
4
+ `)){let[e,,r]=n.trim().split(/\s+/);if(!e||!r||!r.startsWith(`UIKitApplication:${t}[`))continue;let i=Number(e);if(Number.isSafeInteger(i)&&i>0)return{pid:i,label:r}}}function Oi(e){return Math.max(1,e-Date.now())}function P(e,n,r){return new t(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:n.id,appBundleId:r})}function ki(e){return e?.observation===`unobservable`&&e.proof===`no-running-process`}const Ai=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function F(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function ji(e){let t=ve(be({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!F(n))return{observation:`not-eligible`};let a;for(;;){let o=await Ni(e.resolveTarget,n,r,i);if(`verdict`in o)return o.verdict;let{target:s}=o;if(e.isBridgeDisabled(s))return h({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:s.generation}}),Mi({source:`circuit`});let c=await e.source.acquire({target:s,hint:t,signal:i});if(c.stage!==`failed`)return{observation:`observable`};i.throwIfAborted();let{kind:l,code:u}=c.failure,d=Ai.get(u);if(d===void 0)return Mi({source:`bridge`,kind:l,code:u});let f=e.clock.now();if(a=Math.min(a??1/0,f+d),f>=a)return{observation:`unobservable`,proof:`launch-transition`};await e.clock.sleep(Math.min(150,a-f),i)}}})}function Mi(e){return{observation:`probe-failed`,failure:e}}async function Ni(e,t,n,r){for(;;)try{return{target:await e(t,n,r)}}catch(e){if(r.throwIfAborted(),Ci(e))continue;if(wi(e))return{verdict:{observation:`unobservable`,proof:`no-running-process`}};let{code:t,details:n}=i(e),a=n?.reason;return{verdict:Mi(typeof a==`string`?{source:`target`,code:t,reason:a}:{source:`target`,code:t})}}}function Pi(e,t,n){let r=n&&F(e),i=r?mi(t.execution.plannedOperations):void 0,a=g(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function Fi(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function Ii(e,n,r,i,a,o){let s=Date.now(),c=async()=>await Ui(n,r,i,a.observation),l=await c(),u,d,f=a.answerConfirmation,p=f&&l?.observation!==`observable`?await Li(f,a.redispatchLaunchUrl,c,l):void 0;if(p&&(o.runnerDemand=`required`,u=p.report,d=p.probeFailure,l=p.observed,p.unanswered))throw new t(`COMMAND_FAILED`,`The Simulator has not completed the launch URL for ${r.appBundleId}.`,{reason:`launch_confirmation_unanswered`,appBundleId:r.appBundleId,hint:`iOS may still be holding an "Open in" prompt, or the answer died with the runner session that raised it. Inspect the current alert before deciding on another action.`});if(i&&l?.observation!==`observable`&&await e.clock.sleep(300,n.signal),l&&(o.postOpenObservation=l.observation,l.observation===`probe-failed`&&(o.postOpenObservationFailure=l.failure)),o.postOpenSettleDurationMs=Math.max(0,Date.now()-s),u)return u;if(d)return{launchConfirmationProbeFailure:d}}async function Li(e,t,n,r){let i={observed:r,acceptAttempted:!1,confirmationStillPresent:!1};for(let r=0;r<2;r+=1){i=await Ri(e,n,i);let a=r===1;if(i.confirmationStillPresent||a||!Vi(i)||!t)break;await t()}return{observed:i.observed,report:i.report,probeFailure:i.probeFailure,unanswered:Vi(i)||i.confirmationStillPresent}}async function Ri(e,t,n){let r=await e(),i=r.outcome===`unanswered`&&r.reason===`alert-still-present`,a=n.acceptAttempted||Hi(r),o=Bi(n,r);return a?{observed:await t(),...o,acceptAttempted:a,confirmationStillPresent:i}:{observed:n.observed,...o,acceptAttempted:a,confirmationStillPresent:i}}function zi(e){switch(e.outcome){case`accepted`:return{seen:{launchConfirmation:`accepted`}};case`absent`:return{};case`unreadable`:return e.step===`url-owner`?{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:`url-owner-unresolved`}}:{probeFailure:e.step};case`unanswered`:return e.reason===`alert-still-present`?{}:{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:e.reason}}}}function Bi(e,t){let n=zi(t);return`seen`in n?{report:n.seen,probeFailure:void 0}:`probeFailure`in n?{report:void 0,probeFailure:n.probeFailure}:{report:e.report,probeFailure:void 0}}function Vi(e){return e.acceptAttempted&&ki(e.observed)}function Hi(e){return e.outcome===`accepted`||e.outcome===`unanswered`&&e.reason===`alert-still-present`||e.outcome===`unreadable`&&e.step===`alert-accept`}async function Ui(e,t,n,r){if(!(!n||!F(e.device))&&!(!r||!t.appBundleId))return await r.awaitObservable(e.device,t.appBundleId,e.signal)}let Wi;const Gi=()=>Wi??=import(`./launch-confirmation.js`);let Ki;const qi=()=>Ki??=import(`./expo-dev-client-launch.js`);function Ji(e){let t=t=>st({device:t,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve}),n=e.device,r=t(n),i=e=>{n=e,r=t(e)};return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(n,t),prepareApplicationOpen:async t=>{let r=await N(e.host,n,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(n,t.execution,e.signal).catch(()=>{})}:void 0});i(r)},openApplication:async t=>await Yi(e.host,r,t,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(n,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(n,t),closeApplication:async t=>{t.ensureReady&&i(await N(e.host,n,e.signal)),await ca(e.host,r,t)},finalizeApplicationClose:async t=>await la(e.host,n,e.signal,t),prepareAppleRunner:async t=>{let r=await ua(e.host,n,e.signal,t);return i(r.readied),r.prepared},configureProviderPortReverse:ga})}async function Yi(e,t,n,r){let i={},a=I(t.device),o=da(e,t,n,i),s=Pi(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),Fi(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=sa(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Xi(e,t,n,a,l,i);let u=await Zi(t,n,a,i),d=pa(t.device,u?{...n,runtimeLaunchUrl:u}:n,a);await Qi(o,c,n.prewarmRunnerBeforeOpen);let f=o.wasAwaited();await $i(t,n,d,a,i),await ia(o,c,s.awaitPrewarmAfterOpen),await aa(e,t,n,a,f,l);let p=await Ii(e,t,n,a,{observation:r,answerConfirmation:na(t,n,d),redispatchLaunchUrl:ra(t,n,d)},i);return{appBundleId:n.appBundleId,timing:i,...p??{}}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Xi(e,t,n,r,i,a){if(!oa(n,r)||!n.target)return;let o=Date.now();ce(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await ct({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=L(o)}async function Zi(e,n,r,i){if(!Ee(n.runtimeHints))return;let a=Date.now(),o=r?await(await qi()).resolveExpoDevClientLaunchUrl(e.device,n):void 0;if(!o){if(!n.applyRuntimeHints)throw new t(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await n.applyRuntimeHints({appId:n.appBundleId,values:n.runtimeHints})}return i.runtimeHintsDurationMs=L(a),o}async function Qi(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function $i(e,t,n,r,i){let a=Date.now();await lt({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:n.positionals,appBundleId:t.appBundleId,execution:t.execution,...r&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),i.openDispatchDurationMs=L(a),await ea(e,t,n.followUpUrl,i)}async function ea(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i=Date.now();await ta(e,t,n),r.launchUrlDurationMs=L(i)}async function ta(e,t,n){let r={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0};await lt({device:e.device,interactor:await e.resolveInteractor(r,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:r})}function na(e,t,{confirmation:n}){if(n)return async()=>{let{answerSimulatorLaunchConfirmation:r}=await Gi();return await r(e.device,n,e.resolveInteractor(t.execution,n.appBundleId),e.signal)}}function ra(e,t,{confirmation:n}){if(n)return async()=>{await ta(e,t,n.url)}}async function ia(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function aa(e,t,n,r,i,a){!g(t.device)||!r&&!a||!n.relaunch&&!i||r&&!i&&!await e.appleApplications.hasLiveRunnerSession(t.device,n.execution)||await e.appleApplications.notifyRunnerAppRelaunched(t.device,n.execution,t.signal)}function oa(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function sa(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&oa(t,n)}async function ca(e,t,n){ce(t.device.platform)&&!I(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await ct({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),I(t.device)&&await e.clock.sleep(300,t.signal)}async function la(e,t,n,r){r.daemonShutdown||await e.appleApplications.releaseRunnerOnClose(t.id,{retain:r.retainRunner}),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{});let i=r.shutdownTarget&&I(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function ua(e,t,n,r){let i=Date.now()+r.timeoutMs,a=performance.now();return await ne(`prepare_apple_runner`,async()=>{let o=await N(e,t,n,{deadlineAtMs:i}),s=Math.max(1,i-Date.now());return h({phase:`prepare_apple_runner`,durationMs:performance.now()-a,data:{event:`runner_start`,timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}}),{readied:o,prepared:await e.appleApplications.prepareRunner(o,{...r,timeoutMs:s},n)}},()=>({timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}),`readiness_start`)}function da(e,t,n,r){let i,a=!1,o=fa(t.device,n)?{healthCheck:!1}:void 0;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,o?e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a,o):e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=L(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function fa(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function pa(e,t,n){let r=t.runtimeLaunchUrl?.trim(),i=t.positionals.length===1?t.positionals[0]?.trim():void 0;if(!r||!i||u(i))return{positionals:t.positionals};let a=ma(e,t.appBundleId,r),o=a?{confirmation:a}:{};return n&&!ha(t)?{positionals:[i,r],...o}:{positionals:t.positionals,followUpUrl:r,...o}}function ma(e,t,n){if(e.appleOs===`ios`&&e.kind===`simulator`&&!(t===void 0||c(n)))return{url:n,appBundleId:t}}function ha(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function I(e){return g(e)&&e.kind===`simulator`}function L(e){return Math.max(0,Date.now()-e)}async function ga(){throw new t(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const _a=Object.freeze({available:!0}),va=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`}),ya=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),ba=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),xa=Object.freeze({available:!1,reason:`unsupported-device-kind`});function Sa(e){let t=ja(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:Ma(e),uninstallApp:t})}function Ca(e){let{host:t,device:n,signal:r}=e,i=Sa(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await wa(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Ea(t,n,e,r),uninstallApp:async e=>await Ta(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await ka(t,n,e,r),{})}:{}})}async function wa(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Oa(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Da(e,t,a.installablePath,r),{bundleId:i,launchTarget:i}}finally{await a.cleanup()}});let i=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Ea(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function Ta(e,n,r,i){return await e.appleDeployment.withInvalidatedAppResolutionCache(n,async()=>{await N(e,n,i);let a;try{a=await e.appleDeployment.resolveAppBundleId(n,r.app,{installedOnly:!0})}catch(e){if(e instanceof t&&e.code===`APP_NOT_INSTALLED`&&r.app.trim().includes(`.`))return{wasInstalled:!1};throw e}return await Oa(e,n,a,i),{wasInstalled:!0,bundleId:a}})}async function Ea(e,t,n,r){return await Da(e,t,n.artifact.installablePath,r),{...n.artifact.bundleId?{bundleId:n.artifact.bundleId}:{},...n.artifact.appName?{appName:n.artifact.appName}:{},...n.artifact.bundleId?{launchTarget:n.artifact.bundleId}:{}}}async function Da(e,t,n,r){await N(e,t,r),await Aa(e,t.kind===`simulator`?{tool:`simctl`,args:x(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:Yt},r,`Apple app install failed`)}async function Oa(e,t,n,r){await N(e,t,r),await Aa(e,t.kind===`simulator`?{tool:`simctl`,args:x(t,[`uninstall`,t.id,n])}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n]},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>tn(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function ka(e,n,r,i){if(n.kind!==`simulator`)throw new t(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await N(e,n,i);let a=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),await Aa(e,{tool:`simctl`,args:x(n,[`push`,n.id,r.appId,a.path])},i,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}async function Aa(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:p(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:en(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function ja(e){return Na(e)?e.kind!==`simulator`&&e.kind!==`device`?xa:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?va:_a:ba}function Ma(e){return Na(e)?e.kind===`simulator`?_a:ya:ba}function Na(e){return g(e)&&e.appleOs!==`watchos`}const R=Object.freeze({available:!0}),Pa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),Fa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ia(e){return e.kind!==`simulator`&&e.kind!==`device`?Pa:_(e)===`watchos`?Fa:R}const La=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),Ra=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),za=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function Ba(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=_(e);return n===`macos`||n===`watchos`?Ra:R}function z(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=_(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const Va=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),Ha=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ua(e){return e.kind!==`simulator`&&e.kind!==`device`?Va:z(e)?R:Ha}const Wa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function Ga(e){return(e.kind===`simulator`||e.kind===`device`)&&ae(e)?R:Wa}const B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ka=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS`});function qa(e){return z(e)?Ka:B}function Ja(e){return z(e)?R:B}function Ya(e){return z(e)?R:B}const Xa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Za=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),Qa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.`});function $a(e){return e.kind!==`simulator`&&e.kind!==`device`?Za:le(e)?R:Qa}const eo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`hardware-button volume presses the iPhone/iPad volume key; this Apple leaf has none.`}),to=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button volume is supported on physical iPhone and iPad; iOS Simulators refuse because XCUIDevice exposes no volume press there.`});function no(e){return le(e)?e.kind===`device`?R:to:eo}function ro(e){return Object.freeze({...Fe({back:Ia(e)}),...Ze({unsupported:Xa,home:Ba(e,La),appSwitcher:Ba(e,za),actionButton:$a(e),volumeUp:no(e),volumeDown:no(e)}),...tt({orientation:Ua(e)}),...it({tvRemote:Ga(e),buttonSupport:{supported:o(`apple`),unsupported:{available:!1,reason:`unsupported-platform-leaf`,hint:`This TV remote button is not supported on tvOS.`}}}),...et({unsupported:B,status:qa(e),dismiss:Ja(e),enter:Ya(e)})})}function io(e){let{host:t,device:n,signal:r,admitted:i}=e,a=Object.keys(ro(n));return dt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Object.fromEntries(a.map(e=>[e,i[e]]))})}const V=Object.freeze({available:!0}),ao=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),oo=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),so=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`settings is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),co=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Run `agent-device settings --help` for the settings each target serves."}),lo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The macOS host supports settings appearance and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>.`}),uo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Select a booted iPhone or iPad simulator: this setting runs only there.`}),fo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`clipboard is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),po=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function mo(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=_(e);return r===`watchos`?po:e.kind===`simulator`||r===`macos`?V:n}function ho(e){return mo(e,ao,fo)}const go=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),_o=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),vo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function yo(e){if(e.kind!==`simulator`&&e.kind!==`device`)return _o;let t=_(e);return t===`watchos`?po:e.kind===`simulator`||t===`ios`||t===`macos`?V:vo}function bo(e){return e.kind!==`simulator`&&e.kind!==`device`?go:_(e)===`watchos`?po:V}function xo(e){let t=ho(e);return t.available?fo:t}function So(e){let t=mo(e,oo,so);if(v(e))return ut({target:t,unsupported:lo,write:{appearance:V,permission:V}});let n=se(e)?V:uo;return ut({target:t,unsupported:co,write:{wifi:V,airplane:V,location:V,appearance:V,"clear-app-state":V,"reset-keychain":V,permission:V,"text-size":n,faceid:n,touchid:n},read:{"text-size":n}})}function Co(e){let t=ho(e),n=yo(e);return Object.freeze({...nt({unsupported:xo(e),read:t,write:t}),...ot({read:n,wait:n,accept:n,dismiss:n}),...at({triggerAppEvent:bo(e)}),...So(e)})}function wo(e){let{host:t,device:n,signal:r}=e;return dt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Co(n)})}const To=/Angle:\s*(-?\d+(?:[.,]\d+)?)\s*°/g;async function Eo(e,n={}){let r=[`devicectl`,`device`,`motion`,`hinge-angle`,`--device`,e.id,`--session-timeout`,`1`,`--timeout`,`5`],i=await $t(r,{allowFailure:!0,signal:n.signal,timeoutMs:Zt}),a=Do(i.stdout)??Do(i.stderr);if(a!==void 0)return a;throw new t(`COMMAND_FAILED`,`CoreDevice reported no hinge angle sample`,f(i,{cmd:`xcrun`,args:r,stdout:i.stdout,stderr:i.stderr,deviceId:e.id,reason:`fold-hinge-angle-no-sample`,hint:`'devicectl device motion hinge-angle' printed no sample, and foldable poses can be verified only through that stream. The stderr in the details names the cause, such as a devicectl without the subcommand or a device CoreDevice cannot reach.`}))}function Do(e){let t;for(let n of e.matchAll(To)){let e=Number.parseFloat(n[1].replace(`,`,`.`));Number.isFinite(e)&&(t=e)}return t}var H=class extends t{buildFailureKind;buildFailureCode;buildDetails;constructor(e,t,n=`native build ${e}: ${t}`,r={},i){super(`COMMAND_FAILED`,n,{...r,nativeBuildFailure:e,nativeBuildFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`NativeBuildError`,this.buildFailureKind=e,this.buildFailureCode=t,this.buildDetails=r}};function U(e,t,n={},r){return new H(e,t,void 0,n,r)}function Oo(e,t,n=Date.now){if(t?.aborted)throw U(`cancelled`,`abort-signal`);return{clock:ee.fromTimeoutMs(e,n()),now:n,signal:t}}function W(e,t){if(e.signal?.aborted)throw U(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw U(`timeout`,t);return Math.max(1,Math.floor(n))}function ko(e){return{run:e,readText:Ht,readBinary:Gt,writeText:Bt,ensureDirectory:qt,chmod:Kt,exists:Ut,rename:Vt,remove:Jt,acquireLock:Ao,processId:ie,cpuArch:te}}async function Ao(e,t){let n=ie(),r=t.deadline,i=ge({lockDirPath:e,owner:{pid:n,startTime:re(n),acquiredAtMs:Date.now()},timeoutMs:W(r,`cache-lock-deadline`),pollMs:100,description:t.description}),a=r.signal;if(!a)try{return await i}catch(e){throw jo(e,r)}let o=!1,s,c=new Promise((e,t)=>{s=()=>{o=!0,t(U(`cancelled`,`abort-signal`))},a.addEventListener(`abort`,s,{once:!0}),a.aborted&&s()});try{return await Promise.race([i,c])}catch(e){throw o&&i.then(e=>e().catch(()=>void 0),()=>void 0),jo(e,r)}finally{a.removeEventListener(`abort`,s)}}function jo(e,t){return t.clock.isExpired()&&!(e instanceof H&&e.buildFailureKind===`cancelled`)?U(`timeout`,`cache-lock-deadline`):e}async function Mo(e,t){let n=await Po(e,`xcodebuild`,[`-version`],t),r=await Po(e,`sw_vers`,[`-productVersion`],t),i=await Po(e,`sw_vers`,[`-buildVersion`],t),a=await No(e,t);if(a!==`arm64`&&a!==`x86_64`)throw U(`unsupported`,`simulator-architecture-unsupported`,{architecture:a});return{xcode:n,macosProductVersion:r,macosBuild:i,architecture:a}}async function No(e,t){let n=W(t,`host-arch-deadline`),r=t.signal,i,a,o=new Promise((e,t)=>{i=setTimeout(()=>t(U(`timeout`,`host-arch-deadline`)),n),i.unref?.(),a=()=>t(U(`cancelled`,`abort-signal`)),r?.addEventListener(`abort`,a,{once:!0})});try{return await Promise.race([e.cpuArch(),o])}finally{clearTimeout(i),a&&r?.removeEventListener(`abort`,a)}}async function Po(e,t,n,r){let i=await Fo(e,t,n,r);if(i.exitCode!==0)throw U(`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 U(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function Fo(e,t,n,r){let i=[],a;for(let o=1;;o+=1){let s;try{s=Math.min(nn,W(r,`toolchain-probe-deadline`))}catch(e){throw a??e}i.push(s);try{return await Ro(e,t,n,r,s)}catch(e){if(a=Io(e,t,r,i),o>=2)throw a}}}function Io(e,t,n,i){if(r(e))throw U(`cancelled`,`abort-signal`,{},e);if(!m(e))throw e;if(n.signal?.aborted)throw U(`cancelled`,`abort-signal`);return Lo(t,i,e)}function Lo(e,t,n){let r=t.length;return U(`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 Ro(e,t,n,r,i){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:i})}const zo=`manifest.json`;async function Bo(e){let{host:t,deadline:n,cacheRoot:r,binaryFilename:i}=e,a=mn(`sha256`).update(JSON.stringify(e.keyInputs)).digest(`hex`).slice(0,32),o=S.join(r,a);return await he({acquire:()=>t.acquireLock(S.join(r,`${a}.lock`),{deadline:n,description:e.lockDescription}),task:async()=>{let s=await Vo(t,o,i,a,n);if(s)return{path:s,cacheKey:a};W(n,`native-build-deadline`),t.exists(o)&&await t.remove(o),W(n,`native-build-deadline`),await t.ensureDirectory(r);let c=S.join(r,`.${a}.${t.processId()}.tmp`);W(n,`native-build-deadline`),await t.remove(c);try{W(n,`native-build-deadline`),await t.ensureDirectory(c);let r=S.join(c,i);await e.build(r),W(n,`native-build-deadline`),await t.chmod(r,493);let s=await Uo(t,r),l={...e.keyInputs,cacheKey:a,binarySha256:s};return await t.writeText(S.join(c,zo),`${JSON.stringify(l,null,2)}\n`),W(n,`native-build-deadline`),await t.rename(c,o),{path:S.join(o,i),cacheKey:a}}catch(e){throw await t.remove(c),e}}})}async function Vo(e,t,n,r,i){let a=S.join(t,n),o=S.join(t,zo);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:(W(i,`native-cache-hash-deadline`),await Uo(e,a)===t.binarySha256?a:void 0)}catch(e){if(Ho(e))throw e;return}}function Ho(e){return e instanceof H&&(e.buildFailureKind===`cancelled`||e.buildFailureKind===`timeout`)}async function Uo(e,t){return mn(`sha256`).update(await e.readBinary(t)).digest(`hex`)}async function Wo(e,t,n,r){let i=mn(`sha256`);for(let a of n){let n=S.join(t,a);if(W(r,`native-source-fingerprint-deadline`),!e.exists(n))throw U(`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 Go(e){let t=Math.min(e.budgetMs,W(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 m(n)?U(`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}}const Ko=`Fold.m`,qo=3e4,Jo=nn+qo;async function Yo(e={}){let t=e.host??Xo(),n=Oo(Jo,e.signal);try{let r=e.sourceRoot??S.join(_e(),`apple`,`fold-helper`),i=await Wo(t,r,[Ko],n),a=await Mo(t,n);return await Bo({host:t,deadline:n,lockDescription:`iOS Simulator fold helper cache`,cacheRoot:e.cacheRoot??S.join(Wt(),`.agent-device`,`fold-helper`),binaryFilename:`fold-helper`,keyInputs:{schemaVersion:1,sourceHash:i,toolchain:a,compileArgv:Zo({sourceRoot:``,outputPath:``})},build:e=>Qo(t,n,r,e)})}catch(e){throw $o(e)}}function Xo(){return ko(Qt)}function Zo(e){return[`--sdk`,`iphonesimulator`,`clang`,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`IOKit`,S.join(e.sourceRoot,Ko),`-o`,e.outputPath]}async function Qo(e,t,n,r){let i=await Go({host:e,deadline:t,argv:Zo({sourceRoot:n,outputPath:r}),budgetMs:qo,label:`fold helper`});if(i.exitCode!==0||!e.exists(r))throw es(f(i))}function $o(e){return!(e instanceof H)||e.buildFailureKind===`cancelled`?e:es({...e.buildDetails,cause:e.buildFailureCode},e)}function es(e,n){return new t(`COMMAND_FAILED`,`Unable to build the simulator fold helper`,{hint:`Select an Xcode with the iOS simulator SDK and foldable HID support using DEVELOPER_DIR.`,...e,reason:`fold-helper-build-failed`},n)}async function ts(e,n,r){r?.throwIfAborted();let i=await Yo({signal:r});r?.throwIfAborted();let a=typeof n==`string`?0:n.at(-1).atMs,o=typeof n==`string`?n:JSON.stringify(n),s=await sn(e,[`spawn`,e.id,i.path,o],{signal:r,timeoutMs:a+1e4,kill:{signal:`SIGTERM`,graceMs:1e3},allowFailure:!0});if(s.exitCode!==0)throw new t(`COMMAND_FAILED`,`Unable to send the simulator hinge pose`,f(s,{reason:`fold-hid-dispatch-failed`,deviceId:e.id}))}async function ns(e,t,n={}){n.signal?.throwIfAborted(),ln(e,`fold`);let r=t,i=r.keyframes?.at(-1)?.angle,o=r.pose??a(i);as(e,await un(e,{signal:n.signal})),await ts(e,r.keyframes??o,n.signal),h({level:`info`,phase:`apple_fold_pose_dispatched`,data:{deviceId:e.id,pose:o}});let s=await os(e,o,n.signal,i),c=await hs(e,n.signal);return{pose:a(s),hingeAngleDegrees:s,...c?{screen:gs(c)}:{}}}function rs(e){return e instanceof t&&e.details?.reason===`fold-hinge-angle-no-sample`}async function is(e,n,r,i,a){let o=await hs(e,r);return new t(`COMMAND_FAILED`,`${e.name} received the ${n} pose request, but the first hinge-angle read returned no sample to verify it`,{deviceId:e.id,requestedPose:n,...i===void 0?{}:{targetAngleDegrees:i},reason:`fold-pose-dispatched-unverified`,...o?{screen:gs(o)}:{},...a instanceof t?{hingeReadFailure:a.details}:{},hint:`The pose request was sent and the device may have followed it, but the first hinge-angle read returned no sample, so fold cannot confirm it. Take a screenshot or snapshot to see which panel is lit; hingeReadFailure names why the read failed.`},a)}function as(e,n){if(n.unresolved)throw new t(`COMMAND_FAILED`,`CoreDevice reported no display table for this simulator`,{deviceId:e.id,hint:`fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.`});if(!n.multiScreen)throw new t(`UNSUPPORTED_OPERATION`,`${e.name} is not a foldable simulator: fold requires more than one integrated panel`,{deviceId:e.id,reason:`single-panel-device`,hint:`fold sets the hinge angle of a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.`})}async function os(e,t,n,r){let i,a;for(let o=1;o<=4;o+=1){n?.throwIfAborted(),a=i;try{i=await Eo(e,{signal:n})}catch(a){throw i!==void 0||!rs(a)?a:await is(e,t,n,r,a)}if(ss(i,a,t,r))return i}throw us(e,t,i,a,r)}function ss(e,t,n,r){return r===void 0?a(e)===n?n!==`half-open`||t!==void 0&&ds(e,t):!1:cs(e,t,r)}function cs(e,t,n){return ls(e,n)?n===0||n===180||t!==void 0&&ls(t,n)&&Math.abs(e-t)<=.5:!1}function ls(e,t){return t===void 0||e!==void 0&&Math.abs(e-t)<=.5}function us(e,n,r,i,o){return ls(r,o)?o!==void 0&&r!==void 0?ms(e,a(r),r,i):r!==void 0&&n===`half-open`&&a(r)===n?ms(e,n,r,i):ps(e,n,r):new t(`COMMAND_FAILED`,`The hinge did not reach the final keyframe angle`,{reason:`fold-angle-unverified`,targetAngleDegrees:o,hingeAngleDegrees:r,deviceId:e.id})}function ds(e,t){return a(e)===`half-open`&&a(t)===`half-open`&&Math.abs(e-t)<=.5}function fs(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:a(n),hingeAngleDegrees:n}}function ps(e,n,r){return new t(`COMMAND_FAILED`,`${e.name} did not reach the ${n} pose: CoreDevice still reports a hinge angle of ${r}°`,{...fs(e,n,r),reason:`fold-pose-unverified`,hint:`The simulator HID command completed, but the hinge did not follow. Verify that the selected Xcode and simulator runtime support foldable HID control, then retry.`})}function ms(e,n,r,i){return new t(`COMMAND_FAILED`,`${e.name} was observed ${n} at ${r}° but did not settle: 4 hinge reads never held two consecutive angles within ${Xt}° of each other`,{...fs(e,n,r),reason:`fold-pose-unsettled`,...i===void 0?{}:{previousHingeAngleDegrees:i},hint:`The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.`})}async function hs(e,t){let n=await un(e,{signal:t});if(!(n.unresolved||n.ambiguous))return n.activeDisplay}function gs(e){return{display:e.name,coordinateSpace:s,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const _s=Object.freeze({available:!0}),vs=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold is supported on foldable iPhone simulators controlled through simulator HID; a physical device is folded by hand.`}),ys=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.`});function bs(e){return{available:!1,reason:`unsupported-device-scope`,hint:`fold cannot resolve a simulator scoped to the set at "${e}": CoreDevice's display inventory and hinge-angle readback need a simulator in the default set, so the pose could not be verified. Run fold without --ios-simulator-device-set.`}}function xs(e){if(e.kind!==`simulator`)return vs;let t=_(e);return t!==`ios`&&t!==`ipados`?ys:e.simulatorSetPath?bs(e.simulatorSetPath):_s}function Ss(e){return jt({fold:xs(e)})}function Cs(e){let{device:t,signal:n}=e;return b(Ss(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await ns(t,e,{signal:n}))}))}function ws(e,t,n){let r=$e({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(i.options?.observeOnly===!0)return await r.captureSnapshot(i);let a=v(t.device)?pe(i.options?.surface,t.appBackend):void 0;if(a)return await e.snapshot.captureSurface(t.device,{...i.options,surface:a},Qe(t.signal,i));if(!n)return await r.captureSnapshot(i);let o=Qe(t.signal,i);return await n.capture(t.device,i,o,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function Ts(e,t){return Object.freeze({findText:async n=>{let r=await Es(e,t,n);if(!r)return{found:!1};let i=await e.localInteractors.resolve(t.device,{...n.execution,...r});return i.findText?await i.findText(n.text,r):{found:!1}}})}async function Es(e,t,n){let r=n.options?.appBundleId;if(r===void 0||v(t.device)&&me(n.options?.surface,t.appBackend)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await Ds(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function Ds(e,t,n){return!F(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Os(e){return Object.freeze({querySelector:async t=>{let n=t.signal?AbortSignal.any([e.signal,t.signal]):e.signal;n.throwIfAborted();let r={...t.execution,signal:n},{queryAppleRunnerSelector:i}=await import(`./runner-selector-query.js`),a=await i(e.device,t.selector,t.options?.appBundleId,r),o=ks(a);return Object.freeze({found:a.found===!0,...o?{node:o}:{}})}})}function ks(e){let t=e.nodes;if(!Array.isArray(t))return;let n=t[0];if(!n||typeof n!=`object`)return;let r=l(n.rect);if(r)return Object.freeze({rect:r,hittable:n.hittable===!0})}const G=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.`});function As(e,t){return!v(e)||t!==`native`?{}:Object.freeze({screenRecordingStart:G,screenRecordingReattach:G,prepareAppleRunner:G,longPressPoint:G,...Fe({back:G}),...Re({unsupported:G})})}function js(e){let t,n=!1,r=async()=>(t??=import(`./host2.js`).then(e=>e.t).then(({createSnapshotSourceHost:t})=>import(`./adapter.js`).then(({createSimulatorSnapshotSource:n})=>n({host:t(e)}))),await t);return{acquire:async e=>n?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await r()).acquire(e),close:async()=>{n=!0,t&&await(await t).close()}}}function Ms(e=Date.now){let t=new Map;return async(n,r)=>{if(n.kind!==`simulator`)return`absent`;let i=t.get(n.id);if(i!==void 0&&e()-i.at<1e3)return{kind:`present`,host:i.host};t.delete(n.id);let a=await Ns(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function Ns(e,t){let n=await Promise.all(Me.map(async e=>({host:e,pids:await Ps(e.processExecutable,t)}))),r=!1;for(let{host:i,pids:a}of n){if(a===`unknown`){r=!0;continue}for(let n of a){let a=await Fs(n,e.id,t);if(a===`unknown`)r=!0;else if(a)return{kind:`present`,host:i}}}return r?`unknown`:`absent`}async function Ps(e,t){let n=await Is(`pgrep`,[`-f`,e],t);return n===`unknown`?`unknown`:n.exitCode===1?[]:n.exitCode===0?n.stdout.split(`
5
+ `).map(e=>Number.parseInt(e.trim(),10)).filter(e=>Number.isSafeInteger(e)&&e>0):`unknown`}async function Fs(e,t,n){let r=await Is(`ps`,[`eww`,`-p`,String(e),`-o`,`command=`],n);return r===`unknown`||r.exitCode!==0?`unknown`:r.stdout.includes(`SIMULATOR_UDID=${t}`)?!0:!r.stdout.includes(`SIMULATOR_UDID=`)&&`unknown`}async function Is(e,t,n){try{let r=await Qt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Ls=`system-surface-presented`,Rs=`system-surface-host-lingering`,zs=`window-coordinate-space-unresolved`;function Bs(e,n={}){let r=n.source??js(e.hostEnvironment),i=n.resolveTarget??xi(),a=n.systemSurfacePresent??Ms(),o=new Set,s=new Map,c=e=>(tc(e,s,o),o.has(nc(e))),l=ji({source:r,resolveTarget:i,clock:e.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(n,s,l,u)=>{if(!Us(n,s))return await qs(n,s,u);let d=await a(n,l);if(d===`unknown`)return await K(n.id,s,u,Ys(n.id,s),q(s),`system-surface-probe-unavailable`,[ec()]);if(d!==`absent`)return await Ks(n,s,u,d.host.bundleId);let f;try{f=await Vs(e,i,n,s,l)}catch(e){return Hs(l,e),J(`target-resolution-failed`,n,void 0,e),await K(n.id,s,u,Ys(n.id,s),q(s),`target-resolution-failed`,[ec()])}if(c(f))return J(`circuit-disabled`,n,f.generation),await K(n.id,s,u,f,q(s),`circuit-disabled`);let p=q(s),m=await r.acquire({target:f,hint:ve(p),signal:l});if(m.stage===`failed`){if(m.failure.kind===`cancelled`)throw l.throwIfAborted(),new t(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:m.failure.code,...m.failure.details});let e=await $s(m.failure,f,n,s.options.appBundleId,l,i);return await Ws(s,u,f,e,p,m.failure,o)}try{return await ne(`ios.snapshot-source.present`,async()=>await e.snapshot.presentIosAcquisition(m,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await Ws(s,u,f,{lineage:f,residue:[]},p,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Vs(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!Ci(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function Hs(e,t){if(e.aborted)throw r(t)?t:e.reason}function Us(e,t){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&!!t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0}async function Ws(e,t,n,r,i,a,o,s){return Gs(a)&&o.add(nc(n)),J(a.code,{id:n.simulator.udid},n.generation,s,a.details),await K(n.simulator.udid,e,t,r.lineage,i,a.code,r.residue)}function Gs(e){return e.kind!==`preparing`&&e.code!==zs}async function K(e,t,n,r,i,a,o=[]){return Js(e,await n(t),r,i,a,o)}async function Ks(e,t,n,r){let i=await n(t),a=i.systemSurface?Ls:Rs;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),Js(e.id,i,Ys(e.id,t),q(t),a)}async function qs(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:Zs(Xs(e.id,i.bundleId),q(t),[])}:r}function Js(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:Zs(o?Xs(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],Qs(i,n,o!==void 0)]}}function Ys(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function Xs(e,t){return{targetId:`${e}:${t}`}}function Zs(e,t,n){return Object.freeze({producer:`apple-runner`,intent:t.acquisitionIntent,lineage:Object.freeze({...e.targetId?{targetId:e.targetId}:{},...e.generation?{generation:e.generation}:{}}),presentationKey:ye(t),residue:Object.freeze([...n])})}function Qs(e,t,n){return e===Ls?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Rs?`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`:n?`Simulator AX snapshot unavailable (${e}); used XCTest, which read the system surface presented over the app.`:e===`bridge-preparation-pending`?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture while the bridge is still being prepared.`:e===zs?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture, which reports captured geometry in the app's own orientation space.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function $s(e,t,n,r,i,a){if(e.kind!==`stale-target`)return{lineage:t,residue:[]};try{return{lineage:await a(n,r,i,`refresh`),residue:[]}}catch(e){return i.throwIfAborted(),J(`fallback-target-resolution-failed`,n,void 0,e),{lineage:{targetId:t.targetId},residue:[ec()]}}}function ec(){return{kind:`unknown-generation`,captureId:hn()}}function q(e){return be({raw:e.options?.raw,interactiveOnly:e.options?.interactiveOnly,depth:e.options?.depth,scope:e.options?.scope,customActions:e.options?.customActions,acquisitionIntent:e.options?.acquisitionIntent})}function tc(e,t,n){let r=t.get(e.targetId);r&&r!==e.generation&&n.delete(`${e.targetId}:${r}`),t.set(e.targetId,e.generation)}function nc(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){h({level:`debug`,phase:`ios_snapshot_route_fallback`,data:{reason:e,deviceId:t.id,...n?{generation:n}:{},...r?{error:r instanceof Error?r.message:String(r)}:{},...i?{details:i}:{}}})}const Y=fe(`apple`),X=Object.freeze({available:!0}),Z=y(`unsupported-platform-leaf`),rc=y(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`),ic=y(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`),ac=y(`unsupported-device-backend`,`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`),oc=y(`unsupported-device-kind`,`focus is supported on Apple simulators and physical devices.`),sc=y(`unsupported-platform-leaf`,`telephony simulates calls and SMS through the Android emulator console; Apple simulators and devices expose no host control that injects a call or text message.`),cc=y(`unsupported-platform-leaf`,`Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`);function lc(e){return!g(e)||e.appleOs===`watchos`?cc:e.kind===`simulator`||e.kind===`device`?X:cc}const uc=y(`unsupported-provider-mode`,`Headless boot is supported only for local Android emulators.`),dc=y(`unsupported-platform-leaf`,`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`),fc=y(`unsupported-device-kind`),pc=y(`unsupported-platform-leaf`,`watchOS open is not supported because XCUITest cannot drive watchOS UI.`),mc=y(`unsupported-platform-leaf`,`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`),hc=y(`unsupported-platform-leaf`,`watchOS close is not supported because XCUITest cannot drive watchOS UI.`),gc=y(`unsupported-device-kind`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),_c=Q(`open is supported only for Apple simulators and devices.`),vc=Q(`prepare is supported only for Apple simulators and devices.`),yc=Q(`close is supported only for Apple simulators and devices.`),bc=y(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),xc=y(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),Sc=Q(`snapshot is supported only for Apple simulators and devices.`),Cc=y(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),wc=y(`unsupported-platform-leaf`,`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`),Tc=Q(`screenshot is supported only for Apple simulators and devices.`),Ec=y(`owner-capability-missing`,`Open the app under test before capturing its snapshot.`);function Q(e){return y(`unsupported-device-kind`,e)}function Dc(e){return!g(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:xc}function Oc(e){let t=kc(e),n=Ac(e),r=jc(e),i=Mc(e);return De({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:bc})}function kc(e){return _(e)===`watchos`?pc:e.kind===`simulator`||e.kind===`device`?X:_c}function Ac(e){return _(e)===`watchos`?mc:e.kind===`simulator`||e.kind===`device`?X:vc}function jc(e){return _(e)===`watchos`?hc:e.kind===`simulator`||e.kind===`device`?X:yc}function Mc(e){return _(e)!==`watchos`&&g(e)&&e.kind===`simulator`?X:gc}function Nc(e){return e.appleOs===`watchos`?y(`unsupported-platform-leaf`,`watchOS app inventory is not supported.`):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?y(`unsupported-device-backend`,`App inventory is available only on CoreDevice-backed physical iOS devices.`):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:oc}function Pc(e){let t=er(e),n=Bs(e),r,i=t=>v(t)?r??=fn(e.hostEnvironment.env):`xctest`,a=async n=>{let r=await t.inspectFacts(n),a=Sa(n),o=Ur(n),s=o.available?await e.screenRecording.apple.availability(n):void 0,c=o.available&&s?.available===!1?y(`unsupported-provider-mode`,s.hint):o,l=n.appleOs===`watchos`?Z:X,u=v(n)||n.appleOs===`watchos`?Z:X,d=Nc(n);return Object.freeze({device:r.device,operations:{...r.operations,...a,appState:lc(n),networkDump:X,screenRecordingStart:c,screenRecordingReattach:c,screenRecordingCleanup:c,...zc(n),...Le({capture:Rc(n)}),...Be({findText:Lc(n),querySelector:g(n)?$(n):Z}),...We({setViewport:rc}),...Ye({focus:$(n)}),...Cn(n),...Ve({type:$(n)}),...Ae({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...g(n)?{tapElementSelector:$(n)}:{}}),...Xe({readTextAtPoint:Ic(n)}),...ro(n),...Ss(n),sendTelephonyEvent:sc,...Co(n),...Pe({capture:_n(n),query:ic}),...Ue(Fc(n)),ensureReady:l,bootTarget:u,bootTargetHeadless:uc,listApps:d,...Oc(n),shutdownTarget:Dc(n),...As(n,i(n))}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:a,bind:async r=>{let o=await t.bind(r),s=await a(r.device),c=s.operations.screenRecordingStart,l=b(s.operations.appState,()=>gn(e,{device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),u=b(s.operations.querySelector,()=>Os({device:r.device,signal:r.scope.signal})),d={...l,...u,...o.operations,...Ca({host:e,device:r.device,signal:r.scope.signal}),networkDump:async t=>await ir(e,r.device,t,r.scope.signal),...b(c,()=>Wr({host:e,device:r.device,owner:Y,signal:r.scope.signal})),...b(s.operations.audioProbeStart,()=>yt({host:e.audioProbe.hostCapture,device:r.device,owner:Y})),...b(s.operations.perfFrames,()=>vn({resolveHost:()=>e.perf.apple,device:r.device,owner:Y})),...b(s.operations.captureSnapshot,()=>ws(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)},n)),...b(s.operations.captureScreenshot,()=>He({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.focusPoint,()=>rt({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...qe({device:r.device,signal:r.scope.signal,facts:s.operations,resolveInteractor:e.localInteractors.resolve}),...b(s.operations.scrollDirection,()=>Ke({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.typeText,()=>Ie({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.tapPoint,()=>je({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:s.operations,pause:async t=>await e.clock.sleep(t,r.scope.signal)})),...b(s.operations.readTextAtPoint,()=>Je({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.findText,()=>Ts(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)})),...io({host:e,device:r.device,signal:r.scope.signal,admitted:s.operations}),...wo({host:e,device:r.device,signal:r.scope.signal}),...Cs({device:r.device,signal:r.scope.signal}),...b(s.operations.ensureReady,()=>({ensureReady:async()=>await N(e,r.device,r.scope.signal)})),...b(s.operations.bootTarget,()=>({bootTarget:async t=>await N(e,r.device,r.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...b(s.operations.listApps,()=>({listApps:async e=>{r.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...Te(Ji({host:e,device:r.device,signal:r.scope.signal,observation:n}),s.operations),...b(s.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(r.device,r.scope.signal)}))};return Object.freeze({device:o.device,owner:Y,facts:s,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Fc(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&_(e)!==`watchos`?X:ac;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Ic(e){return _(e)===`watchos`?dc:e.kind===`simulator`||e.kind===`device`?X:fc}function Lc(e){return _(e)===`watchos`?Sc:e.kind===`simulator`||e.kind===`device`?X:Sc}function Rc(e){return _(e)===`watchos`?wc:e.kind===`simulator`||e.kind===`device`?X:Tc}function zc(e){let t=Lc(e);return ze({capture:t,customActions:t.available&&g(e)&&e.kind===`simulator`?X:Cc,withoutActiveApp:g(e)?Ec:t})}export{ko as a,H as c,Pc as createApplePlatformRuntime,hi as d,Mo as i,_i as l,Go as n,Oo as o,Wo as r,W as s,Bo as t,gi as u};
@@ -1 +1 @@
1
- import{R as e}from"./sdk-contracts.js";import{F as t}from"./sdk-device.js";import{Zt as n,in as r,rn as i}from"./sdk-batch.js";import{n as a}from"./device-shell.js";import{i as o,n as s}from"./durable-resource.js";import{n as c}from"./screen-recording-runtime.js";import{n as l,t as u}from"./application-lifecycle-runtime.js";import{n as ee}from"./async-lifecycle.js";import{i as d}from"./touch-runtime.js";import{r as f}from"./gesture-admission.js";import{D as p,F as te,G as ne,H as re,J as ie,L as ae,M as oe,O as se,S as ce,X as le,_ as ue,b as m,g as h,j as g,l as _,o as v,p as de,r as fe,w as pe,z as me}from"./tv-remote-runtime.js";import{r as he,u as ge}from"./application-lifecycle-interaction.js";import{t as _e}from"./local-interactor-operation-set.js";import{n as ve,t as y}from"./src4.js";import{n as b,t as x}from"./screen-recording-completion.js";import{t as S}from"./screen-recording-options.js";import{i as C,n as w}from"./perf-runtime-operation-builder.js";import{t as T}from"./app-log-runtime.js";import{randomUUID as E}from"node:crypto";import{setTimeout as D}from"node:timers/promises";const O=Object.freeze({resourceKind:T,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!A(e.outputPath)||!A(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function k(e){return s({resourceKind:T,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:o(O,e.descriptor)})}function A(e){return typeof e==`string`&&e.trim().length>0}function j(e){return y(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:O,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await M(e,r);return{resolvePid:async r=>await ve(e,{executable:i,args:a(`hdc`,`shell`,[`pidof`,n.appBundleId],[`-t`,t.id]),allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:a(`hdc`,`shell`,[`hilog`,`-P`,e],[`-t`,t.id]),allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>k({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function M(t,n){n.throwIfAborted(),await N(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await N(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function N(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}function P(e){let{resolveHost:t,device:n}=e,r={available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`};return Object.freeze({perfFrames:async()=>({metric:r,sampling:r}),perfMemorySample:async({appId:e})=>({metric:e?await C(t().sampleMemory(n,e)):w(`HarmonyOS`,`bundle`),sampling:{method:`hdc-shell-proc-status`,description:`Resident memory snapshot from HarmonyOS /proc/<pid>/status. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:1}}),perfMemorySnapshot:async({kind:e})=>({artifact:{available:!1,kind:e??`memgraph`,reason:`Memory snapshot artifacts are not supported on harmonyos.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`,support:{platform:`harmonyos`,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1}},sampling:{method:`unsupported`,description:`HarmonyOS memory snapshot capture is not available through HDC.`,artifactOnly:!0}})})}const F=Object.freeze({resourceKind:c,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&xe(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function ye(e){let{device:n,owner:r,input:i,descriptor:a}=e;return s({resourceKind:c,sessionId:i.sessionId,device:t(n),owner:r,fence:i.fence,lifecycle:`open`,descriptor:o(F,a)})}function be(e){return F.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function xe(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function Se(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function Ce(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await we({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>be(e.envelope.descriptor.body)})}async function we(t){let{host:n,device:r,owner:i,input:a,signal:o}=t;if(a.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);S(a,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),o.throwIfAborted(),await n.screenRecording.outputs.prepare(a.outputPath);let s=`agent-device-recording-${E()}.mp4`,c={backend:`harmony-screen-recorder`,fileName:s,remotePath:`/data/local/tmp/${s}`},l;try{l=await n.screenRecording.harmony.start(r,s,o),o.throwIfAborted()}catch(e){throw o.aborted?(await L(n,r,c).catch(()=>{}),o.reason):e}z(l,`start`);try{o.throwIfAborted()}catch(e){throw await L(n,r,c).catch(()=>{}),e}let u=Te(a),d=!1,f=async()=>{d||=(z(await n.screenRecording.harmony.stop(r),`stop`),!0)},p=b(u,{finish:async e=>await Ee(n,r,e,c,f),forceCleanup:async()=>await L(n,r,c,f)});return Object.freeze({pendingHandle:new ee(p),envelope:ye({device:r,owner:i,input:a,descriptor:c})})}function Te(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function Ee(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await ke(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await De(e,t,r,a);return x(n,{...i,...Oe(i.warning,o)},{stopObservation:{recorder:`confirmed`},nativePathDisposition:o===void 0?`retired`:`retirable`,showTouches:!1})}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function De(e,t,n,r){let i=[];return await I(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await I(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function I(e){try{return await e()}catch{return!1}}function Oe(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function ke(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function L(e,t,n,r=async()=>{z(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await R(r),await R(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await R(async()=>await Ae(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function Ae(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function R(e){try{await e();return}catch(e){return e}}function z(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function B(t,n){n.throwIfAborted();let{runHarmonyShell:r}=await import(`./hdc.js`),i=await r(t,[`aa`,`dump`,`-l`],{timeoutMs:15e3,signal:n});n.throwIfAborted();let a=je(i.stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function je(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}const Me=Object.freeze({available:!0}),Ne=Object.freeze({available:!1,reason:`unsupported-device-kind`}),V=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function H(e){let t=e.kind===`emulator`||e.kind===`device`?Me:Ne;return Object.freeze({deployApp:t,materializeAppSource:V,deployMaterializedApp:V,sendPushNotification:V,uninstallApp:V})}function Pe(e){return H(e.device).deployApp.available?Object.freeze({deployApp:async t=>await Fe(e.commands,e.device,t,e.signal)}):Object.freeze({})}async function Fe(t,n,r,i){let a=await Ie(t,r.appPath,i)??r.app.trim();if(!a)throw new e(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await ze(t,n,[`install`,`-r`,r.appPath],i,18e4),r.replaceExisting&&(await D(1e3,void 0,{signal:i}),await Le(t,n,a,i)),{packageName:a,launchTarget:a}}async function Ie(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(r.exitCode===0&&r.stdout.trim().length!==0)try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function Le(t,n,r,i){let a=Re((await U(t,n,[`bm`,`dump`,`-n`,r],i)).stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine a launchable ability for ${r}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await U(t,n,[`aa`,`start`,`-b`,r,...a.module?[`-m`,a.module]:[],`-a`,a.ability],i)}function Re(e){let t=e.indexOf(`{`);if(t!==-1)try{let n=JSON.parse(e.slice(t)).hapModuleInfos?.find(e=>e.mainElementName);return n?.mainElementName?{ability:n.mainElementName,...n.moduleName?{module:n.moduleName}:{}}:void 0}catch{return}}async function ze(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}async function U(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:a(`hdc`,`shell`,n,[`-t`,t.id]),timeoutMs:i},r)}const W=n(`harmonyos`),Be=i(`unsupported-platform-leaf`,`HarmonyOS reads element text from the captured tree only.`),Ve=i(`unsupported-device-kind`,`focus is supported on HarmonyOS emulators and physical devices.`),G=Object.freeze({available:!0}),K=i(`unsupported-platform-leaf`),He=i(`unsupported-device-kind`,`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`),Ue=i(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),q=Object.freeze({available:!0}),We=i(`unsupported-device-kind`,`open is supported only for HarmonyOS emulators and devices.`),Ge=i(`unsupported-device-kind`,`close is supported only for HarmonyOS emulators and devices.`),Ke=i(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),J=i(`unsupported-device-kind`,`snapshot is supported only for HarmonyOS emulators and devices.`),qe=i(`unsupported-device-kind`,`screenshot is supported only for HarmonyOS emulators and devices.`),Je=i(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),Ye=i(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web).`);function Xe(e){let t=Ze(e),n=Qe(e);return u({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:K,clearRuntimeHints:K,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Ue,configureProviderPortReverse:Ke})}function Ze(e){return e.kind===`emulator`||e.kind===`device`?q:We}function Qe(e){return e.kind===`emulator`||e.kind===`device`?q:Ge}const Y=i(`unsupported-device-kind`,`Gestures are supported on HarmonyOS emulators and physical devices.`),$e=i(`unsupported-platform-leaf`),et=i(`unsupported-platform-leaf`,f);function X(e){return e.kind===`emulator`||e.kind===`device`?G:Y}function Z(e){return e.kind===`emulator`||e.kind===`device`?G:Ve}const Q=i(`unsupported-platform-leaf`),tt=i(`unsupported-platform-leaf`,`HarmonyOS supports settings clear-app-state only.`),nt=i(`unsupported-platform-leaf`,`keyboard status/get is not available through the public HarmonyOS HDC API; use keyboard dismiss or enter`),$=i(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function rt(e){let t=j(e),n=async e=>{let n=await t.inspectFacts(e),r=H(e),i=Se(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?He:G,networkDump:K,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...g({capture:e.kind===`emulator`||e.kind===`device`?G:J,customActions:Je,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?G:J}),...te({capture:e.kind===`emulator`||e.kind===`device`?G:qe}),...oe({findText:J,querySelector:J}),...pe({setViewport:Ye}),...ie({focus:Z(e)}),...ne({unsupported:Y,plan:X(e),directionalFling:X(e),multiTouch:$e,targetAuthoredDrag:et,viewport:X(e)}),...re({scroll:X(e)}),...p({type:Z(e)}),...d({unsupported:K,tap:Z(e),longPress:Z(e),fill:Z(e)}),...le({readTextAtPoint:Be}),...ce({back:Z(e)}),...h({unsupported:Q,home:Z(e),appSwitcher:Z(e)}),setFoldPose:Q,sendTelephonyEvent:Q,...ue({triggerAppEvent:Q}),...ge({target:Z(e),unsupported:tt,write:{"clear-app-state":G}}),...m({read:Q,wait:Q,accept:Q,dismiss:Q}),...v({orientation:Q}),...fe({tvRemote:Q}),..._({unsupported:Q,status:nt,dismiss:Z(e),enter:Z(e)}),...de({unsupported:Q}),...me({capture:$,query:$}),...ae({frames:Z(e),memorySample:Z(e),memorySnapshot:Z(e),nativeCapture:Q,profileReport:Q}),ensureReady:G,bootTarget:K,bootTargetHeadless:K,listApps:G,...Xe(e),shutdownTarget:K}})};return Object.freeze({owner:W,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:n,bind:async i=>{let a=await t.bind(i),o=await n(i.device),s=o.operations.screenRecordingStart;return Object.freeze({device:a.device,owner:W,facts:o,operations:Object.freeze({...a.operations,...Pe({commands:e.commands,device:i.device,signal:i.scope.signal}),...o.operations.appState.available?{appState:async()=>await B(i.device,i.scope.signal)}:{},ensureReady:async()=>({...i.device,booted:!0}),...s.available?Ce({host:e,device:i.device,owner:W,signal:i.scope.signal}):{},...o.operations.captureSnapshot.available?se({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},..._e({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:o.operations,pause:async t=>await e.clock.sleep(t,i.scope.signal)}),...r(o.operations.perfFrames,()=>P({resolveHost:()=>e.perf.harmony,device:i.device})),listApps:async e=>{i.scope.signal.throwIfAborted();let{listHarmonyApps:t}=await import(`./app-lifecycle2.js`);return(await t(e.device,e.filter,{signal:i.scope.signal})).map(e=>({id:e.package,name:e.name}))},...l(he({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,host:e.localInteractors,device:i.device,signal:i.scope.signal}),o.operations)}),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{rt as createHarmonyPlatformRuntime};
1
+ import{R as e}from"./sdk-contracts.js";import{F as t}from"./sdk-device.js";import{en as n,on as r,sn as i}from"./sdk-batch.js";import{n as a}from"./device-shell.js";import{i as o,n as s}from"./durable-resource.js";import{n as c}from"./screen-recording-runtime.js";import{n as l,t as u}from"./application-lifecycle-runtime.js";import{n as ee}from"./async-lifecycle.js";import{i as d}from"./touch-runtime.js";import{r as f}from"./gesture-admission.js";import{B as p,C as te,I as ne,K as re,M as ie,N as ae,O as oe,R as se,T as ce,U as le,Y as ue,Z as m,_ as h,k as g,l as _,o as v,p as de,r as fe,v as pe,x as me}from"./tv-remote-runtime.js";import{r as he,u as ge}from"./application-lifecycle-interaction.js";import{t as _e}from"./local-interactor-operation-set.js";import{n as ve,t as y}from"./src4.js";import{n as b,t as x}from"./screen-recording-completion.js";import{t as S}from"./screen-recording-options.js";import{i as C,n as w}from"./perf-runtime-operation-builder.js";import{t as T}from"./app-log-runtime.js";import{randomUUID as E}from"node:crypto";import{setTimeout as D}from"node:timers/promises";const O=Object.freeze({resourceKind:T,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!A(e.outputPath)||!A(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function k(e){return s({resourceKind:T,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:o(O,e.descriptor)})}function A(e){return typeof e==`string`&&e.trim().length>0}function j(e){return y(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:O,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await M(e,r);return{resolvePid:async r=>await ve(e,{executable:i,args:a(`hdc`,`shell`,[`pidof`,n.appBundleId],[`-t`,t.id]),allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:a(`hdc`,`shell`,[`hilog`,`-P`,e],[`-t`,t.id]),allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>k({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function M(t,n){n.throwIfAborted(),await N(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await N(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function N(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}function P(e){let{resolveHost:t,device:n}=e,r={available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`};return Object.freeze({perfFrames:async()=>({metric:r,sampling:r}),perfMemorySample:async({appId:e})=>({metric:e?await C(t().sampleMemory(n,e)):w(`HarmonyOS`,`bundle`),sampling:{method:`hdc-shell-proc-status`,description:`Resident memory snapshot from HarmonyOS /proc/<pid>/status. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:1}}),perfMemorySnapshot:async({kind:e})=>({artifact:{available:!1,kind:e??`memgraph`,reason:`Memory snapshot artifacts are not supported on harmonyos.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`,support:{platform:`harmonyos`,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1}},sampling:{method:`unsupported`,description:`HarmonyOS memory snapshot capture is not available through HDC.`,artifactOnly:!0}})})}const F=Object.freeze({resourceKind:c,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&xe(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function ye(e){let{device:n,owner:r,input:i,descriptor:a}=e;return s({resourceKind:c,sessionId:i.sessionId,device:t(n),owner:r,fence:i.fence,lifecycle:`open`,descriptor:o(F,a)})}function be(e){return F.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function xe(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function Se(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function Ce(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await we({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>be(e.envelope.descriptor.body)})}async function we(t){let{host:n,device:r,owner:i,input:a,signal:o}=t;if(a.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);S(a,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),o.throwIfAborted(),await n.screenRecording.outputs.prepare(a.outputPath);let s=`agent-device-recording-${E()}.mp4`,c={backend:`harmony-screen-recorder`,fileName:s,remotePath:`/data/local/tmp/${s}`},l;try{l=await n.screenRecording.harmony.start(r,s,o),o.throwIfAborted()}catch(e){throw o.aborted?(await L(n,r,c).catch(()=>{}),o.reason):e}z(l,`start`);try{o.throwIfAborted()}catch(e){throw await L(n,r,c).catch(()=>{}),e}let u=Te(a),d=!1,f=async()=>{d||=(z(await n.screenRecording.harmony.stop(r),`stop`),!0)},p=b(u,{finish:async e=>await Ee(n,r,e,c,f),forceCleanup:async()=>await L(n,r,c,f)});return Object.freeze({pendingHandle:new ee(p),envelope:ye({device:r,owner:i,input:a,descriptor:c})})}function Te(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function Ee(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await ke(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await De(e,t,r,a);return x(n,{...i,...Oe(i.warning,o)},{stopObservation:{recorder:`confirmed`},nativePathDisposition:o===void 0?`retired`:`retirable`,showTouches:!1})}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function De(e,t,n,r){let i=[];return await I(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await I(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function I(e){try{return await e()}catch{return!1}}function Oe(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function ke(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function L(e,t,n,r=async()=>{z(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await R(r),await R(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await R(async()=>await Ae(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function Ae(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function R(e){try{await e();return}catch(e){return e}}function z(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function B(t,n){n.throwIfAborted();let{runHarmonyShell:r}=await import(`./hdc.js`),i=await r(t,[`aa`,`dump`,`-l`],{timeoutMs:15e3,signal:n});n.throwIfAborted();let a=je(i.stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function je(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}const Me=Object.freeze({available:!0}),Ne=Object.freeze({available:!1,reason:`unsupported-device-kind`}),V=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function H(e){let t=e.kind===`emulator`||e.kind===`device`?Me:Ne;return Object.freeze({deployApp:t,materializeAppSource:V,deployMaterializedApp:V,sendPushNotification:V,uninstallApp:V})}function Pe(e){return H(e.device).deployApp.available?Object.freeze({deployApp:async t=>await Fe(e.commands,e.device,t,e.signal)}):Object.freeze({})}async function Fe(t,n,r,i){let a=await Ie(t,r.appPath,i)??r.app.trim();if(!a)throw new e(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await ze(t,n,[`install`,`-r`,r.appPath],i,18e4),r.replaceExisting&&(await D(1e3,void 0,{signal:i}),await Le(t,n,a,i)),{packageName:a,launchTarget:a}}async function Ie(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(r.exitCode===0&&r.stdout.trim().length!==0)try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function Le(t,n,r,i){let a=Re((await U(t,n,[`bm`,`dump`,`-n`,r],i)).stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine a launchable ability for ${r}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await U(t,n,[`aa`,`start`,`-b`,r,...a.module?[`-m`,a.module]:[],`-a`,a.ability],i)}function Re(e){let t=e.indexOf(`{`);if(t!==-1)try{let n=JSON.parse(e.slice(t)).hapModuleInfos?.find(e=>e.mainElementName);return n?.mainElementName?{ability:n.mainElementName,...n.moduleName?{module:n.moduleName}:{}}:void 0}catch{return}}async function ze(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}async function U(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:a(`hdc`,`shell`,n,[`-t`,t.id]),timeoutMs:i},r)}const W=n(`harmonyos`),Be=r(`unsupported-platform-leaf`,`HarmonyOS reads element text from the captured tree only.`),Ve=r(`unsupported-device-kind`,`focus is supported on HarmonyOS emulators and physical devices.`),G=Object.freeze({available:!0}),K=r(`unsupported-platform-leaf`),He=r(`unsupported-device-kind`,`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`),Ue=r(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),q=Object.freeze({available:!0}),We=r(`unsupported-device-kind`,`open is supported only for HarmonyOS emulators and devices.`),Ge=r(`unsupported-device-kind`,`close is supported only for HarmonyOS emulators and devices.`),Ke=r(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),J=r(`unsupported-device-kind`,`snapshot is supported only for HarmonyOS emulators and devices.`),qe=r(`unsupported-device-kind`,`screenshot is supported only for HarmonyOS emulators and devices.`),Je=r(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),Ye=r(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web).`);function Xe(e){let t=Ze(e),n=Qe(e);return u({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:K,clearRuntimeHints:K,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Ue,configureProviderPortReverse:Ke})}function Ze(e){return e.kind===`emulator`||e.kind===`device`?q:We}function Qe(e){return e.kind===`emulator`||e.kind===`device`?q:Ge}const Y=r(`unsupported-device-kind`,`Gestures are supported on HarmonyOS emulators and physical devices.`),$e=r(`unsupported-platform-leaf`),et=r(`unsupported-platform-leaf`,f);function X(e){return e.kind===`emulator`||e.kind===`device`?G:Y}function Z(e){return e.kind===`emulator`||e.kind===`device`?G:Ve}const Q=r(`unsupported-platform-leaf`),tt=r(`unsupported-platform-leaf`,`HarmonyOS supports settings clear-app-state only.`),nt=r(`unsupported-platform-leaf`,`keyboard status/get is not available through the public HarmonyOS HDC API; use keyboard dismiss or enter`),$=r(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function rt(e){let t=j(e),n=async e=>{let n=await t.inspectFacts(e),r=H(e),i=Se(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?He:G,networkDump:K,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...ie({capture:e.kind===`emulator`||e.kind===`device`?G:J,customActions:Je,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?G:J}),...ne({capture:e.kind===`emulator`||e.kind===`device`?G:qe}),...ae({findText:J,querySelector:J}),...ce({setViewport:Ye}),...ue({focus:Z(e)}),...re({unsupported:Y,plan:X(e),directionalFling:X(e),multiTouch:$e,targetAuthoredDrag:et,viewport:X(e)}),...le({scroll:X(e)}),...oe({type:Z(e)}),...d({unsupported:K,tap:Z(e),longPress:Z(e),fill:Z(e)}),...m({readTextAtPoint:Be}),...te({back:Z(e)}),...h({unsupported:Q,home:Z(e),appSwitcher:Z(e)}),setFoldPose:Q,sendTelephonyEvent:Q,...pe({triggerAppEvent:Q}),...ge({target:Z(e),unsupported:tt,write:{"clear-app-state":G}}),...me({read:Q,wait:Q,accept:Q,dismiss:Q}),...v({orientation:Q}),...fe({tvRemote:Q}),..._({unsupported:Q,status:nt,dismiss:Z(e),enter:Z(e)}),...de({unsupported:Q}),...p({capture:$,query:$}),...se({frames:Z(e),memorySample:Z(e),memorySnapshot:Z(e),nativeCapture:Q,profileReport:Q}),ensureReady:G,bootTarget:K,bootTargetHeadless:K,listApps:G,...Xe(e),shutdownTarget:K}})};return Object.freeze({owner:W,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:n,bind:async r=>{let a=await t.bind(r),o=await n(r.device),s=o.operations.screenRecordingStart;return Object.freeze({device:a.device,owner:W,facts:o,operations:Object.freeze({...a.operations,...Pe({commands:e.commands,device:r.device,signal:r.scope.signal}),...o.operations.appState.available?{appState:async()=>await B(r.device,r.scope.signal)}:{},ensureReady:async()=>({...r.device,booted:!0}),...s.available?Ce({host:e,device:r.device,owner:W,signal:r.scope.signal}):{},...o.operations.captureSnapshot.available?g({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},..._e({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:o.operations,pause:async t=>await e.clock.sleep(t,r.scope.signal)}),...i(o.operations.perfFrames,()=>P({resolveHost:()=>e.perf.harmony,device:r.device})),listApps:async e=>{r.scope.signal.throwIfAborted();let{listHarmonyApps:t}=await import(`./app-lifecycle2.js`);return(await t(e.device,e.filter,{signal:r.scope.signal})).map(e=>({id:e.package,name:e.name}))},...l(he({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,host:e.localInteractors,device:r.device,signal:r.scope.signal}),o.operations)}),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{rt as createHarmonyPlatformRuntime};
@@ -1 +1 @@
1
- import{R as e}from"./sdk-contracts.js";import{Zt as t,nn as n,rn as r}from"./sdk-batch.js";import{n as i,t as a}from"./application-lifecycle-runtime.js";import{i as o}from"./touch-runtime.js";import{r as s}from"./gesture-admission.js";import{A as c,D as l,F as u,G as d,H as f,J as p,S as m,X as h,g,j as _,p as v}from"./tv-remote-runtime.js";import{r as y}from"./application-lifecycle-interaction.js";import{t as b}from"./local-interactor-operation-set.js";import{r as x}from"./platform-runtime-unavailable.js";const S=Object.freeze({available:!0}),C=t(`linux`),w=r(`unsupported-platform-leaf`),T=r(`unsupported-device-kind`),E=r(`unsupported-device-kind`,`focus is supported only for the Linux desktop device.`),D=r(`unsupported-device-kind`,`type is supported only for the Linux desktop device.`),O=r(`unsupported-device-kind`,`Gestures are supported only for the Linux desktop device.`),k=r(`unsupported-device-kind`,`scroll is supported only for the Linux desktop device.`),A=r(`unsupported-platform-leaf`),j=r(`unsupported-platform-leaf`),M=r(`unsupported-platform-leaf`,s),N=r(`unsupported-platform-leaf`),P=r(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),F=r(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),I=r(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),L=r(`unsupported-device-kind`,`open is supported only for the Linux desktop device.`),R=r(`unsupported-device-kind`,`close is supported only for the Linux desktop device.`),z=r(`unsupported-device-kind`,`snapshot is supported only for the Linux desktop device.`),B=r(`unsupported-device-kind`,`screenshot is supported only for the Linux desktop device.`),V=r(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),H=r(`unsupported-device-kind`,`back is supported only for the Linux desktop device.`),U=r(`unsupported-device-kind`,`home is supported only for the Linux desktop device.`),W=r(`unsupported-device-kind`,`clipboard is supported only for the Linux desktop device.`),G=w,K=r(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function q(t){return Object.freeze({owner:C,ownsDevice:e=>e.platform===`linux`,inspectFacts:async e=>Y(e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!n(r.intent.owner,C))throw new e(`UNSUPPORTED_OPERATION`,`Linux runtime owner identity does not match`);if(r.device.platform!==`linux`)throw new e(`UNSUPPORTED_PLATFORM`,`Linux runtime cannot bind this device`);let a=Y(r.device),o=y({owner:`Linux`,openTargetIdentity:`app-name`,host:t.localInteractors,device:r.device,signal:r.scope.signal});return Object.freeze({device:r.device,owner:C,facts:a,operations:Object.freeze({...i(o,a.operations),...a.operations.captureSnapshot.available?Q(t,r):{},...J(t,r,a)}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}function J(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return b({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}function Y(e){let t=e.kind===`device`?S:L,n=e.kind===`device`?S:R,r=x(e,C,{appLog:w,network:w,screenshot:B,snapshot:z,viewport:w,focus:E,gesture:O,scroll:k,typeText:D,touch:E,elementText:T,back:H,orientation:G,tvRemote:G,clipboard:W,systemButton:G,fold:G,telephony:G,triggerAppEvent:G,settings:G,readAlert:G,awaitAlert:G,acceptAlert:G,dismissAlert:G,keyboard:G,audioProbeCapture:K,audioProbeQuery:K,perf:G,readiness:w,lifecycle:a({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:P,clearRuntimeHints:P,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:F,configureProviderPortReverse:I})});return Object.freeze({device:r.device,operations:{...r.operations,..._({capture:X(e,z),customActions:V,withoutActiveApp:X(e,z)}),...u({capture:X(e,B)}),...p({focus:X(e,E)}),...d({unsupported:O,plan:X(e,O),directionalFling:A,multiTouch:j,targetAuthoredDrag:M,viewport:N}),...f({scroll:X(e,k)}),...l({type:X(e,D)}),...Z(e),...h({readTextAtPoint:X(e,T)}),...m({back:X(e,H)}),...g({unsupported:G,home:X(e,U)}),...v({unsupported:W,read:X(e,W),write:X(e,W)})}})}function X(e,t){return e.kind===`device`?S:t}function Z(e){let t=e.kind===`device`?S:E;return o({unsupported:w,tap:t,longPress:t,fill:t})}function Q(e,t){let n=async n=>await e.snapshot.captureSurface(t.device,n.options,c(t.scope.signal,n));return Object.freeze({captureSnapshot:n,captureSnapshotWithCustomActions:n,captureSnapshotWithoutActiveApp:n})}export{q as createLinuxPlatformRuntime};
1
+ import{R as e}from"./sdk-contracts.js";import{an as t,en as n,on as r}from"./sdk-batch.js";import{n as i,t as a}from"./application-lifecycle-runtime.js";import{i as o}from"./touch-runtime.js";import{r as s}from"./gesture-admission.js";import{C as c,I as l,K as u,M as d,O as f,U as p,Y as m,Z as h,_ as g,j as _,p as v}from"./tv-remote-runtime.js";import{r as y}from"./application-lifecycle-interaction.js";import{t as b}from"./local-interactor-operation-set.js";import{r as x}from"./platform-runtime-unavailable.js";const S=Object.freeze({available:!0}),C=n(`linux`),w=r(`unsupported-platform-leaf`),T=r(`unsupported-device-kind`),E=r(`unsupported-device-kind`,`focus is supported only for the Linux desktop device.`),D=r(`unsupported-device-kind`,`type is supported only for the Linux desktop device.`),O=r(`unsupported-device-kind`,`Gestures are supported only for the Linux desktop device.`),k=r(`unsupported-device-kind`,`scroll is supported only for the Linux desktop device.`),A=r(`unsupported-platform-leaf`),j=r(`unsupported-platform-leaf`),M=r(`unsupported-platform-leaf`,s),N=r(`unsupported-platform-leaf`),P=r(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),F=r(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),I=r(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),L=r(`unsupported-device-kind`,`open is supported only for the Linux desktop device.`),R=r(`unsupported-device-kind`,`close is supported only for the Linux desktop device.`),z=r(`unsupported-device-kind`,`snapshot is supported only for the Linux desktop device.`),B=r(`unsupported-device-kind`,`screenshot is supported only for the Linux desktop device.`),V=r(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),H=r(`unsupported-device-kind`,`back is supported only for the Linux desktop device.`),U=r(`unsupported-device-kind`,`home is supported only for the Linux desktop device.`),W=r(`unsupported-device-kind`,`clipboard is supported only for the Linux desktop device.`),G=w,K=r(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function q(n){return Object.freeze({owner:C,ownsDevice:e=>e.platform===`linux`,inspectFacts:async e=>Y(e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,C))throw new e(`UNSUPPORTED_OPERATION`,`Linux runtime owner identity does not match`);if(r.device.platform!==`linux`)throw new e(`UNSUPPORTED_PLATFORM`,`Linux runtime cannot bind this device`);let a=Y(r.device),o=y({owner:`Linux`,openTargetIdentity:`app-name`,host:n.localInteractors,device:r.device,signal:r.scope.signal});return Object.freeze({device:r.device,owner:C,facts:a,operations:Object.freeze({...i(o,a.operations),...a.operations.captureSnapshot.available?Q(n,r):{},...J(n,r,a)}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}function J(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return b({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}function Y(e){let t=e.kind===`device`?S:L,n=e.kind===`device`?S:R,r=x(e,C,{appLog:w,network:w,screenshot:B,snapshot:z,viewport:w,focus:E,gesture:O,scroll:k,typeText:D,touch:E,elementText:T,back:H,orientation:G,tvRemote:G,clipboard:W,systemButton:G,fold:G,telephony:G,triggerAppEvent:G,settings:G,readAlert:G,awaitAlert:G,acceptAlert:G,dismissAlert:G,keyboard:G,audioProbeCapture:K,audioProbeQuery:K,perf:G,readiness:w,lifecycle:a({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:P,clearRuntimeHints:P,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:F,configureProviderPortReverse:I})});return Object.freeze({device:r.device,operations:{...r.operations,...d({capture:X(e,z),customActions:V,withoutActiveApp:X(e,z)}),...l({capture:X(e,B)}),...m({focus:X(e,E)}),...u({unsupported:O,plan:X(e,O),directionalFling:A,multiTouch:j,targetAuthoredDrag:M,viewport:N}),...p({scroll:X(e,k)}),...f({type:X(e,D)}),...Z(e),...h({readTextAtPoint:X(e,T)}),...c({back:X(e,H)}),...g({unsupported:G,home:X(e,U)}),...v({unsupported:W,read:X(e,W),write:X(e,W)})}})}function X(e,t){return e.kind===`device`?S:t}function Z(e){let t=e.kind===`device`?S:E;return o({unsupported:w,tap:t,longPress:t,fill:t})}function Q(e,t){let n=async n=>await e.snapshot.captureSurface(t.device,n.options,_(t.scope.signal,n));return Object.freeze({captureSnapshot:n,captureSnapshotWithCustomActions:n,captureSnapshotWithoutActiveApp:n})}export{q as createLinuxPlatformRuntime};
@@ -1 +1 @@
1
- import{R as e}from"./sdk-contracts.js";import{Zt as t,nn as n,rn as r}from"./sdk-batch.js";import{n as i,t as a}from"./application-lifecycle-runtime.js";import{r as o}from"./gesture-admission.js";import{G as s,S as c,g as l,r as u}from"./tv-remote-runtime.js";import{r as d}from"./application-lifecycle-interaction.js";import{t as f}from"./interactor-operation-catalog.js";import{r as p}from"./platform-runtime-unavailable.js";const m=t(`vega`),h=Object.freeze({available:!0}),g=r(`unsupported-platform-leaf`),_=r(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),v=r(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),y=r(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),b=r(`unsupported-device-kind`,`open currently supports only Vega Virtual Devices.`),x=r(`unsupported-device-kind`,`close currently supports only Vega Virtual Devices.`);function S(t){return Object.freeze({owner:m,ownsDevice:e=>e.platform===`vega`,inspectFacts:async e=>U(e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!n(r.intent.owner,m))throw new e(`UNSUPPORTED_OPERATION`,`Vega runtime owner identity does not match`);if(r.device.platform!==`vega`)throw new e(`UNSUPPORTED_PLATFORM`,`Vega runtime cannot bind this device`);let a=U(r.device),o=d({owner:`Vega`,openTargetIdentity:`app-name`,host:t.localInteractors,device:r.device,signal:r.scope.signal});return Object.freeze({device:r.device,owner:m,facts:a,operations:Object.freeze({...i(o,a.operations),...f({device:r.device,signal:r.scope.signal,resolveInteractor:t.localInteractors.resolve,facts:a.operations})}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}const C=r(`unsupported-platform-leaf`,`screenshot is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),w=r(`unsupported-platform-leaf`,`focus is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),T=r(`unsupported-platform-leaf`,`type is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),E=r(`unsupported-platform-leaf`,`Gestures are not supported on Vega OS: the Vega runtime exposes remote navigation only.`),D=r(`unsupported-platform-leaf`,`scroll is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),O=r(`unsupported-platform-leaf`),k=r(`unsupported-platform-leaf`,o),A=r(`unsupported-platform-leaf`,`orientation is not supported on Vega OS.`),j=r(`unsupported-platform-leaf`,`keyboard is not supported on Vega OS.`),M=r(`unsupported-platform-leaf`,`alert is not supported on Vega OS.`),N=r(`unsupported-platform-leaf`,`settings is not supported on Vega OS.`),P=r(`unsupported-platform-leaf`,`trigger-app-event is not supported on Vega OS.`),F=r(`unsupported-platform-leaf`,`System buttons other than home are not supported on Vega OS.`),I=r(`unsupported-platform-leaf`,`fold is not supported on Vega OS.`),L=r(`unsupported-platform-leaf`,`telephony is not supported on Vega OS.`),R=r(`unsupported-platform-leaf`,`clipboard is not supported on Vega OS.`),z=r(`unsupported-device-kind`,`back currently supports only Vega Virtual Devices.`),B=r(`unsupported-device-kind`,`home currently supports only Vega Virtual Devices.`),V=r(`unsupported-device-kind`,`tv-remote currently supports only Vega Virtual Devices.`),H=r(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function U(e){let t=e.kind===`emulator`&&e.target===`tv`,n=t?h:b,r=t?h:x,i=p(e,m,{appLog:g,network:g,screenshot:C,snapshot:g,viewport:g,focus:w,gesture:E,scroll:D,typeText:T,touch:g,elementText:g,back:z,orientation:A,tvRemote:V,clipboard:R,systemButton:F,fold:I,telephony:L,triggerAppEvent:P,settings:N,readAlert:M,awaitAlert:M,acceptAlert:M,dismissAlert:M,keyboard:j,audioProbeCapture:H,audioProbeQuery:H,perf:g,readiness:g,lifecycle:a({resolveOpenTarget:n,prepareApplicationOpen:n,openApplication:n,applyRuntimeHints:_,clearRuntimeHints:_,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:v,configureProviderPortReverse:y})});return Object.freeze({device:i.device,operations:{...i.operations,...c({back:t?h:z}),...l({unsupported:F,home:t?h:B}),...u({tvRemote:t?h:V}),...s({unsupported:E,multiTouch:O,targetAuthoredDrag:k})}})}export{S as createVegaPlatformRuntime};
1
+ import{R as e}from"./sdk-contracts.js";import{l as t}from"./tv-remote.js";import{an as n,en as r,on as i}from"./sdk-batch.js";import{n as a,t as o}from"./application-lifecycle-runtime.js";import{r as s}from"./gesture-admission.js";import{C as c,K as l,_ as u,r as d}from"./tv-remote-runtime.js";import{r as f}from"./application-lifecycle-interaction.js";import{t as p}from"./interactor-operation-catalog.js";import{r as m}from"./platform-runtime-unavailable.js";const h=r(`vega`),g=Object.freeze({available:!0}),_=i(`unsupported-platform-leaf`),v=i(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),y=i(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),b=i(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),x=i(`unsupported-device-kind`,`open currently supports only Vega Virtual Devices.`),S=i(`unsupported-device-kind`,`close currently supports only Vega Virtual Devices.`);function C(t){return Object.freeze({owner:h,ownsDevice:e=>e.platform===`vega`,inspectFacts:async e=>W(e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!n(r.intent.owner,h))throw new e(`UNSUPPORTED_OPERATION`,`Vega runtime owner identity does not match`);if(r.device.platform!==`vega`)throw new e(`UNSUPPORTED_PLATFORM`,`Vega runtime cannot bind this device`);let i=W(r.device),o=f({owner:`Vega`,openTargetIdentity:`app-name`,host:t.localInteractors,device:r.device,signal:r.scope.signal});return Object.freeze({device:r.device,owner:h,facts:i,operations:Object.freeze({...a(o,i.operations),...p({device:r.device,signal:r.scope.signal,resolveInteractor:t.localInteractors.resolve,facts:i.operations})}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}const w=i(`unsupported-platform-leaf`,`screenshot is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),T=i(`unsupported-platform-leaf`,`focus is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),E=i(`unsupported-platform-leaf`,`type is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),D=i(`unsupported-platform-leaf`,`Gestures are not supported on Vega OS: the Vega runtime exposes remote navigation only.`),O=i(`unsupported-platform-leaf`,`scroll is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),k=i(`unsupported-platform-leaf`),A=i(`unsupported-platform-leaf`,s),j=i(`unsupported-platform-leaf`,`orientation is not supported on Vega OS.`),M=i(`unsupported-platform-leaf`,`keyboard is not supported on Vega OS.`),N=i(`unsupported-platform-leaf`,`alert is not supported on Vega OS.`),P=i(`unsupported-platform-leaf`,`settings is not supported on Vega OS.`),F=i(`unsupported-platform-leaf`,`trigger-app-event is not supported on Vega OS.`),I=i(`unsupported-platform-leaf`,`System buttons other than home are not supported on Vega OS.`),L=i(`unsupported-platform-leaf`,`fold is not supported on Vega OS.`),R=i(`unsupported-platform-leaf`,`telephony is not supported on Vega OS.`),z=i(`unsupported-platform-leaf`,`clipboard is not supported on Vega OS.`),B=i(`unsupported-device-kind`,`back currently supports only Vega Virtual Devices.`),V=i(`unsupported-device-kind`,`home currently supports only Vega Virtual Devices.`),H=i(`unsupported-device-kind`,`tv-remote currently supports only Vega Virtual Devices.`),U=i(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function W(e){let n=e.kind===`emulator`&&e.target===`tv`,r=n?g:x,i=n?g:S,a=m(e,h,{appLog:_,network:_,screenshot:w,snapshot:_,viewport:_,focus:T,gesture:D,scroll:O,typeText:E,touch:_,elementText:_,back:B,orientation:j,tvRemote:H,clipboard:z,systemButton:I,fold:L,telephony:R,triggerAppEvent:F,settings:P,readAlert:N,awaitAlert:N,acceptAlert:N,dismissAlert:N,keyboard:M,audioProbeCapture:U,audioProbeQuery:U,perf:_,readiness:_,lifecycle:o({resolveOpenTarget:r,prepareApplicationOpen:r,openApplication:r,applyRuntimeHints:v,clearRuntimeHints:v,closeApplication:i,finalizeApplicationClose:i,prepareAppleRunner:y,configureProviderPortReverse:b})});return Object.freeze({device:a.device,operations:{...a.operations,...c({back:n?g:B}),...u({unsupported:I,home:n?g:V}),...d({tvRemote:n?g:H,buttonSupport:{supported:t(`vega`),unsupported:{available:!1,reason:`unsupported-platform-leaf`,hint:`This TV remote button is not supported on Vega OS.`}}}),...l({unsupported:D,multiTouch:k,targetAuthoredDrag:A})}})}export{C as createVegaPlatformRuntime};