agent-device 0.21.3 → 0.21.5

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 (134) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.3.apk → agent-device-android-ime-helper-0.21.5.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.5.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.3.manifest.json → agent-device-android-ime-helper-0.21.5.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.3.apk → agent-device-android-snapshot-helper-0.21.5.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.5.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.5.manifest.json +16 -0
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +39 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +9 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -1
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +10 -1
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +26 -124
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +46 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +36 -4
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+MainThreadWork.swift +229 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +15 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +4 -40
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +6 -40
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +30 -9
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +22 -6
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/adb-executor.js +2 -2
  22. package/dist/src/adb-failure.js +1 -1
  23. package/dist/src/agent-browser-process-record.js +1 -1
  24. package/dist/src/agent-device-client.js +2 -2
  25. package/dist/src/api.js +3 -11
  26. package/dist/src/app-launch.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-reconnect.js +1 -1
  29. package/dist/src/app-log-runtime2.js +1 -1
  30. package/dist/src/archive.js +2 -2
  31. package/dist/src/cli-help.js +2 -2
  32. package/dist/src/cli.js +4 -4
  33. package/dist/src/client-metro-companion.js +1 -1
  34. package/dist/src/client-metro.js +1 -1
  35. package/dist/src/client-types.d.ts +69 -4
  36. package/dist/src/code-signature-cache.js +1 -1
  37. package/dist/src/command-tools.js +2 -2
  38. package/dist/src/command.js +1 -1
  39. package/dist/src/connection-runtime.js +1 -1
  40. package/dist/src/contracts.js +1 -1
  41. package/dist/src/daemon-client-lifecycle.js +1 -1
  42. package/dist/src/daemon-shutdown-report.js +1 -1
  43. package/dist/src/device-claim-rule.js +1 -1
  44. package/dist/src/device-input-state.d.ts +10 -8
  45. package/dist/src/device-inventory-context.js +1 -1
  46. package/dist/src/device-session.js +1 -1
  47. package/dist/src/diagnostics.js +1 -1
  48. package/dist/src/error.js +2 -2
  49. package/dist/src/exec.js +1 -1
  50. package/dist/src/file.js +1 -1
  51. package/dist/src/find.js +1 -1
  52. package/dist/src/gesture-runtime.js +1 -1
  53. package/dist/src/helper.js +1 -1
  54. package/dist/src/index.js +1 -1
  55. package/dist/src/install-source-network-transport.js +1 -1
  56. package/dist/src/interaction2.js +1 -1
  57. package/dist/src/interactor.js +4 -4
  58. package/dist/src/internal/bin.js +1 -1
  59. package/dist/src/internal/daemon.js +2 -2
  60. package/dist/src/internal/png-worker.js +1 -1
  61. package/dist/src/ios-client.js +121 -7
  62. package/dist/src/ios-snapshot-adapter.js +1 -1
  63. package/dist/src/ios-system-surface.js +1 -1
  64. package/dist/src/limrun-delta-sync-omitted.js +1 -0
  65. package/dist/src/limrun.d.ts +0 -1598
  66. package/dist/src/location-coordinates.js +1 -1
  67. package/dist/src/mechanics.js +16 -16
  68. package/dist/src/output-common.js +2 -0
  69. package/dist/src/owner-identity.js +1 -1
  70. package/dist/src/perf-runtime-operation-builder.js +1 -1
  71. package/dist/src/perf-runtime-plan.js +1 -1
  72. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  73. package/dist/src/platform-runtime-app-log-android-transport.js +1 -1
  74. package/dist/src/platform-runtime-app-log-process.js +1 -1
  75. package/dist/src/platform-runtime-host.js +1 -1
  76. package/dist/src/platform-runtime-operation-host.js +2 -2
  77. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  78. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  79. package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
  80. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  81. package/dist/src/process.js +1 -1
  82. package/dist/src/proxy.js +1 -1
  83. package/dist/src/quality-warnings.js +1 -1
  84. package/dist/src/react-native.js +1 -1
  85. package/dist/src/record-runtime.js +1 -1
  86. package/dist/src/recording-stop-observation.js +1 -0
  87. package/dist/src/registry.js +35 -36
  88. package/dist/src/replay-divergence.js +1 -1
  89. package/dist/src/reporting.js +11 -9
  90. package/dist/src/result-serialization.js +1 -1
  91. package/dist/src/runner-cache-metadata.js +1 -1
  92. package/dist/src/runner-client.js +1 -1
  93. package/dist/src/runner-disposal.js +1 -1
  94. package/dist/src/runner-operations-facade.js +1 -1
  95. package/dist/src/runner.js +1 -1
  96. package/dist/src/runtime.js +3 -3
  97. package/dist/src/runtime10.js +1 -1
  98. package/dist/src/runtime2.js +4 -4
  99. package/dist/src/runtime3.js +1 -1
  100. package/dist/src/runtime4.js +4 -4
  101. package/dist/src/runtime5.js +1 -1
  102. package/dist/src/runtime6.js +1 -1
  103. package/dist/src/runtime9.js +1 -1
  104. package/dist/src/screen-recording-completion.js +1 -1
  105. package/dist/src/screen-recording-resource-recovery.js +1 -1
  106. package/dist/src/screenshot-result.js +1 -1
  107. package/dist/src/sdk-contracts.js +2 -2
  108. package/dist/src/sdk-selectors.d.ts +36 -24
  109. package/dist/src/selector-runtime.js +1 -1
  110. package/dist/src/semantic-index.js +1 -1
  111. package/dist/src/session-observation.js +1 -1
  112. package/dist/src/session-snapshot.js +1 -1
  113. package/dist/src/session-store.js +2 -2
  114. package/dist/src/session2.js +5 -5
  115. package/dist/src/snapshot-process.js +1 -1
  116. package/dist/src/snapshot-runtime.js +1 -1
  117. package/dist/src/snapshot.js +1 -1
  118. package/dist/src/snapshot4.js +1 -1
  119. package/dist/src/stop-sequence.js +1 -0
  120. package/dist/src/success-text.js +1 -1
  121. package/dist/src/text-entry-focus.js +1 -0
  122. package/dist/src/tool-provider.js +1 -1
  123. package/dist/src/tool-provider2.js +1 -1
  124. package/dist/src/tool-provider3.js +1 -1
  125. package/dist/src/type-text-runtime.js +1 -1
  126. package/dist/src/video.js +2 -2
  127. package/dist/src/yauzl.js +1 -0
  128. package/package.json +2 -2
  129. package/server.json +2 -2
  130. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.3.apk.sha256 +0 -1
  131. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.3.apk.sha256 +0 -1
  132. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.3.manifest.json +0 -17
  133. package/dist/src/audio-probe-support.js +0 -1
  134. package/dist/src/screen-recording-live-handle.js +0 -1
@@ -1,5 +1,5 @@
1
- import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Gt as n,Zt as r}from"./sdk-batch.js";import{n as i,r as a,t as o}from"./application-lifecycle-runtime.js";import{i as s}from"./touch-runtime.js";import{A as c,D as l,G as u,H as d,I as f,L as p,N as m,R as h,a as g,b as ee,d as te,g as ne,i as re,m as ie,s as ae,t as oe,v as se,w as ce,x as le,z as ue}from"./alert-runtime.js";import{n as de}from"./audio-probe-runtime.js";import{n as fe}from"./perf-runtime.js";import{a as pe,n as me}from"./durable-resource.js";import{n as he}from"./async-lifecycle.js";import{i as ge,l as _e,n as ve,r as ye,t as be}from"./src7.js";import{t as xe}from"./screen-recording-live-handle.js";import{n as Se,r as Ce,t as we}from"./audio-probe-support.js";import{n as Te}from"./screen-recording-runtime.js";import{t as Ee}from"./mp4-atoms.js";import{readAndroidAppStateWithExecutor as De}from"./app-state.js";import{i as Oe,t as ke}from"./gesture-admission.js";import{t as Ae}from"./local-interactor-operation-set.js";import{a as je,i as Me,n as Ne,r as Pe,t as Fe}from"./perf-runtime-operation-builder.js";import{t as Ie}from"./app-log-runtime.js";import{n as _,r as Le}from"./managed-device-scope.js";import{a as v,i as Re,n as ze,o as Be}from"./application-lifecycle-interaction.js";import y from"node:path";import b from"node:fs";function Ve(e){return we(e)?Object.freeze({available:!0}):e.kind===`emulator`?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 probe capture is supported for Android emulators on macOS hosts.`})}function He(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Fe({platform:`Android`,expectedProfileKind:`simpleperf`,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(n,e)}),perfFrames:async({appId:e})=>({metric:e?await Me(t().sampleFrames(n,e)):Ne(`Android`,`package`),sampling:{method:`adb-shell-dumpsys-gfxinfo-framestats`,description:`Rendered-frame health from the current adb shell dumpsys gfxinfo <package> framestats window. Dropped frames use Android gfxinfo janky-frame/frame-deadline data when available; this is not video recording FPS.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}),perfMemorySample:async({appId:e})=>({metric:e?await Me(t().sampleMemory(n,e)):Ne(`Android`,`package`),sampling:{method:`adb-shell-dumpsys-meminfo`,description:`Memory snapshot from adb shell dumpsys meminfo <package>. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:5}}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`android-hprof`,s=Ue();if(o!==`android-hprof`)return je(`Android`,o,s,`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`);if(!e)throw Pe();let c=i??y.join(a,`memory-android-hprof-${We()}.hprof`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`adb-shell-am-dumpheap`,description:`Java heap dump captured with adb shell am dumpheap, pulled to a local artifact path.`,defaultKind:`android-hprof`,artifactOnly:!0}}}})}function Ue(){return{platform:`android`,defaultKind:`android-hprof`,androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:`Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice.`}}function We(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function Ge(t){if(!/^[a-zA-Z0-9._:-]+$/.test(t))throw new e(`INVALID_ARGS`,`Invalid Android package name for logs: ${t}`)}const x=Object.freeze({resourceKind:Ie,version:1,encode:e=>({...e}),decode:e=>e.transport!==`android-logcat-local`&&e.transport!==`android-logcat-transport-composed`||!qe(e.outputPath)||!qe(e.pidPath)?{status:`invalid`,message:`Invalid Android app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:e.transport,outputPath:e.outputPath,pidPath:e.pidPath})}});function Ke(e){let t=x.decode(e.descriptor);if(t.status!==`decoded`)throw TypeError(t.message);return me({resourceKind:Ie,sessionId:e.sessionId,device:{id:e.device.id,family:`android`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:pe(x,t.descriptor)})}function qe(e){return typeof e==`string`&&e.trim().length>0}function Je(e){return ye(e,{family:`android`,backend:`android`,label:`Android`,codec:x,startUnavailableHint:`The selected Android transport cannot start a background adb logcat stream.`,cleanupFailureMessage:`Android app-log cleanup did not settle every owned resource`,doctor:async({host:e,device:t,signal:n},r)=>await Ye(e,t.id,r,n),validateStart:({input:e})=>Ge(e.appBundleId),process:async({host:e,device:t,input:n})=>({resolvePid:async r=>await ge(e,Xe(t.id,n.appBundleId),r),command:e=>({kind:`android-adb`,serial:t.id,args:[`logcat`,`-v`,`time`,`--pid`,e],options:{allowFailure:!0}})}),descriptor:({artifacts:e,transport:t})=>({transport:t.mode===`transport-composed`?`android-logcat-transport-composed`:`android-logcat-local`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>Ke({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function Ye(e,t,n,r){let i={};return i.adbAvailable=await Ce(async()=>Se(await e.commands.run({executable:`adb`,args:[`-s`,t,`shell`,`echo`,`ok`],allowFailure:!0,timeoutMs:1e3},r)),r),n&&(i.androidPidVisible=await Ce(async()=>!!await ge(e,Xe(t,n),r),r)),{backend:`android`,checks:i,notes:n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}}function Xe(e,t){return{executable:`adb`,args:[`-s`,e,`shell`,`pidof`,t],allowFailure:!0,timeoutMs:5e3}}async function Ze(e,t,n,r){let i=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),a=ve(i.text,{...n,path:i.path,exists:i.exists,lineNumberOffset:i.skippedLines,backend:`android`}),o=[],s=await $e(e,t,n,r);if(s&&n.appBundleId){Ge(n.appBundleId);let c=await tt(e,t,n.appBundleId,r);if(c){let e=ve(c.text,{...n,path:`${i.path} (adb logcat recovery)`,exists:!0,backend:`android`});e.dump.entries.length>0&&(a=be(e,a,n.maxEntries),o.push(s.reason===`stale-active`?`Session app log stream was still bound to prior Android PID ${s.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`))}}return n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&o.length===0&&o.push(`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):o.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`),a.dump.entries.length===0&&o.push(`No HTTP(s) entries were found in recent session app logs.`),Object.freeze({source:`app-log`,backend:`android`,dump:a.dump,notes:Object.freeze(o)})}async function Qe(e,t,n){n.throwIfAborted();try{let r=await e.commands.run(t,n);return n.throwIfAborted(),r}catch{n.throwIfAborted();return}}async function $e(e,t,n,r){if(!n.appBundleId||n.appLogSnapshot?.state===void 0)return;if(n.appLogSnapshot.state!==`active`)return{reason:`inactive`};let i=et(await e.appLogs.readProcessMarker(n.sessionId));if(!i)return;let a=await nt(e,t.id,n.appBundleId,r);if(!(!a||a===i))return{reason:`stale-active`,trackedPid:i}}function et(e){if(e.status===`decoded`)return/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(e.marker.command)?.[1]}async function tt(e,t,n,r){let i=await nt(e,t.id,n,r),a=await Qe(e,{executable:`adb`,args:[`-s`,t.id,`logcat`,`-d`,`-v`,`time`,`-t`,`4000`],allowFailure:!0,timeoutMs:3e3},r);if(!a||a.exitCode!==0||!a.stdout.trim())return;let o=rt(a.stdout,n,i);if(o.length===0)return;let s=new Set(o),c=a.stdout.split(`
1
+ import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Gt as n,Zt as r}from"./sdk-batch.js";import{i,n as a}from"./recording-stop-observation.js";import{n as o,r as s,t as c}from"./application-lifecycle-runtime.js";import{i as l}from"./touch-runtime.js";import{A as u,D as d,G as f,H as p,I as m,L as h,N as g,R as ee,a as te,b as ne,d as re,g as ie,i as ae,m as oe,s as se,t as ce,v as le,w as ue,x as de,z as fe}from"./alert-runtime.js";import{n as pe}from"./audio-probe-runtime.js";import{n as me}from"./perf-runtime.js";import{a as he,n as ge}from"./durable-resource.js";import{n as _e}from"./async-lifecycle.js";import{i as ve,l as ye,n as be,r as xe,t as Se}from"./src7.js";import{n as Ce}from"./screen-recording-completion.js";import{a as we,i as Te,r as Ee,t as De}from"./stop-sequence.js";import{n as Oe}from"./screen-recording-runtime.js";import{t as ke}from"./mp4-atoms.js";import{readAndroidAppStateWithExecutor as Ae}from"./app-state.js";import{i as je,t as Me}from"./gesture-admission.js";import{t as Ne}from"./local-interactor-operation-set.js";import{a as Pe,i as Fe,n as Ie,r as Le,t as Re}from"./perf-runtime-operation-builder.js";import{t as ze}from"./app-log-runtime.js";import{n as _,r as Be}from"./managed-device-scope.js";import{a as Ve,i as He,n as Ue,o as We}from"./application-lifecycle-interaction.js";import v from"node:path";import y from"node:fs";function Ge(e){return Ee(e)?Object.freeze({available:!0}):e.kind===`emulator`?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 probe capture is supported for Android emulators on macOS hosts.`})}function Ke(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Re({platform:`Android`,expectedProfileKind:`simpleperf`,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(n,e)}),perfFrames:async({appId:e})=>({metric:e?await Fe(t().sampleFrames(n,e)):Ie(`Android`,`package`),sampling:{method:`adb-shell-dumpsys-gfxinfo-framestats`,description:`Rendered-frame health from the current adb shell dumpsys gfxinfo <package> framestats window. Dropped frames use Android gfxinfo janky-frame/frame-deadline data when available; this is not video recording FPS.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}),perfMemorySample:async({appId:e})=>({metric:e?await Fe(t().sampleMemory(n,e)):Ie(`Android`,`package`),sampling:{method:`adb-shell-dumpsys-meminfo`,description:`Memory snapshot from adb shell dumpsys meminfo <package>. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:5}}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`android-hprof`,s=qe();if(o!==`android-hprof`)return Pe(`Android`,o,s,`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`);if(!e)throw Le();let c=i??v.join(a,`memory-android-hprof-${Je()}.hprof`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`adb-shell-am-dumpheap`,description:`Java heap dump captured with adb shell am dumpheap, pulled to a local artifact path.`,defaultKind:`android-hprof`,artifactOnly:!0}}}})}function qe(){return{platform:`android`,defaultKind:`android-hprof`,androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:`Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice.`}}function Je(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function Ye(t){if(!/^[a-zA-Z0-9._:-]+$/.test(t))throw new e(`INVALID_ARGS`,`Invalid Android package name for logs: ${t}`)}const b=Object.freeze({resourceKind:ze,version:1,encode:e=>({...e}),decode:e=>e.transport!==`android-logcat-local`&&e.transport!==`android-logcat-transport-composed`||!Ze(e.outputPath)||!Ze(e.pidPath)?{status:`invalid`,message:`Invalid Android app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:e.transport,outputPath:e.outputPath,pidPath:e.pidPath})}});function Xe(e){let t=b.decode(e.descriptor);if(t.status!==`decoded`)throw TypeError(t.message);return ge({resourceKind:ze,sessionId:e.sessionId,device:{id:e.device.id,family:`android`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:he(b,t.descriptor)})}function Ze(e){return typeof e==`string`&&e.trim().length>0}function Qe(e){return xe(e,{family:`android`,backend:`android`,label:`Android`,codec:b,startUnavailableHint:`The selected Android transport cannot start a background adb logcat stream.`,cleanupFailureMessage:`Android app-log cleanup did not settle every owned resource`,doctor:async({host:e,device:t,signal:n},r)=>await $e(e,t.id,r,n),validateStart:({input:e})=>Ye(e.appBundleId),process:async({host:e,device:t,input:n})=>({resolvePid:async r=>await ve(e,et(t.id,n.appBundleId),r),command:e=>({kind:`android-adb`,serial:t.id,args:[`logcat`,`-v`,`time`,`--pid`,e],options:{allowFailure:!0}})}),descriptor:({artifacts:e,transport:t})=>({transport:t.mode===`transport-composed`?`android-logcat-transport-composed`:`android-logcat-local`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>Xe({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function $e(e,t,n,r){let i={};return i.adbAvailable=await we(async()=>Te(await e.commands.run({executable:`adb`,args:[`-s`,t,`shell`,`echo`,`ok`],allowFailure:!0,timeoutMs:1e3},r)),r),n&&(i.androidPidVisible=await we(async()=>!!await ve(e,et(t,n),r),r)),{backend:`android`,checks:i,notes:n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}}function et(e,t){return{executable:`adb`,args:[`-s`,e,`shell`,`pidof`,t],allowFailure:!0,timeoutMs:5e3}}async function tt(e,t,n,r){let i=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),a=be(i.text,{...n,path:i.path,exists:i.exists,lineNumberOffset:i.skippedLines,backend:`android`}),o=[],s=await rt(e,t,n,r);if(s&&n.appBundleId){Ye(n.appBundleId);let c=await at(e,t,n.appBundleId,r);if(c){let e=be(c.text,{...n,path:`${i.path} (adb logcat recovery)`,exists:!0,backend:`android`});e.dump.entries.length>0&&(a=Se(e,a,n.maxEntries),o.push(s.reason===`stale-active`?`Session app log stream was still bound to prior Android PID ${s.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`))}}return n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&o.length===0&&o.push(`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):o.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`),a.dump.entries.length===0&&o.push(`No HTTP(s) entries were found in recent session app logs.`),Object.freeze({source:`app-log`,backend:`android`,dump:a.dump,notes:Object.freeze(o)})}async function nt(e,t,n){n.throwIfAborted();try{let r=await e.commands.run(t,n);return n.throwIfAborted(),r}catch{n.throwIfAborted();return}}async function rt(e,t,n,r){if(!n.appBundleId||n.appLogSnapshot?.state===void 0)return;if(n.appLogSnapshot.state!==`active`)return{reason:`inactive`};let i=it(await e.appLogs.readProcessMarker(n.sessionId));if(!i)return;let a=await ot(e,t.id,n.appBundleId,r);if(!(!a||a===i))return{reason:`stale-active`,trackedPid:i}}function it(e){if(e.status===`decoded`)return/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(e.marker.command)?.[1]}async function at(e,t,n,r){let i=await ot(e,t.id,n,r),a=await nt(e,{executable:`adb`,args:[`-s`,t.id,`logcat`,`-d`,`-v`,`time`,`-t`,`4000`],allowFailure:!0,timeoutMs:3e3},r);if(!a||a.exitCode!==0||!a.stdout.trim())return;let o=st(a.stdout,n,i);if(o.length===0)return;let s=new Set(o),c=a.stdout.split(`
2
2
  `).filter(e=>{if(!e.trim())return!1;if(e.includes(n))return!0;let t=/\(\s*(\d+)\)\s*:/.exec(e)?.[1];return!!(t&&s.has(t))}).join(`
3
- `);return c.trim()?{text:c,pids:o}:void 0}async function nt(e,t,n,r){let i=await Qe(e,{executable:`adb`,args:[`-s`,t,`shell`,`pidof`,n],allowFailure:!0},r);if(!i)return;let a=i.stdout.trim().split(/\s+/)[0];return a&&/^\d+$/.test(a)?a:void 0}function rt(e,t,n){let r=new Set(n?[n]:[]),i=t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),a=[RegExp(`\\bStart proc\\s+(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`\\b(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`${i}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,`i`),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${i}`,`i`)];for(let n of e.split(`
4
- `))if(n.includes(t))for(let e of a){let t=e.exec(n)?.[1];t&&/^\d+$/.test(t)&&r.add(t)}return Object.freeze([...r])}const it=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,at=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function ot(e){return lt(e)&&ut(e)&&dt(e)}function st(e){if(!S(e))return!1;let t=e;return ft(t)&&pt(t)&&mt(t)&&ht(t)&&(t.completion===void 0||xt(t))}function ct(e,t){return St(e,t)&&Ct(e,t.outputPath,t.clientOutputPath)}function lt(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&at.test(e.manifestPath)&&typeof e.outputPath==`string`}function ut(e){return(e.clientOutputPath===void 0||typeof e.clientOutputPath==`string`)&&C(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function dt(e){return wt(e.transportMode)&&Tt(e.exportQuality)&&w(e.activeSessionApp)}function ft(e){return e.version===1&&e.resourceKind===`screen-recording`&&typeof e.fenceToken==`string`&&Number.isInteger(e.fenceGeneration)&&typeof e.sessionId==`string`&&typeof e.deviceId==`string`&&Number.isFinite(e.startedAt)}function pt(e){return typeof e.outputPath==`string`&&(e.clientOutputPath===void 0||typeof e.clientOutputPath==`string`)&&C(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function mt(e){return w(e.activeSessionApp)&&Tt(e.exportQuality)&&wt(e.transportMode)&&(e.pendingRemotePath===void 0||Et(e.pendingRemotePath))}function ht(e){return Array.isArray(e.chunks)&&e.chunks.every(gt)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||_t(e.completion))}function gt(e,t){if(!S(e))return!1;let n=e;return n.index===t+1&&Et(n.remotePath)&&Dt(n.remotePid)&&Dt(n.remoteStartTime)}function _t(e){if(!S(e))return!1;let t=e;return vt(t)&&yt(t)&&(t.chunks===void 0||t.chunks.every(bt))}function vt(e){return typeof e.backend==`string`&&typeof e.outPath==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)&&Number.isFinite(e.startedAt)&&Number.isFinite(e.completedAt)&&(e.capturedDurationMs===void 0||Number.isFinite(e.capturedDurationMs))}function yt(e){return C(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`&&w(e.activeSessionApp)}function bt(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function xt(e){let t=e.completion;return t!==void 0&&St(t,e)&&t.startedAt===e.startedAt&&Ct(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function St(e,t){return e.backend===`adb screenrecord`&&e.outPath===t.outputPath&&e.clientOutPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&Ot(e.activeSessionApp,t.activeSessionApp)}function Ct(e,t,n,r=e.chunks===void 0?1:e.chunks.length){return r===1?e.chunks===void 0:e.chunks?.length===r&&e.chunks.every((e,r)=>e.path===kt(t,r+1)&&e.clientOutPath===(n===void 0?void 0:kt(n,r+1)))}function S(e){return typeof e==`object`&&!!e}function C(e){return e===`app`||e===`device`||e===`system`}function wt(e){return e===`local`||e===`transport-composed`}function Tt(e){return e===void 0||e===`medium`||e===`high`}function w(e){return e===void 0||S(e)&&typeof e.bundleId==`string`&&(e.name===void 0||typeof e.name==`string`)}function Et(e){return typeof e==`string`&&it.test(e)}function Dt(e){return typeof e==`string`&&/^\d+$/.test(e)}function Ot(e,t){return JSON.stringify(e)===JSON.stringify(t)}function kt(e,t){if(t===1)return e;let n=e.lastIndexOf(`.`),r=n>e.lastIndexOf(`/`)?e.slice(0,n):e,i=n>e.lastIndexOf(`/`)?e.slice(n):`.mp4`;return`${r}.part-${String(t).padStart(3,`0`)}${i}`}const T=Object.freeze({resourceKind:Te,version:1,encode:e=>({...e}),decode:e=>ot(e)?{status:`decoded`,descriptor:Object.freeze({backend:`adb-screenrecord`,manifestPath:e.manifestPath,outputPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutputPath:e.clientOutputPath},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,transportMode:e.transportMode,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality}})}:{status:`invalid`,message:`Invalid Android screen-recording descriptor`}});function E(e,t,n,r,i,a=`local`){return Object.freeze({version:1,resourceKind:`screen-recording`,fenceToken:t.fence.token,fenceGeneration:t.fence.generation,sessionId:t.sessionId,deviceId:e.id,startedAt:n,outputPath:t.outputPath,...t.clientOutputPath===void 0?{}:{clientOutputPath:t.clientOutputPath},scope:t.scope,showTouches:t.showTouches,recordOnlySession:t.recordOnlySession,...t.activeSessionApp===void 0?{}:{activeSessionApp:t.activeSessionApp},...t.exportQuality===void 0?{}:{exportQuality:t.exportQuality},chunks:r,...i===void 0?{}:{pendingRemotePath:i},transportMode:a})}function At(e,t){return Object.freeze({...e,completion:t})}function D(e){try{let t=e&&JSON.parse(e);return st(t)?t:void 0}catch{return}}function jt(e,t,n){return e.deviceId===t.id&&e.deviceId===n.device.id&&e.fenceToken===n.fence.token&&e.fenceGeneration===n.fence.generation&&e.sessionId===n.sessionId}function Mt(e,t){return e.outputPath===t.outputPath&&e.clientOutputPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&JSON.stringify(e.activeSessionApp)===JSON.stringify(t.activeSessionApp)&&e.exportQuality===t.exportQuality&&e.transportMode===t.transportMode&&(e.completion===void 0||ct(e.completion,t))}function O(e){switch(e){case`missing`:case`ownership-lost`:case`foreign-writer`:return!0;case`owned-alive`:case`uncertain`:return!1}}function Nt(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const Pt=1e4,Ft=1e3;var k=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}};function A(e,t=Date.now()){return[...new Set(e?[e,`/sdcard`,`/data/local/tmp`]:[`/sdcard`,`/data/local/tmp`])].map(e=>`${e}/agent-device-recording-${t}.mp4`)}async function It(e,t,n,r){let i;try{if(i=(await e.start({remotePath:t,quality:n.exportQuality??`medium`},r)).process,!/^\d+$/.test(i.pid)||!/^\d+$/.test(i.startTime)||i.remotePath!==t)throw Error(`Android screenrecord returned an invalid process identity`);if(!await Vt(e,t,i,r))throw Error(`Android screenrecord did not begin producing frames`);return{index:1,remotePath:t,remotePid:i.pid,remoteStartTime:i.startTime}}catch(t){throw i&&Lt(i)&&!await Ht(e,i)?new k(t):r?.aborted?r.reason:t}}function Lt(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function j(e,t){let n=!1,r;for(let i of[...t].reverse())try{n=await N(e,i)||n}catch(e){r??=e}if(r)throw r;return n}async function Rt(e,t){for(let n of t){let t;for(let r=0;r<3;r+=1){let i=await e.size(n.remotePath);if(typeof i==`number`&&i>0&&i===t)break;if(t=typeof i==`number`&&i>0?i:void 0,r===2)throw Error(`Android recording artifact is not stable: ${n.remotePath}`);await new Promise(e=>setTimeout(e,250))}}}async function zt(e,t,n,r){let i=[];for(let[a,o]of t.entries()){let t=a===0?n:Kt(n,a+1);await Ut(e,o.remotePath,t);let s=a===0||r===void 0?r:Kt(r,a+1);i.push({index:a+1,path:t,...s===void 0?{}:{clientOutPath:s}})}return Object.freeze(i)}async function M(e,t){let n;for(let r of t)try{if(!await e.remove(r.remotePath))throw Error(`failed to remove Android recording artifact: ${r.remotePath}`)}catch(e){n??=e}if(n)throw n}async function Bt(e,t){try{await j(e,t)}finally{await M(e,t)}}async function Vt(e,t,n,r){for(let i=0;i<3;i+=1){if(r?.throwIfAborted(),await e.exists(t,r)===!0)return!0;if(await e.inspect(n,r)!==`owned-alive`)return!1;i<2&&await new Promise(e=>setTimeout(e,250))}return!0}async function Ht(e,t){try{let n=await e.stop(t,{force:!0});return(n===`stopped`||n===`already-missing`)&&await e.remove(t.remotePath)}catch{return!1}}async function N(e,t){if(!t)return!1;let n={pid:t.remotePid,remotePath:t.remotePath,startTime:t.remoteStartTime},r=await e.stop(n);if(r===`already-missing`)return!0;if(r===`ownership-lost`)throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.remotePid}`);if(await Wt(e,n))return!1;let i=await e.stop(n,{force:!0});if(i===`stopped`||i===`already-missing`)return!1;throw Error(`failed to stop Android screenrecord pid ${t.remotePid}`)}async function Ut(e,t,n){for(let r=0;r<3;r+=1){let i=await e.pullPlayable({remotePath:t,outputPath:n});if(i.exitCode===0&&i.playable)return;r+1<3&&await Gt(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function Wt(e,t){for(let n=0;n<=Pt;n+=Ft){let r=await e.inspect(t);if(r===`missing`)return!0;if(O(r))throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.pid}`);n<Pt&&await Gt(Ft)}return!1}function Gt(e){return new Promise(t=>setTimeout(t,e))}function Kt(e,t){let n=y.parse(e);return y.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}async function P(e,t,n,r){await e.writeManifest({manifestPath:t,contents:JSON.stringify(n)},r)}async function F(e,t){if(!await e.removeManifest(t))throw Error(`failed to remove Android recording manifest: ${t}`)}async function qt(e,t){let n=(await Jt(e)).flatMap(n=>Yt(n,t,e.mode));for(let t of n)await Zt(e,t.evidence,t.manifestPath)}async function Jt(e){return await Promise.all(A(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function Yt(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw en(e.manifestPath,e.read.message);let r=D(e.read.contents);if(r===void 0)throw tn(e.manifestPath);if(r.transportMode!==n)throw nn(e.manifestPath,r,n);if(!Xt(r,t))throw rn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function Xt(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function Zt(e,t,n){if(await Qt(e,t),await M(e,t.chunks),await $t(e,t),await F(e,n),(await e.readManifest(n)).status!==`missing`)throw sn(n)}async function Qt(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!Nt(t))throw t===`uncertain`?cn(n.remotePath):an(n.remotePath,t===`owned-alive`?`named-recorder`:`other-recorder`)}let n=t.pendingRemotePath;if(n===void 0)return;let r=await e.probeRunningWriters(n);if(r.writers.length>0)throw an(n,`other-recorder`);if(!r.conclusive)throw cn(n)}async function $t(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw on(n)}function en(t,n){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unavailable: ${t}`,{reason:`native_recovery_evidence_unavailable`,manifestPath:t,hint:`Confirm the device is online and its storage readable, then run record start again.`},Error(n))}function tn(t){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unreadable: ${t}`,{reason:`native_recovery_evidence_unreadable`,manifestPath:t,hint:I(t)})}function nn(t,n,r){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence was written by the ${n.transportMode} transport, not this ${r} one: ${t}`,{reason:`native_recovery_evidence_transport_mismatch`,manifestPath:t,evidenceTransportMode:n.transportMode,hint:I(t)})}function rn(t,n,r){return new e(`DEVICE_IN_USE`,`Android screenrecord native recovery evidence already exists: ${t} (open recording of session "${n.sessionId}" on ${r.id})`,{reason:`native_recovery_evidence_open`,manifestPath:t,sessionId:n.sessionId,retriable:!1,hint:`Run record stop --session ${n.sessionId} to retire it, or close that session. If it is already closed, ${I(t)}`})}function an(t,n){let r=n===`named-recorder`;return new e(`DEVICE_IN_USE`,`Android screenrecord recovery evidence is retained: ${r?`its recorder`:`another recorder`} is writing ${t}`,{reason:`native_recording_artifact_claimed`,remotePath:t,writer:n,...r?{retriable:!1}:{},hint:r?`Run record stop for the session that owns that recording before starting another.`:`Android ends any recorder after 180 seconds. Run record start again once that recorder has stopped.`})}function on(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence could not remove ${t}`,{reason:`native_recording_artifact_removal_failed`,remotePath:t,hint:`Confirm the device is online and run record start again.`})}function sn(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence removal could not be confirmed: ${t}`,{reason:`native_recovery_evidence_retirement_unconfirmed`,manifestPath:t,hint:`Run record start again; the marker is retired from the beginning.`})}function cn(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence cannot be safely retired: ${t}`,{reason:`native_recording_recorder_unproven`,remotePath:t,hint:`Confirm the device is online and run record start again.`})}function I(e){return`no recording session can retire this marker; remove it on the device with \`adb shell rm -f ${e}\`.`}async function ln(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await qt(t,n),await o();let s;for(let e of A(void 0)){let o=t.manifestPathFor(e);await P(t,o,E(n,r,i,[],e,t.mode),a);let c,l;try{l=Date.now(),c=await It(t,e,r,a)}catch(e){if(a.aborted)throw await un(t,o,e),a.reason;await pn(t,o,e),s=e;continue}try{await P(t,o,E(n,r,i,[c],void 0,t.mode),a)}catch(e){throw await dn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function un(e,t,n){n instanceof k||await F(e,t).catch(()=>{})}async function dn(e,t,n){try{await Bt(e,[n])}catch{return}await F(e,t).catch(()=>{})}async function fn(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s}=e,c;for(let e of A(s)){await P(t,o,E(n,r,i,a,e,t.mode));try{return await It(t,e,r)}catch(e){if(e instanceof k)throw e;try{await P(t,o,E(n,r,i,a,void 0,t.mode))}catch{throw new k(e)}c=e}}throw c??Error(`failed to start next Android recording chunk`)}async function pn(e,t,n){if(n instanceof k)throw n;try{await F(e,t)}catch{throw new k(n)}}const mn=[`moov`,`mvhd`];function hn(e){let t=_n(e);if(!t)return;let n=t[0];if(n===1)return gn(t.readUInt32BE(20),Number(t.readBigUInt64BE(24)));if(n!==0)return;let r=t.readUInt32BE(16);if(r!==4294967295)return gn(t.readUInt32BE(12),r)}function gn(e,t){if(!(e<=0||t<0||!Number.isSafeInteger(t)))return Math.round(t*1e3/e)}function _n(e){let t=Ee(e,mn);if(!t||!Number.isSafeInteger(t.size))return;let n=t.offset+t.headerSize;if(t.size-t.headerSize<32)return;let r=Buffer.alloc(32),i;try{return i=b.openSync(e,`r`),b.readSync(i,r,0,r.length,n)===r.length?r:void 0}catch{return}finally{i!==void 0&&b.closeSync(i)}}function vn(e){let t=yn(e.chunkPaths);if(t===void 0)return{};let n=e.stoppedAtMs-e.startedAtMs;return n-t<2e3?{capturedDurationMs:t}:{capturedDurationMs:t,idleTailWarning:`Android screenrecord encodes a frame only when the screen changes, so this video ends at the last frame it encoded: it covers ${bn(t)}s of the ${bn(n)}s recording window.`}}function yn(e){let t=0;for(let n of e){let e=hn(n);if(e===void 0)return;t+=e}return t}function bn(e){return(e/1e3).toFixed(1)}function xn(e,t){return Object.freeze({backend:`adb screenrecord`,outPath:e.outputPath,...e.clientOutputPath?{clientOutPath:e.clientOutputPath}:{},startedAt:t,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp?{activeSessionApp:e.activeSessionApp}:{},...e.exportQuality?{exportQuality:e.exportQuality}:{},gestureEvents:[]})}async function Sn(e){let{host:t,recording:n,chunks:r,targetLabel:i,reachedLimit:a,startedAtMs:o,stoppedAtMs:s}=e,c=r.length>1,l=await t.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!c&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:i}),u=vn({chunkPaths:r.map(e=>e.path),startedAtMs:o,stoppedAtMs:s}),d=[...l.warning?[l.warning]:[],...a?[`Android adb screenrecord stopped before record stop, likely after reaching the 180s platform limit. The MP4 may be truncated; final interactions after the limit are not in the video.`]:[],...c?[`Android adb screenrecord is capped at 180s, so this recording was split into multiple MP4 chunks.`]:[],...u.idleTailWarning?[u.idleTailWarning]:[]],f=Date.now();return{status:`completed`,result:{backend:n.backend,outPath:n.outPath,...n.clientOutPath?{clientOutPath:n.clientOutPath}:{},startedAt:n.startedAt,completedAt:f,scope:n.scope,showTouches:n.showTouches,recordOnlySession:n.recordOnlySession,...n.activeSessionApp?{activeSessionApp:n.activeSessionApp}:{},...c?{chunks:r}:{},...l,...u.capturedDurationMs===void 0?{}:{capturedDurationMs:u.capturedDurationMs},...d.length?{warning:d.join(` `)}:{},...c&&n.showTouches&&n.gestureEvents.length>0?{overlayWarning:`touch overlay burn-in is skipped for chunked Android recordings; returning raw chunks plus gesture telemetry`}:{}}}}function Cn(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function wn(e){let t=Date.now(),n=await j(e.transport,e.evidence.chunks)||e.reachedLimit===!0;await Rt(e.transport,e.evidence.chunks);let r=await zt(e.transport,e.evidence.chunks,e.recording.outPath,e.recording.clientOutPath),i=await Sn({host:e.host,recording:e.recording,chunks:r,targetLabel:`Android recording`,reachedLimit:n,startedAtMs:e.startedAtMs,stoppedAtMs:t});return await P(e.transport,e.manifestPath,At(e.evidence,i.result)),await M(e.transport,e.evidence.chunks),i}async function Tn(e,t,n){try{let r=t.pendingRemotePath;if(await j(e,[...t.chunks,...await En(e,t)]),await M(e,t.chunks),r!==void 0&&!await e.remove(r))throw Error(`failed to remove Android recording artifact: ${r}`);return await F(e,n),{status:`cleaned`}}catch(e){return Cn(e)}}async function En(e,t){let n=t.pendingRemotePath;if(n===void 0)return[];let r=await e.probeRunningWriters(n);if(!r.conclusive)throw Error(`cannot list every recorder writing Android artifact: ${n}`);return r.writers.map((e,r)=>({index:t.chunks.length+1+r,remotePath:n,remotePid:e.pid,remoteStartTime:e.startTime}))}async function Dn(e){let{transport:t,device:n,envelope:r,descriptor:i}=e;if(i.transportMode!==t.mode)return{status:`transport-unavailable`};let a=await t.readManifest(i.manifestPath);if(a.status===`unavailable`)return{status:`transport-unavailable`};let o=a.status===`read`?D(a.contents):void 0;return o&&jt(o,n,r)&&Mt(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function On(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=D(t.contents);return n&&kn(n,e)?n:void 0}function kn(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function An(e){let{host:t,transport:n,device:r,input:i}=e,a=T.decode(i.envelope.descriptor.body);if(a.status!==`decoded`)return L(`descriptor-invalid`);let o=await Dn({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await Mn({host:t,transport:n,device:r,input:i,descriptor:a.descriptor,evidence:o.evidence}):L(o.status===`transport-unavailable`?`transport-not-reattachable`:`ownership-fence-lost`)}async function jn(e){let t=T.decode(e.input.envelope.descriptor.body);if(t.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`};let n=await Dn({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await Tn(e.transport,n.evidence,t.descriptor.manifestPath):n.status===`transport-unavailable`?{status:`cleanup-pending`,reason:`owner-unavailable`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function Mn(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0&&await Nn(n,o))return{status:`completed`,result:o.completion};if(o.completion!==void 0)return L(`ownership-fence-lost`,`Android recording completed evidence still names a live or unverifiable recorder.`);if(o.pendingRemotePath!==void 0)return L(`transport-not-reattachable`,`Android recording launch was interrupted before its process identity was committed.`);let s=o.chunks.at(-1);if(!s)return{status:`missing`};let c=await n.inspect({pid:s.remotePid,remotePath:s.remotePath,startTime:s.remoteStartTime});if(c!==`owned-alive`&&await n.exists(s.remotePath)!==!0)return L(`transport-not-reattachable`,`Android recording process ended before its artifact could be recovered.`);let l=Pn(i.envelope.sessionId,i.envelope.fence,a),u=!1;return{status:`active`,handle:xe(xn(l,o.startedAt),{finish:async e=>{let r=await wn({host:t,transport:n,evidence:o,manifestPath:a.manifestPath,recording:e,startedAtMs:o.startedAt,reachedLimit:O(c)});return u=!0,r},forceCleanup:async()=>u?{status:`cleaned`}:await jn({transport:n,device:r,input:i})})}}async function Nn(e,t){try{for(let n of t.chunks)if(!O(await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime})))return!1;return!0}catch{return!1}}function Pn(e,t,n){return{sessionId:e,outputPath:n.outputPath,...n.clientOutputPath===void 0?{}:{clientOutputPath:n.clientOutputPath},scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:!1,recordOnlySession:n.recordOnlySession,...n.activeSessionApp===void 0?{}:{activeSessionApp:n.activeSessionApp},...n.exportQuality===void 0?{}:{exportQuality:n.exportQuality},fence:t}}function L(e,t){return{status:`unreattachable`,reason:e,...t===void 0?{}:{message:t}}}async function Fn(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.android.resolve(n);return Object.freeze({screenRecordingStart:async e=>await In({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await An({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await jn({transport:a,device:n,input:e})})}async function In(e){let{host:n,transport:r,device:i,owner:a,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await ln({transport:r,device:i,input:o,startedAt:c,signal:s,prepareOutput:async()=>await n.screenRecording.outputs.prepare(o.outputPath)}),u=l.manifestPath,d=[l.chunk],f,p,m,h=!1,g=()=>{f=setTimeout(()=>{p=ee().catch(e=>{m=e})},17e4),f.unref?.()},ee=async()=>{let e=d.at(-1);if(!e)throw Error(`Android recording has no active chunk`);let t=!1,n;try{n=await fn({transport:r,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:y.posix.dirname(e.remotePath)})}catch(a){await N(r,e),t=!0;try{n=await fn({transport:r,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:y.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:a}}let a=[...d,{...n,index:d.length+1}];try{await P(r,u,E(i,o,c,a,void 0,r.mode))}catch(a){if(await Bt(r,[n]).catch(()=>{}),t)await P(r,u,E(i,o,c,d,n.remotePath,r.mode)).catch(()=>{});else try{await P(r,u,E(i,o,c,d,void 0,r.mode))}catch{await N(r,e).catch(()=>{}),await P(r,u,E(i,o,c,d,n.remotePath,r.mode)).catch(()=>{})}throw a}d=a,t||await N(r,e),g()};g();let te=xe(xn(o,c),{finish:async e=>{if(f&&clearTimeout(f),await p,m)throw m;let t=await wn({host:n,transport:r,evidence:E(i,o,c,d,void 0,r.mode),manifestPath:u,recording:e,startedAtMs:l.startedAtMs});return h=!0,t},forceCleanup:async()=>{if(f&&clearTimeout(f),h)return{status:`cleaned`};try{await p}catch(e){m=e}let e=await On({transport:r,deviceId:i.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await Tn(r,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new he(te),envelope:me({resourceKind:Te,sessionId:o.sessionId,device:t(i),owner:a,fence:o.fence,lifecycle:`open`,descriptor:pe(T,{backend:`adb-screenrecord`,manifestPath:u,outputPath:o.outputPath,...o.clientOutputPath===void 0?{}:{clientOutputPath:o.clientOutputPath},scope:o.scope,showTouches:o.showTouches,recordOnlySession:o.recordOnlySession,...o.activeSessionApp===void 0?{}:{activeSessionApp:o.activeSessionApp},...o.exportQuality===void 0?{}:{exportQuality:o.exportQuality},transportMode:r.mode})})})}const R=12e4,Ln=1e3;async function z(e,t,n,r){return r.throwIfAborted(),await Le(t)?{...t,booted:!0}:t.kind===`emulator`&&(t.booted!==!0||!B(t))?await Rn(e,t,n,r):(t.booted!==!0&&await Hn(e,t.id,R,r),{...t,booted:!0})}async function Rn(e,t,n,r){await zn(e);let i=Un(n),a=Bn(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),o=B(a)?a:void 0,s=o?void 0:e.deviceReadiness.androidEmulator.launch(a.name,n.headless);try{let t=o??await Vn(e,a.name,i,n.serial,r);return await Hn(e,t.id,R,r),{...(await e.deviceReadiness.androidEmulator.discover(i,r)).find(e=>e.id===t.id)??t,name:a.name,booted:!0}}catch(t){throw s!==void 0&&r.aborted&&await e.deviceReadiness.androidEmulator.terminate(s),r.throwIfAborted(),t}}async function zn(t){if(await t.toolchains.prepare(`android`),!await t.commands.which(`adb`))throw new e(`TOOL_MISSING`,`adb not found in PATH`);if(!await t.commands.which(`emulator`))throw new e(`TOOL_MISSING`,`emulator not found in PATH`)}function Bn(t,n,r){let i=Wn(t,n,r);if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No Android emulator AVD named ${n}`,{requestedAvdName:n,availableAvds:t.map(e=>e.name),hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."})}async function Vn(t,n,r,i,a){let o=t.clock.now()+R;for(;t.clock.now()<o;){let e=Wn(await t.deviceReadiness.androidEmulator.discover(r,a),n,i);if(e&&B(e))return e;await t.clock.sleep(Ln,a)}throw new e(`COMMAND_FAILED`,`Android emulator did not appear in time`,{avdName:n,serial:i,timeoutMs:R})}async function Hn(t,n,r,i){let a=t.clock.now()+r;for(;t.clock.now()<a;){if((await t.commands.run({executable:`adb`,args:[`-s`,n,`shell`,`getprop`,`sys.boot_completed`],allowFailure:!0,timeoutMs:Math.min(1e4,Math.max(1e3,a-t.clock.now()))},i)).stdout.trim()===`1`)return;await t.clock.sleep(Ln,i)}throw new e(`COMMAND_FAILED`,`Android device failed to finish booting`,{serial:n,timeoutMs:r,reason:`ANDROID_BOOT_TIMEOUT`})}function Un(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function Wn(e,t,n){let r=Gn(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&Gn(e.name)===r&&(!n||!B(e)||e.id===n))}function B(e){return e.id.startsWith(`emulator-`)}function Gn(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function Kn(e){let{host:t,device:n,signal:r}=e,i=ze({device:n,signal:r,resolveInteractor:t.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async e=>await t.androidApplications.resolveOpenTarget(n,e),prepareApplicationOpen:async e=>{await z(t,n,{headless:!1},r)},openApplication:async e=>await qn(t,i,e),applyRuntimeHints:async e=>await t.androidApplications.applyRuntimeHints(n,e),clearRuntimeHints:async e=>await t.androidApplications.clearRuntimeHints(n,e),closeApplication:async e=>{e.ensureReady&&await z(t,n,{headless:!1},r),await v({device:n,interactor:await i.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async e=>{await t.androidApplications.restoreTestIme(n,{stateDir:e.stateDir});let i=e.shutdownTarget&&n.kind===`emulator`?await t.deviceShutdown.android.shutdownTarget(n,r):void 0;return i===void 0?{}:{shutdown:i}},prepareAppleRunner:Jn,configureProviderPortReverse:Jn})}async function qn(t,n,r){let i={};if(r.relaunch&&r.target){let e=Date.now();await v({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:[r.appBundleId??r.target]}),i.relaunchCloseDurationMs=V(e)}if(a(r.runtimeHints)){if(!r.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let t=Date.now();await r.applyRuntimeHints({appId:r.appBundleId,values:r.runtimeHints}),i.runtimeHintsDurationMs=V(t)}let o=Date.now();await Be({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution}),i.openDispatchDurationMs=V(o),r.enableTestIme&&await t.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let s=Re(r);if(s){let e=Date.now();await Be({device:n.device,interactor:await n.resolveInteractor({...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},r.appBundleId),positionals:[s],appBundleId:r.appBundleId,execution:{...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),i.launchUrlDurationMs=V(e)}else i.launchUrlDurationMs=0;let c=await t.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId);return c&&await t.androidApplications.resetFramePerfStats(n.device,c),i.postOpenSettleDurationMs=0,{appBundleId:c,timing:i}}function V(e){return Math.max(0,Date.now()-e)}async function Jn(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Android.`)}async function H(e,t,n,r,i){U(n);let a=r?void 0:await $n(e,t,i);if(y.extname(n).toLowerCase()===`.aab`?await Qn(e,t,n,i):G(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await $n(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}function U(t){if(_()&&y.extname(t).toLowerCase()===`.aab`)throw new e(`UNSUPPORTED_OPERATION`,`Managed Android deployment does not support app bundles.`,{reason:`managed-bundle-install-unavailable`,hint:`Install an APK on this managed device.`})}async function Yn(e,t,n,r){let i=await W(e,t,[`uninstall`,n],r);if(i.exitCode===0)return;let a=`${i.stdout}\n${i.stderr}`.toLowerCase();a.includes(`unknown package`)||a.includes(`not installed`)||G(i,`adb uninstall failed for ${n}`)}async function Xn(t,n,r,i){let a=r.payload,o=typeof a.action==`string`&&a.action.trim()?a.action.trim():`${r.appId}.TEST_PUSH`,s=[`shell`,`am`,`broadcast`,`-a`,o,`-p`,r.appId];typeof a.receiver==`string`&&a.receiver.trim()&&s.push(`-n`,a.receiver.trim());let c=a.extras??{};if(typeof c!=`object`||!c||Array.isArray(c))throw new e(`INVALID_ARGS`,`Android push payload extras must be an object`);let l=0;for(let[e,t]of Object.entries(c))e&&(er(s,e,t),l+=1);return G(await W(t,n,s,i),`adb push broadcast failed`),{action:o,extrasCount:l}}function Zn(e){let t=new Set([`com`,`android`,`google`,`app`,`apps`,`service`,`services`,`mobile`,`client`]),n=e.split(/[._-]+/).map(e=>e.trim().toLowerCase()).filter(Boolean),r=[...n].reverse().find(e=>!t.has(e))??n.at(-1)??e;return r.charAt(0).toUpperCase()+r.slice(1)}async function Qn(t,n,r,i){if(await t.androidTools.installBundle(n,r,`universal`,i))return;let a=await t.commands.which(`bundletool`),o=t.androidDeployment.bundletoolJar;if(!a&&!o)throw new e(`TOOL_MISSING`,`bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR.`);let s=a?`bundletool`:`java`,c=a?[]:[`-jar`,o],l=await t.temporaryFiles.create({prefix:`agent-device-aab-`,suffix:`.apks`}),u=l.path;try{G(await t.commands.run({executable:s,args:[...c,`build-apks`,`--bundle`,r,`--output`,u,`--mode`,`universal`]},i),`bundletool build-apks failed`),G(await t.commands.run({executable:s,args:[...c,`install-apks`,`--apks`,u,`--device-id`,n.id]},i),`bundletool install-apks failed`)}finally{await l[Symbol.asyncDispose]()}}async function $n(e,t,n){let r=await W(e,t,[`shell`,`pm`,`list`,`packages`],n);return G(r,`adb package inventory failed`),new Set(r.stdout.split(`
5
- `).map(e=>e.replace(`package:`,``).trim()).filter(Boolean))}function er(t,n,r){if(typeof r==`string`)t.push(`--es`,n,r);else if(typeof r==`boolean`)t.push(`--ez`,n,String(r));else if(typeof r==`number`&&Number.isFinite(r))t.push(Number.isInteger(r)?`--ei`:`--ef`,n,String(r));else throw new e(`INVALID_ARGS`,`Unsupported Android broadcast extra type for "${n}". Use string, boolean, or number.`)}async function W(e,t,n,r,i=15e3){return await e.androidTools.runAdb(t,n,{timeoutMs:i,allowFailure:!0},r)}function G(t,n){if(t.exitCode===0)return;let r={stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode};throw new e(`COMMAND_FAILED`,n,r)}const tr=Object.freeze({available:!0});function nr(e){let t=or(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:t})}function rr(e){let{host:t,device:n,signal:r}=e;return nr(n).deployApp.available?Object.freeze({deployApp:async e=>await ir(t,n,e,r),materializeAppSource:async e=>await t.androidDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await ar(t,n,e,r),sendPushNotification:async e=>await Xn(t,n,e,r)}):Object.freeze({})}async function ir(e,t,n,r){if(n.replaceExisting)return await e.androidDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i;try{_()&&(i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),U(i.installablePath)),t.booted!==!0&&await z(e,t,{headless:!1},r);let a=await e.androidDeployment.resolveAppPackage(t,n.app);return await Yn(e,t,a,r),i??=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),await H(e,t,i.installablePath,void 0,r),{packageName:a,launchTarget:a}}finally{await i?.cleanup()}});let i;try{_()&&(i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!0,signal:r}),U(i.installablePath)),t.booted!==!0&&await z(e,t,{headless:!1},r),i??=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!0,signal:r});let a=await H(e,t,i.installablePath,i.packageName,r);return a?{packageName:a,appName:Zn(a),launchTarget:a}:{}}finally{await i?.cleanup()}}async function ar(t,n,r,i){let a=await H(t,n,r.artifact.installablePath,r.artifact.packageName,i);if(!a)throw new e(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{packageName:a,appName:Zn(a),launchTarget:a}}function or(e){return e.kind===`emulator`||e.kind===`device`?tr:Object.freeze({available:!1,reason:`unsupported-device-kind`})}const K=n(`android`),q=Object.freeze({available:!0}),sr=Object.freeze({available:!1,reason:`unsupported-device-kind`}),J=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Android emulators and physical devices.`}),cr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`keyboard actions are supported on Android emulators and physical devices.`}),lr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ur=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Headless boot is supported only for Android emulators.`}),dr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Android appstate is supported only for Android emulators and devices.`}),fr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),pr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for Android emulators and devices.`}),mr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for Android emulators and devices.`}),hr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for Android emulators and devices.`}),gr=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),_r=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),vr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`screenshot is supported only for Android emulators and devices.`}),Y=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`snapshot is supported only for Android emulators and devices.`}),yr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),br=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web).`}),xr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`the stateless audio page probe is a web-session operation; Android targets use the host capture.`});function Sr(e){let t=Cr(e),n=wr(e),r=Tr(e);return o({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:r,clearRuntimeHints:r,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:fr,configureProviderPortReverse:gr})}function Cr(e){return e.kind===`emulator`||e.kind===`device`?q:pr}function wr(e){return e.kind===`emulator`||e.kind===`device`?q:mr}function Tr(e){return e.kind===`emulator`||e.kind===`device`?q:hr}const X=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Gestures are supported on Android emulators and physical devices.`}),Er=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:ke}),Dr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Oe});function Or(e,t){return e.kind===`simulator`?X:e.target===`tv`?t:q}function Z(e){return e.kind===`simulator`?X:q}function Q(e){return e.kind===`simulator`?J:q}const $=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`This Android build ships no shell implementation for the clipboard service, so adb cannot read or write the clipboard on it.`}),kr=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Could not determine whether this Android build supports a shell clipboard: the adb probe did not complete. Retry once the device is reachable.`});async function Ar(e,t){let n=e.androidTools?.probeClipboardShellSupport;return n?await n.call(e.androidTools,t):`probe-failed`}const jr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`tv-remote is supported only on Android TV targets.`});function Mr(e){return e.kind!==`simulator`&&e.target===`tv`?q:jr}function Nr(e){let t=Je(e),n=new Map,a=async t=>{if(t.kind===`simulator`)return $;let r=n.get(t.id)??await Ar(e,t);return r!==`probe-failed`&&n.set(t.id,r),r===`supported`?q:r===`unsupported`?$:kr},o=async e=>{let n=await t.inspectFacts(e),r=nr(e),i=await a(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?dr:q,networkDump:q,screenRecordingStart:q,screenRecordingReattach:q,screenRecordingCleanup:q,...d({capture:e.kind===`simulator`?Y:q,customActions:yr,withoutActiveApp:e.kind===`simulator`?Y:q}),...u({capture:e.kind===`simulator`?vr:q}),...h({findText:Y}),...p({setViewport:br}),...f({focus:Q(e)}),...m({unsupported:X,plan:Z(e),directionalFling:Z(e),multiTouch:Or(e,Er),targetAuthoredDrag:Or(e,Dr),viewport:Z(e)}),...c({scroll:Z(e)}),...l({type:Q(e)}),...s({unsupported:J,tap:Q(e),longPress:Q(e),hover:lr,fill:Q(e)}),...ce({readTextAtPoint:e.kind===`simulator`?sr:q}),...le({back:Q(e)}),...ee({home:Q(e)}),...ae({appSwitcher:Q(e)}),...g({triggerAppEvent:Q(e)}),...re({setSetting:Q(e)}),...oe({read:Q(e),wait:Q(e),accept:Q(e),dismiss:Q(e)}),...se({orientation:Q(e)}),...ne({tvRemote:Mr(e)}),...ie({unsupported:cr,status:Q(e),dismiss:Q(e),enter:Q(e)}),...te({unsupported:i.available?$:i,read:i,write:i}),...de({capture:Ve(e),query:xr}),...fe({frames:Q(e),memorySample:Q(e),memorySnapshot:Q(e),nativeCapture:Q(e),profileReport:Q(e)}),ensureReady:q,bootTarget:q,bootTargetHeadless:e.kind===`emulator`?q:ur,listApps:q,...Sr(e),shutdownTarget:e.kind===`emulator`?q:_r}})};return Object.freeze({owner:K,ownsDevice:e=>e.platform===`android`,inspectFacts:o,bind:async n=>{let a=await t.bind(n),s=await o(n.device),c=await Fn({host:e,device:n.device,owner:K,signal:n.scope.signal});return Object.freeze({device:a.device,owner:K,facts:s,operations:Object.freeze({...a.operations,...rr({host:e,device:n.device,signal:n.scope.signal}),...s.operations.appState.available?{appState:async()=>{n.scope.signal.throwIfAborted();let{runAndroidAdb:e}=await import(`./adb.js`).then(e=>e.t);return await De(async(t,r)=>await e(n.device,t,{...r,signal:n.scope.signal}),n.scope.signal)}}:{},networkDump:async t=>await Ze(e,n.device,t,n.scope.signal),...c,...r(s.operations.audioProbeStart,()=>_e({host:e.audioProbe.hostCapture,device:n.device,owner:K})),...r(s.operations.perfFrames,()=>He({resolveHost:()=>e.perf.android,device:n.device,owner:K})),...Pr(e,n,s),ensureReady:async t=>await z(e,n.device,{...t,headless:!1},n.scope.signal),bootTarget:async t=>await z(e,n.device,{...t,headless:!1},n.scope.signal),...s.operations.bootTargetHeadless.available?{bootTargetHeadless:async t=>await z(e,n.device,{...t,headless:!0},n.scope.signal)}:{},listApps:async e=>{n.scope.signal.throwIfAborted();let{listAndroidApps:t}=await import(`./app-lifecycle.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.package,name:e.name}))},...i(Kn({host:e,device:n.device,signal:n.scope.signal}),s.operations),...s.operations.shutdownTarget.available?{shutdownTarget:async()=>await e.deviceShutdown.android.shutdownTarget(n.device,n.scope.signal)}:{}}),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}function Pr(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return{...n.operations.captureSnapshot.available?ue(r):{},...Ae({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}}export{Nr as createAndroidPlatformRuntime};
3
+ `);return c.trim()?{text:c,pids:o}:void 0}async function ot(e,t,n,r){let i=await nt(e,{executable:`adb`,args:[`-s`,t,`shell`,`pidof`,n],allowFailure:!0},r);if(!i)return;let a=i.stdout.trim().split(/\s+/)[0];return a&&/^\d+$/.test(a)?a:void 0}function st(e,t,n){let r=new Set(n?[n]:[]),i=t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),a=[RegExp(`\\bStart proc\\s+(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`\\b(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`${i}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,`i`),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${i}`,`i`)];for(let n of e.split(`
4
+ `))if(n.includes(t))for(let e of a){let t=e.exec(n)?.[1];t&&/^\d+$/.test(t)&&r.add(t)}return Object.freeze([...r])}function x(e,t){if(t===1)return e;let n=v.parse(e);return v.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const ct=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,lt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function ut(e){return pt(e)&&mt(e)&&ht(e)}function dt(e){if(!S(e))return!1;let t=e;return gt(t)&&_t(t)&&vt(t)&&yt(t)&&(t.completion===void 0||Et(t))}function ft(e,t){return Dt(e,t)&&Ot(e,t.outputPath,t.clientOutputPath)}function pt(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&lt.test(e.manifestPath)&&typeof e.outputPath==`string`}function mt(e){return(e.clientOutputPath===void 0||typeof e.clientOutputPath==`string`)&&C(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function ht(e){return kt(e.transportMode)&&At(e.exportQuality)&&w(e.activeSessionApp)}function gt(e){return e.version===1&&e.resourceKind===`screen-recording`&&typeof e.fenceToken==`string`&&Number.isInteger(e.fenceGeneration)&&typeof e.sessionId==`string`&&typeof e.deviceId==`string`&&Number.isFinite(e.startedAt)}function _t(e){return typeof e.outputPath==`string`&&(e.clientOutputPath===void 0||typeof e.clientOutputPath==`string`)&&C(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function vt(e){return w(e.activeSessionApp)&&At(e.exportQuality)&&kt(e.transportMode)&&(e.pendingRemotePath===void 0||jt(e.pendingRemotePath))}function yt(e){return Array.isArray(e.chunks)&&e.chunks.every(bt)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||xt(e.completion))}function bt(e,t){if(!S(e))return!1;let n=e;return n.index===t+1&&jt(n.remotePath)&&Mt(n.remotePid)&&Mt(n.remoteStartTime)}function xt(e){if(!S(e))return!1;let t=e;return Ct(t)&&wt(t)&&St(t)&&(t.chunks===void 0||t.chunks.every(Tt))}function St(e){return(e.stopObservation===void 0||a(e.stopObservation))&&(e.nativePathDisposition===void 0||i(e.nativePathDisposition))}function Ct(e){return typeof e.backend==`string`&&typeof e.outPath==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)&&Number.isFinite(e.startedAt)&&Number.isFinite(e.completedAt)&&(e.capturedDurationMs===void 0||Number.isFinite(e.capturedDurationMs))}function wt(e){return C(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`&&w(e.activeSessionApp)}function Tt(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function Et(e){let t=e.completion;return t!==void 0&&Dt(t,e)&&t.startedAt===e.startedAt&&Ot(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function Dt(e,t){return e.backend===`adb screenrecord`&&e.outPath===t.outputPath&&e.clientOutPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&Nt(e.activeSessionApp,t.activeSessionApp)}function Ot(e,t,n,r=e.chunks===void 0?1:e.chunks.length){return r===1?e.chunks===void 0:e.chunks?.length===r&&e.chunks.every((e,r)=>e.path===x(t,r+1)&&e.clientOutPath===(n===void 0?void 0:x(n,r+1)))}function S(e){return typeof e==`object`&&!!e}function C(e){return e===`app`||e===`device`||e===`system`}function kt(e){return e===`local`||e===`transport-composed`}function At(e){return e===void 0||e===`medium`||e===`high`}function w(e){return e===void 0||S(e)&&typeof e.bundleId==`string`&&(e.name===void 0||typeof e.name==`string`)}function jt(e){return typeof e==`string`&&ct.test(e)}function Mt(e){return typeof e==`string`&&/^\d+$/.test(e)}function Nt(e,t){return JSON.stringify(e)===JSON.stringify(t)}const T=Object.freeze({resourceKind:Oe,version:1,encode:e=>({...e}),decode:e=>ut(e)?{status:`decoded`,descriptor:Object.freeze({backend:`adb-screenrecord`,manifestPath:e.manifestPath,outputPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutputPath:e.clientOutputPath},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,transportMode:e.transportMode,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality}})}:{status:`invalid`,message:`Invalid Android screen-recording descriptor`}});function E(e,t,n,r,i,a=`local`){return Object.freeze({version:1,resourceKind:`screen-recording`,fenceToken:t.fence.token,fenceGeneration:t.fence.generation,sessionId:t.sessionId,deviceId:e.id,startedAt:n,outputPath:t.outputPath,...t.clientOutputPath===void 0?{}:{clientOutputPath:t.clientOutputPath},scope:t.scope,showTouches:t.showTouches,recordOnlySession:t.recordOnlySession,...t.activeSessionApp===void 0?{}:{activeSessionApp:t.activeSessionApp},...t.exportQuality===void 0?{}:{exportQuality:t.exportQuality},chunks:r,...i===void 0?{}:{pendingRemotePath:i},transportMode:a})}function Pt(e,t){return Object.freeze({...e,completion:t})}function D(e){try{let t=e&&JSON.parse(e);return dt(t)?t:void 0}catch{return}}function Ft(e,t,n){return e.deviceId===t.id&&e.deviceId===n.device.id&&e.fenceToken===n.fence.token&&e.fenceGeneration===n.fence.generation&&e.sessionId===n.sessionId}function It(e,t){return e.outputPath===t.outputPath&&e.clientOutputPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&JSON.stringify(e.activeSessionApp)===JSON.stringify(t.activeSessionApp)&&e.exportQuality===t.exportQuality&&e.transportMode===t.transportMode&&(e.completion===void 0||ft(e.completion,t))}function O(e){switch(e){case`missing`:case`ownership-lost`:case`foreign-writer`:return!0;case`owned-alive`:case`uncertain`:return!1}}function Lt(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const Rt=1e4,zt=1e3;var k=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}};function A(e,t=Date.now()){return[...new Set(e?[e,`/sdcard`,`/data/local/tmp`]:[`/sdcard`,`/data/local/tmp`])].map(e=>`${e}/agent-device-recording-${t}.mp4`)}async function Bt(e,t,n,r){let i;try{if(i=(await e.start({remotePath:t,quality:n.exportQuality??`medium`},r)).process,!/^\d+$/.test(i.pid)||!/^\d+$/.test(i.startTime)||i.remotePath!==t)throw Error(`Android screenrecord returned an invalid process identity`);if(!await Kt(e,t,i,r))throw Error(`Android screenrecord did not begin producing frames`);return{index:1,remotePath:t,remotePid:i.pid,remoteStartTime:i.startTime}}catch(t){throw i&&Vt(i)&&!await qt(e,i)?new k(t):r?.aborted?r.reason:t}}function Vt(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function j(e,t){let n=t.at(-1),r=!1,i;for(let a of[...t].reverse())try{let t=await N(e,a);a===n&&(r=t)}catch(e){i??=e}if(i)throw i;return r}async function Ht(e,t){for(let n of t){let t;for(let r=0;r<3;r+=1){let i=await e.size(n.remotePath);if(typeof i==`number`&&i>0&&i===t)break;if(t=typeof i==`number`&&i>0?i:void 0,r===2)throw Error(`Android recording artifact is not stable: ${n.remotePath}`);await new Promise(e=>setTimeout(e,250))}}}async function Ut(e,t,n){for(let[r,i]of t.entries())await Jt(e,i.remotePath,x(n,r+1))}async function M(e,t){let n;for(let r of t)try{if(!await e.remove(r.remotePath))throw Error(`failed to remove Android recording artifact: ${r.remotePath}`)}catch(e){n??=e}if(n)throw n}async function Wt(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function Gt(e,t){try{await j(e,t)}finally{await M(e,t)}}async function Kt(e,t,n,r){for(let i=0;i<3;i+=1){if(r?.throwIfAborted(),await e.exists(t,r)===!0)return!0;if(await e.inspect(n,r)!==`owned-alive`)return!1;i<2&&await new Promise(e=>setTimeout(e,250))}return!0}async function qt(e,t){try{let n=await e.stop(t,{force:!0});return(n===`stopped`||n===`already-missing`)&&await e.remove(t.remotePath)}catch{return!1}}async function N(e,t){if(!t)return!1;let n={pid:t.remotePid,remotePath:t.remotePath,startTime:t.remoteStartTime},r=await e.stop(n);if(r===`already-missing`)return!0;if(r===`ownership-lost`)throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.remotePid}`);if(await Yt(e,n))return!1;let i=await e.stop(n,{force:!0});if(i===`stopped`||i===`already-missing`)return!1;throw Error(`failed to stop Android screenrecord pid ${t.remotePid}`)}async function Jt(e,t,n){for(let r=0;r<3;r+=1){let i=await e.pullPlayable({remotePath:t,outputPath:n});if(i.exitCode===0&&i.playable)return;r+1<3&&await P(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function Yt(e,t){for(let n=0;n<=Rt;n+=zt){let r=await e.inspect(t);if(r===`missing`)return!0;if(O(r))throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.pid}`);n<Rt&&await P(zt)}return!1}function P(e){return new Promise(t=>setTimeout(t,e))}async function F(e,t,n,r){await e.writeManifest({manifestPath:t,contents:JSON.stringify(n)},r)}async function I(e,t){if(!await e.removeManifest(t))throw Error(`failed to remove Android recording manifest: ${t}`)}async function Xt(e,t){let n=(await Zt(e)).flatMap(n=>Qt(n,t,e.mode));for(let t of n)await en(e,t.evidence,t.manifestPath)}async function Zt(e){return await Promise.all(A(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function Qt(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw rn(e.manifestPath,e.read.message);let r=D(e.read.contents);if(r===void 0)throw an(e.manifestPath);if(r.transportMode!==n)throw on(e.manifestPath,r,n);if(!$t(r,t))throw sn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function $t(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function en(e,t,n){if(await tn(e,t),await M(e,t.chunks),await nn(e,t),await I(e,n),(await e.readManifest(n)).status!==`missing`)throw un(n)}async function tn(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!Lt(t))throw t===`uncertain`?dn(n.remotePath):cn(n.remotePath,t===`owned-alive`?`named-recorder`:`other-recorder`)}let n=t.pendingRemotePath;if(n===void 0)return;let r=await e.probeRunningWriters(n);if(r.writers.length>0)throw cn(n,`other-recorder`);if(!r.conclusive)throw dn(n)}async function nn(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw ln(n)}function rn(t,n){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unavailable: ${t}`,{reason:`native_recovery_evidence_unavailable`,manifestPath:t,hint:`Confirm the device is online and its storage readable, then run record start again.`},Error(n))}function an(t){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unreadable: ${t}`,{reason:`native_recovery_evidence_unreadable`,manifestPath:t,hint:L(t)})}function on(t,n,r){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence was written by the ${n.transportMode} transport, not this ${r} one: ${t}`,{reason:`native_recovery_evidence_transport_mismatch`,manifestPath:t,evidenceTransportMode:n.transportMode,hint:L(t)})}function sn(t,n,r){return new e(`DEVICE_IN_USE`,`Android screenrecord native recovery evidence already exists: ${t} (open recording of session "${n.sessionId}" on ${r.id})`,{reason:`native_recovery_evidence_open`,manifestPath:t,sessionId:n.sessionId,retriable:!1,hint:`Run record stop --session ${n.sessionId} to retire it, or close that session. If it is already closed, ${L(t)}`})}function cn(t,n){let r=n===`named-recorder`;return new e(`DEVICE_IN_USE`,`Android screenrecord recovery evidence is retained: ${r?`its recorder`:`another recorder`} is writing ${t}`,{reason:`native_recording_artifact_claimed`,remotePath:t,writer:n,...r?{retriable:!1}:{},hint:r?`Run record stop for the session that owns that recording before starting another.`:`Android ends any recorder after 180 seconds. Run record start again once that recorder has stopped.`})}function ln(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence could not remove ${t}`,{reason:`native_recording_artifact_removal_failed`,remotePath:t,hint:`Confirm the device is online and run record start again.`})}function un(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence removal could not be confirmed: ${t}`,{reason:`native_recovery_evidence_retirement_unconfirmed`,manifestPath:t,hint:`Run record start again; the marker is retired from the beginning.`})}function dn(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence cannot be safely retired: ${t}`,{reason:`native_recording_recorder_unproven`,remotePath:t,hint:`Confirm the device is online and run record start again.`})}function L(e){return`no recording session can retire this marker; remove it on the device with \`adb shell rm -f ${e}\`.`}async function fn(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await Xt(t,n),await o();let s;for(let e of A(void 0)){let o=t.manifestPathFor(e);await F(t,o,E(n,r,i,[],e,t.mode),a);let c,l;try{l=Date.now(),c=await Bt(t,e,r,a)}catch(e){if(a.aborted)throw await pn(t,o,e),a.reason;await gn(t,o,e),s=e;continue}try{await F(t,o,E(n,r,i,[c],void 0,t.mode),a)}catch(e){throw await mn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function pn(e,t,n){n instanceof k||await I(e,t).catch(()=>{})}async function mn(e,t,n){try{await Gt(e,[n])}catch{return}await I(e,t).catch(()=>{})}async function hn(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s}=e,c;for(let e of A(s)){await F(t,o,E(n,r,i,a,e,t.mode));try{return await Bt(t,e,r)}catch(e){if(e instanceof k)throw e;try{await F(t,o,E(n,r,i,a,void 0,t.mode))}catch{throw new k(e)}c=e}}throw c??Error(`failed to start next Android recording chunk`)}async function gn(e,t,n){if(n instanceof k)throw n;try{await I(e,t)}catch{throw new k(n)}}function _n(e,t){return Object.freeze({backend:`adb screenrecord`,outPath:e.outputPath,...e.clientOutputPath?{clientOutPath:e.clientOutputPath}:{},startedAt:t,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp?{activeSessionApp:e.activeSessionApp}:{},...e.exportQuality?{exportQuality:e.exportQuality}:{},gestureEvents:[]})}const vn=[`moov`,`mvhd`];function yn(e){let t=xn(e);if(!t)return;let n=t[0];if(n===1)return bn(t.readUInt32BE(20),Number(t.readBigUInt64BE(24)));if(n!==0)return;let r=t.readUInt32BE(16);if(r!==4294967295)return bn(t.readUInt32BE(12),r)}function bn(e,t){if(!(e<=0||t<0||!Number.isSafeInteger(t)))return Math.round(t*1e3/e)}function xn(e){let t=ke(e,vn);if(!t||!Number.isSafeInteger(t.size))return;let n=t.offset+t.headerSize;if(t.size-t.headerSize<32)return;let r=Buffer.alloc(32),i;try{return i=y.openSync(e,`r`),y.readSync(i,r,0,r.length,n)===r.length?r:void 0}catch{return}finally{i!==void 0&&y.closeSync(i)}}function Sn(e){let t=Cn(e.chunkPaths);if(t===void 0)return{};let n=e.stoppedAtMs-e.startedAtMs;return n-t<2e3?{capturedDurationMs:t}:{capturedDurationMs:t,idleTailWarning:`Android screenrecord encodes a frame only when the screen changes, so this video ends at the last frame it encoded: it covers ${wn(t)}s of the ${wn(n)}s recording window.`}}function Cn(e){let t=0;for(let n of e){let e=yn(n);if(e===void 0)return;t+=e}return t}function wn(e){return(e/1e3).toFixed(1)}async function Tn(e){let{host:t,transport:n,evidence:r,recording:i,startedAtMs:a,progress:o}=e,s=e.reachedLimit===!0;return await An(e,await De({snapshot:i,progress:o,steps:{stop:async()=>(s=await j(n,r.chunks)||s,await Ht(n,r.chunks),{observation:{recorder:`confirmed`},...s?{warning:`Android adb screenrecord stopped before record stop, likely after reaching the 180s platform limit. The MP4 may be truncated; final interactions after the limit are not in the video.`}:{}}),collect:e=>Ut(n,r.chunks,e),finalize:({collectedPath:e,exportPath:n,stoppedAtMs:o})=>En({host:t,evidence:r,recording:i,startedAtMs:a,stoppedAtMs:o,collectedPath:e,exportPath:n}),discard:e=>On(t,e,r.chunks.length)}}))}async function En(e){let{host:t,evidence:n,recording:r,collectedPath:i,exportPath:a}=e,o=jn({collectedPath:i,exportPath:a,exportClientPath:r.clientOutPath,count:n.chunks.length}),s=o.length>1,c;try{await Dn(t,o),c=await t.screenRecording.finalize.complete({outputPath:a,showTouches:!s&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,targetLabel:`Android recording`})}catch(e){for(let{served:e}of o)await t.screenRecording.outputs.remove(e.path);throw e}let l=Sn({chunkPaths:o.map(({collected:e})=>e.path),startedAtMs:e.startedAtMs,stoppedAtMs:e.stoppedAtMs});return kn({finalization:c,captured:l,recording:r,chunked:s,files:o})}async function Dn(e,t){for(let{collected:n,served:r}of t)await e.screenRecording.outputs.copy({from:n.path,to:r.path})}async function On(e,t,n){for(let r=1;r<=n;r+=1)await e.screenRecording.outputs.remove(x(t,r))}function kn(e){let{finalization:t,captured:n,recording:r,chunked:i,files:a}=e,o=[t.warning,...i?[`Android adb screenrecord is capped at 180s, so this recording was split into multiple MP4 chunks.`]:[],n.idleTailWarning].filter(e=>e!==void 0&&e.length>0);return{...t.telemetryPath===void 0?{}:{telemetryPath:t.telemetryPath},...o.length===0?{}:{warning:o.join(` `)},...i&&r.showTouches&&r.gestureEvents.length>0?{overlayWarning:`touch overlay burn-in is skipped for chunked Android recordings; returning raw chunks plus gesture telemetry`}:{},...n.capturedDurationMs===void 0?{}:{capturedDurationMs:n.capturedDurationMs},...i?{chunks:a.map(e=>e.served)}:{},nativePathDisposition:`retirable`}}async function An(e,t){let{transport:n,evidence:r,manifestPath:i}=e;return await F(n,i,Pt(r,t.result)),await M(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await Wt(n,r.chunks)}}}function jn(e){return Object.freeze(Array.from({length:e.count},(t,n)=>({collected:Object.freeze({index:n+1,path:x(e.collectedPath,n+1)}),served:Object.freeze({index:n+1,path:x(e.exportPath,n+1),...e.exportClientPath===void 0?{}:{clientOutPath:x(e.exportClientPath,n+1)}})})))}async function Mn(e,t,n){try{let r=t.pendingRemotePath;if(await j(e,[...t.chunks,...await Nn(e,t)]),await M(e,t.chunks),r!==void 0&&!await e.remove(r))throw Error(`failed to remove Android recording artifact: ${r}`);return await I(e,n),{status:`cleaned`}}catch(e){return Pn(e)}}async function Nn(e,t){let n=t.pendingRemotePath;if(n===void 0)return[];let r=await e.probeRunningWriters(n);if(!r.conclusive)throw Error(`cannot list every recorder writing Android artifact: ${n}`);return r.writers.map((e,r)=>({index:t.chunks.length+1+r,remotePath:n,remotePid:e.pid,remoteStartTime:e.startTime}))}function Pn(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function Fn(e){let{transport:t,device:n,envelope:r,descriptor:i}=e;if(i.transportMode!==t.mode)return{status:`transport-unavailable`};let a=await t.readManifest(i.manifestPath);if(a.status===`unavailable`)return{status:`transport-unavailable`};let o=a.status===`read`?D(a.contents):void 0;return o&&Ft(o,n,r)&&It(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function In(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=D(t.contents);return n&&Ln(n,e)?n:void 0}function Ln(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function Rn(e){let{host:t,transport:n,device:r,input:i}=e,a=T.decode(i.envelope.descriptor.body);if(a.status!==`decoded`)return R(`descriptor-invalid`);let o=await Fn({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await Bn({host:t,transport:n,device:r,input:i,descriptor:a.descriptor,evidence:o.evidence}):R(o.status===`transport-unavailable`?`transport-not-reattachable`:`ownership-fence-lost`)}async function zn(e){let t=T.decode(e.input.envelope.descriptor.body);if(t.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`};let n=await Fn({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await Mn(e.transport,n.evidence,t.descriptor.manifestPath):n.status===`transport-unavailable`?{status:`cleanup-pending`,reason:`owner-unavailable`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function Bn(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0){let e=await Vn(n,o);return e.status===`terminal`?{status:`completed`,result:{...o.completion,nativePathDisposition:e.nativePathDisposition}}:R(`ownership-fence-lost`,`Android recording completed evidence still names a live or unverifiable recorder.`)}if(o.pendingRemotePath!==void 0)return R(`transport-not-reattachable`,`Android recording launch was interrupted before its process identity was committed.`);let s=o.chunks.at(-1);if(!s)return{status:`missing`};let c=await n.inspect({pid:s.remotePid,remotePath:s.remotePath,startTime:s.remoteStartTime});if(c!==`owned-alive`&&await n.exists(s.remotePath)===!1)return R(`transport-not-reattachable`,`Android recording process ended before its artifact could be recovered.`);let l=Hn(i.envelope.sessionId,i.envelope.fence,a),u=!1;return{status:`active`,handle:Ce(_n(l,o.startedAt),{finish:async(e,r)=>{let i=await Tn({host:t,transport:n,evidence:o,manifestPath:a.manifestPath,recording:e,startedAtMs:o.startedAt,reachedLimit:O(c),progress:r});return u=!0,i},forceCleanup:async()=>u?{status:`cleaned`}:await zn({transport:n,device:r,input:i})})}}async function Vn(e,t){try{for(let n of t.chunks)if(!O(await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime})))return{status:`retained`};return{status:`terminal`,nativePathDisposition:await Wt(e,t.chunks)}}catch{return{status:`retained`}}}function Hn(e,t,n){return{sessionId:e,outputPath:n.outputPath,...n.clientOutputPath===void 0?{}:{clientOutputPath:n.clientOutputPath},scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:!1,recordOnlySession:n.recordOnlySession,...n.activeSessionApp===void 0?{}:{activeSessionApp:n.activeSessionApp},...n.exportQuality===void 0?{}:{exportQuality:n.exportQuality},fence:t}}function R(e,t){return{status:`unreattachable`,reason:e,...t===void 0?{}:{message:t}}}async function Un(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.android.resolve(n);return Object.freeze({screenRecordingStart:async e=>await Wn({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await Rn({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await zn({transport:a,device:n,input:e})})}async function Wn(e){let{host:n,transport:r,device:i,owner:a,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await fn({transport:r,device:i,input:o,startedAt:c,signal:s,prepareOutput:async()=>await n.screenRecording.outputs.prepare(o.outputPath)}),u=l.manifestPath,d=[l.chunk],f,p,m,h=!1,g=()=>{f=setTimeout(()=>{p=ee().catch(e=>{m=e})},17e4),f.unref?.()},ee=async()=>{let e=d.at(-1);if(!e)throw Error(`Android recording has no active chunk`);let t=!1,n;try{n=await hn({transport:r,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:v.posix.dirname(e.remotePath)})}catch(a){await N(r,e),t=!0;try{n=await hn({transport:r,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:v.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:a}}let a=[...d,{...n,index:d.length+1}];try{await F(r,u,E(i,o,c,a,void 0,r.mode))}catch(a){if(await Gt(r,[n]).catch(()=>{}),t)await F(r,u,E(i,o,c,d,n.remotePath,r.mode)).catch(()=>{});else try{await F(r,u,E(i,o,c,d,void 0,r.mode))}catch{await N(r,e).catch(()=>{}),await F(r,u,E(i,o,c,d,n.remotePath,r.mode)).catch(()=>{})}throw a}d=a,t||await N(r,e),g()};g();let te=Ce(_n(o,c),{finish:async(e,t)=>{if(f&&clearTimeout(f),await p,m)throw m;let a=await Tn({host:n,transport:r,evidence:E(i,o,c,d,void 0,r.mode),manifestPath:u,recording:e,startedAtMs:l.startedAtMs,progress:t});return h=!0,a},forceCleanup:async()=>{if(f&&clearTimeout(f),h)return{status:`cleaned`};try{await p}catch(e){m=e}let e=await In({transport:r,deviceId:i.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await Mn(r,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new _e(te),envelope:ge({resourceKind:Oe,sessionId:o.sessionId,device:t(i),owner:a,fence:o.fence,lifecycle:`open`,descriptor:he(T,{backend:`adb-screenrecord`,manifestPath:u,outputPath:o.outputPath,...o.clientOutputPath===void 0?{}:{clientOutputPath:o.clientOutputPath},scope:o.scope,showTouches:o.showTouches,recordOnlySession:o.recordOnlySession,...o.activeSessionApp===void 0?{}:{activeSessionApp:o.activeSessionApp},...o.exportQuality===void 0?{}:{exportQuality:o.exportQuality},transportMode:r.mode})})})}const z=12e4,Gn=1e3;async function B(e,t,n,r){return r.throwIfAborted(),await Be(t)?{...t,booted:!0}:t.kind===`emulator`&&(t.booted!==!0||!V(t))?await Kn(e,t,n,r):(t.booted!==!0&&await Xn(e,t.id,z,r),{...t,booted:!0})}async function Kn(e,t,n,r){await qn(e);let i=Zn(n),a=Jn(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),o=V(a)?a:void 0,s=o?void 0:e.deviceReadiness.androidEmulator.launch(a.name,n.headless);try{let t=o??await Yn(e,a.name,i,n.serial,r);return await Xn(e,t.id,z,r),{...(await e.deviceReadiness.androidEmulator.discover(i,r)).find(e=>e.id===t.id)??t,name:a.name,booted:!0}}catch(t){throw s!==void 0&&r.aborted&&await e.deviceReadiness.androidEmulator.terminate(s),r.throwIfAborted(),t}}async function qn(t){if(await t.toolchains.prepare(`android`),!await t.commands.which(`adb`))throw new e(`TOOL_MISSING`,`adb not found in PATH`);if(!await t.commands.which(`emulator`))throw new e(`TOOL_MISSING`,`emulator not found in PATH`)}function Jn(t,n,r){let i=Qn(t,n,r);if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No Android emulator AVD named ${n}`,{requestedAvdName:n,availableAvds:t.map(e=>e.name),hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."})}async function Yn(t,n,r,i,a){let o=t.clock.now()+z;for(;t.clock.now()<o;){let e=Qn(await t.deviceReadiness.androidEmulator.discover(r,a),n,i);if(e&&V(e))return e;await t.clock.sleep(Gn,a)}throw new e(`COMMAND_FAILED`,`Android emulator did not appear in time`,{avdName:n,serial:i,timeoutMs:z})}async function Xn(t,n,r,i){let a=t.clock.now()+r;for(;t.clock.now()<a;){if((await t.commands.run({executable:`adb`,args:[`-s`,n,`shell`,`getprop`,`sys.boot_completed`],allowFailure:!0,timeoutMs:Math.min(1e4,Math.max(1e3,a-t.clock.now()))},i)).stdout.trim()===`1`)return;await t.clock.sleep(Gn,i)}throw new e(`COMMAND_FAILED`,`Android device failed to finish booting`,{serial:n,timeoutMs:r,reason:`ANDROID_BOOT_TIMEOUT`})}function Zn(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function Qn(e,t,n){let r=$n(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&$n(e.name)===r&&(!n||!V(e)||e.id===n))}function V(e){return e.id.startsWith(`emulator-`)}function $n(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function er(e){let{host:t,device:n,signal:r}=e,i=Ue({device:n,signal:r,resolveInteractor:t.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async e=>await t.androidApplications.resolveOpenTarget(n,e),prepareApplicationOpen:async e=>{await B(t,n,{headless:!1},r)},openApplication:async e=>await tr(t,i,e),applyRuntimeHints:async e=>await t.androidApplications.applyRuntimeHints(n,e),clearRuntimeHints:async e=>await t.androidApplications.clearRuntimeHints(n,e),closeApplication:async e=>{e.ensureReady&&await B(t,n,{headless:!1},r),await Ve({device:n,interactor:await i.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async e=>{await t.androidApplications.restoreTestIme(n,{stateDir:e.stateDir});let i=e.shutdownTarget&&n.kind===`emulator`?await t.deviceShutdown.android.shutdownTarget(n,r):void 0;return i===void 0?{}:{shutdown:i}},prepareAppleRunner:nr,configureProviderPortReverse:nr})}async function tr(t,n,r){let i={};if(r.relaunch&&r.target){let e=Date.now();await Ve({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:[r.appBundleId??r.target]}),i.relaunchCloseDurationMs=H(e)}if(s(r.runtimeHints)){if(!r.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let t=Date.now();await r.applyRuntimeHints({appId:r.appBundleId,values:r.runtimeHints}),i.runtimeHintsDurationMs=H(t)}let a=Date.now();await We({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution}),i.openDispatchDurationMs=H(a),r.enableTestIme&&await t.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let o=He(r);if(o){let e=Date.now();await We({device:n.device,interactor:await n.resolveInteractor({...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},r.appBundleId),positionals:[o],appBundleId:r.appBundleId,execution:{...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),i.launchUrlDurationMs=H(e)}else i.launchUrlDurationMs=0;let c=await t.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId);return c&&await t.androidApplications.resetFramePerfStats(n.device,c),i.postOpenSettleDurationMs=0,{appBundleId:c,timing:i}}function H(e){return Math.max(0,Date.now()-e)}async function nr(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Android.`)}async function U(e,t,n,r,i){W(n);let a=r?void 0:await sr(e,t,i);if(v.extname(n).toLowerCase()===`.aab`?await or(e,t,n,i):K(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await sr(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}function W(t){if(_()&&v.extname(t).toLowerCase()===`.aab`)throw new e(`UNSUPPORTED_OPERATION`,`Managed Android deployment does not support app bundles.`,{reason:`managed-bundle-install-unavailable`,hint:`Install an APK on this managed device.`})}async function rr(e,t,n,r){let i=await G(e,t,[`uninstall`,n],r);if(i.exitCode===0)return;let a=`${i.stdout}\n${i.stderr}`.toLowerCase();a.includes(`unknown package`)||a.includes(`not installed`)||K(i,`adb uninstall failed for ${n}`)}async function ir(t,n,r,i){let a=r.payload,o=typeof a.action==`string`&&a.action.trim()?a.action.trim():`${r.appId}.TEST_PUSH`,s=[`shell`,`am`,`broadcast`,`-a`,o,`-p`,r.appId];typeof a.receiver==`string`&&a.receiver.trim()&&s.push(`-n`,a.receiver.trim());let c=a.extras??{};if(typeof c!=`object`||!c||Array.isArray(c))throw new e(`INVALID_ARGS`,`Android push payload extras must be an object`);let l=0;for(let[e,t]of Object.entries(c))e&&(cr(s,e,t),l+=1);return K(await G(t,n,s,i),`adb push broadcast failed`),{action:o,extrasCount:l}}function ar(e){let t=new Set([`com`,`android`,`google`,`app`,`apps`,`service`,`services`,`mobile`,`client`]),n=e.split(/[._-]+/).map(e=>e.trim().toLowerCase()).filter(Boolean),r=[...n].reverse().find(e=>!t.has(e))??n.at(-1)??e;return r.charAt(0).toUpperCase()+r.slice(1)}async function or(t,n,r,i){if(await t.androidTools.installBundle(n,r,`universal`,i))return;let a=await t.commands.which(`bundletool`),o=t.androidDeployment.bundletoolJar;if(!a&&!o)throw new e(`TOOL_MISSING`,`bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR.`);let s=a?`bundletool`:`java`,c=a?[]:[`-jar`,o],l=await t.temporaryFiles.create({prefix:`agent-device-aab-`,suffix:`.apks`}),u=l.path;try{K(await t.commands.run({executable:s,args:[...c,`build-apks`,`--bundle`,r,`--output`,u,`--mode`,`universal`]},i),`bundletool build-apks failed`),K(await t.commands.run({executable:s,args:[...c,`install-apks`,`--apks`,u,`--device-id`,n.id]},i),`bundletool install-apks failed`)}finally{await l[Symbol.asyncDispose]()}}async function sr(e,t,n){let r=await G(e,t,[`shell`,`pm`,`list`,`packages`],n);return K(r,`adb package inventory failed`),new Set(r.stdout.split(`
5
+ `).map(e=>e.replace(`package:`,``).trim()).filter(Boolean))}function cr(t,n,r){if(typeof r==`string`)t.push(`--es`,n,r);else if(typeof r==`boolean`)t.push(`--ez`,n,String(r));else if(typeof r==`number`&&Number.isFinite(r))t.push(Number.isInteger(r)?`--ei`:`--ef`,n,String(r));else throw new e(`INVALID_ARGS`,`Unsupported Android broadcast extra type for "${n}". Use string, boolean, or number.`)}async function G(e,t,n,r,i=15e3){return await e.androidTools.runAdb(t,n,{timeoutMs:i,allowFailure:!0},r)}function K(t,n){if(t.exitCode===0)return;let r={stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode};throw new e(`COMMAND_FAILED`,n,r)}const lr=Object.freeze({available:!0});function ur(e){let t=mr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:t})}function dr(e){let{host:t,device:n,signal:r}=e;return ur(n).deployApp.available?Object.freeze({deployApp:async e=>await fr(t,n,e,r),materializeAppSource:async e=>await t.androidDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await pr(t,n,e,r),sendPushNotification:async e=>await ir(t,n,e,r)}):Object.freeze({})}async function fr(e,t,n,r){if(n.replaceExisting)return await e.androidDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i;try{_()&&(i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),W(i.installablePath)),t.booted!==!0&&await B(e,t,{headless:!1},r);let a=await e.androidDeployment.resolveAppPackage(t,n.app);return await rr(e,t,a,r),i??=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),await U(e,t,i.installablePath,void 0,r),{packageName:a,launchTarget:a}}finally{await i?.cleanup()}});let i;try{_()&&(i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!0,signal:r}),W(i.installablePath)),t.booted!==!0&&await B(e,t,{headless:!1},r),i??=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!0,signal:r});let a=await U(e,t,i.installablePath,i.packageName,r);return a?{packageName:a,appName:ar(a),launchTarget:a}:{}}finally{await i?.cleanup()}}async function pr(t,n,r,i){let a=await U(t,n,r.artifact.installablePath,r.artifact.packageName,i);if(!a)throw new e(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{packageName:a,appName:ar(a),launchTarget:a}}function mr(e){return e.kind===`emulator`||e.kind===`device`?lr:Object.freeze({available:!1,reason:`unsupported-device-kind`})}const q=n(`android`),J=Object.freeze({available:!0}),hr=Object.freeze({available:!1,reason:`unsupported-device-kind`}),gr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Android emulators and physical devices.`}),_r=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`keyboard actions are supported on Android emulators and physical devices.`}),vr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),yr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Headless boot is supported only for Android emulators.`}),br=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Android appstate is supported only for Android emulators and devices.`}),xr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),Sr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for Android emulators and devices.`}),Cr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for Android emulators and devices.`}),wr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for Android emulators and devices.`}),Tr=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),Er=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Dr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`screenshot is supported only for Android emulators and devices.`}),Y=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`snapshot is supported only for Android emulators and devices.`}),Or=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),kr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web).`}),Ar=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`the stateless audio page probe is a web-session operation; Android targets use the host capture.`});function jr(e){let t=Mr(e),n=Nr(e),r=Pr(e);return c({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:r,clearRuntimeHints:r,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:xr,configureProviderPortReverse:Tr})}function Mr(e){return e.kind===`emulator`||e.kind===`device`?J:Sr}function Nr(e){return e.kind===`emulator`||e.kind===`device`?J:Cr}function Pr(e){return e.kind===`emulator`||e.kind===`device`?J:wr}const X=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Gestures are supported on Android emulators and physical devices.`}),Fr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Me}),Ir=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:je});function Lr(e,t){return e.kind===`simulator`?X:e.target===`tv`?t:J}function Z(e){return e.kind===`simulator`?X:J}function Q(e){return e.kind===`simulator`?gr:J}const $=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`This Android build ships no shell implementation for the clipboard service, so adb cannot read or write the clipboard on it.`}),Rr=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Could not determine whether this Android build supports a shell clipboard: the adb probe did not complete. Retry once the device is reachable.`});async function zr(e,t){let n=e.androidTools?.probeClipboardShellSupport;return n?await n.call(e.androidTools,t):`probe-failed`}const Br=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`tv-remote is supported only on Android TV targets.`});function Vr(e){return e.kind!==`simulator`&&e.target===`tv`?J:Br}function Hr(e){let t=Qe(e),n=new Map,i=async t=>{if(t.kind===`simulator`)return $;let r=n.get(t.id)??await zr(e,t);return r!==`probe-failed`&&n.set(t.id,r),r===`supported`?J:r===`unsupported`?$:Rr},a=async e=>{let n=await t.inspectFacts(e),r=ur(e),a=await i(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?br:J,networkDump:J,screenRecordingStart:J,screenRecordingReattach:J,screenRecordingCleanup:J,...p({capture:e.kind===`simulator`?Y:J,customActions:Or,withoutActiveApp:e.kind===`simulator`?Y:J}),...f({capture:e.kind===`simulator`?Dr:J}),...ee({findText:Y}),...h({setViewport:kr}),...m({focus:Q(e)}),...g({unsupported:X,plan:Z(e),directionalFling:Z(e),multiTouch:Lr(e,Fr),targetAuthoredDrag:Lr(e,Ir),viewport:Z(e)}),...u({scroll:Z(e)}),...d({type:Q(e)}),...l({unsupported:gr,tap:Q(e),longPress:Q(e),hover:vr,fill:Q(e)}),...ue({readTextAtPoint:e.kind===`simulator`?hr:J}),...de({back:Q(e)}),...ne({home:Q(e)}),...se({appSwitcher:Q(e)}),...te({triggerAppEvent:Q(e)}),...ae({setSetting:Q(e)}),...ce({read:Q(e),wait:Q(e),accept:Q(e),dismiss:Q(e)}),...le({orientation:Q(e)}),...ie({tvRemote:Vr(e)}),...oe({unsupported:_r,status:Q(e),dismiss:Q(e),enter:Q(e)}),...re({unsupported:a.available?$:a,read:a,write:a}),...pe({capture:Ge(e),query:Ar}),...me({frames:Q(e),memorySample:Q(e),memorySnapshot:Q(e),nativeCapture:Q(e),profileReport:Q(e)}),ensureReady:J,bootTarget:J,bootTargetHeadless:e.kind===`emulator`?J:yr,listApps:J,...jr(e),shutdownTarget:e.kind===`emulator`?J:Er}})};return Object.freeze({owner:q,ownsDevice:e=>e.platform===`android`,inspectFacts:a,bind:async n=>{let i=await t.bind(n),s=await a(n.device),c=await Un({host:e,device:n.device,owner:q,signal:n.scope.signal});return Object.freeze({device:i.device,owner:q,facts:s,operations:Object.freeze({...i.operations,...dr({host:e,device:n.device,signal:n.scope.signal}),...s.operations.appState.available?{appState:async()=>{n.scope.signal.throwIfAborted();let{runAndroidAdb:e}=await import(`./adb.js`).then(e=>e.t);return await Ae(async(t,r)=>await e(n.device,t,{...r,signal:n.scope.signal}),n.scope.signal)}}:{},networkDump:async t=>await tt(e,n.device,t,n.scope.signal),...c,...r(s.operations.audioProbeStart,()=>ye({host:e.audioProbe.hostCapture,device:n.device,owner:q})),...r(s.operations.perfFrames,()=>Ke({resolveHost:()=>e.perf.android,device:n.device,owner:q})),...Ur(e,n,s),ensureReady:async t=>await B(e,n.device,{...t,headless:!1},n.scope.signal),bootTarget:async t=>await B(e,n.device,{...t,headless:!1},n.scope.signal),...s.operations.bootTargetHeadless.available?{bootTargetHeadless:async t=>await B(e,n.device,{...t,headless:!0},n.scope.signal)}:{},listApps:async e=>{n.scope.signal.throwIfAborted();let{listAndroidApps:t}=await import(`./app-lifecycle.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.package,name:e.name}))},...o(er({host:e,device:n.device,signal:n.scope.signal}),s.operations),...s.operations.shutdownTarget.available?{shutdownTarget:async()=>await e.deviceShutdown.android.shutdownTarget(n.device,n.scope.signal)}:{}}),[Symbol.asyncDispose]:async()=>await i[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}function Ur(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return{...n.operations.captureSnapshot.available?fe(r):{},...Ne({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}}export{Hr as createAndroidPlatformRuntime};
@@ -1 +1 @@
1
- import{M as e}from"./sdk-contracts.js";function t(e){return Object.freeze({canShutdownTarget:n,shutdownTarget:async(t,n)=>await r(e.commands,t,n)})}function n(e){return e.platform===`android`&&e.kind===`emulator`}async function r(t,n,r){if(n.booted===!1)return i();r.throwIfAborted();try{let e=await t.run({executable:`adb`,args:[`-s`,n.id,`emu`,`kill`],allowFailure:!0,timeoutMs:15e3},r);r.throwIfAborted();let i=e.exitCode??-1;return{success:i===0,exitCode:i,stdout:e.stdout,stderr:e.stderr}}catch(t){r.throwIfAborted();let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}function i(){return{success:!0,exitCode:0,stdout:``,stderr:``}}export{t as createAndroidShutdownRuntime};
1
+ import{N as e}from"./sdk-contracts.js";function t(e){return Object.freeze({canShutdownTarget:n,shutdownTarget:async(t,n)=>await r(e.commands,t,n)})}function n(e){return e.platform===`android`&&e.kind===`emulator`}async function r(t,n,r){if(n.booted===!1)return i();r.throwIfAborted();try{let e=await t.run({executable:`adb`,args:[`-s`,n.id,`emu`,`kill`],allowFailure:!0,timeoutMs:15e3},r);r.throwIfAborted();let i=e.exitCode??-1;return{success:i===0,exitCode:i,stdout:e.stdout,stderr:e.stderr}}catch(t){r.throwIfAborted();let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}function i(){return{success:!0,exitCode:0,stdout:``,stderr:``}}export{t as createAndroidShutdownRuntime};
@@ -1,5 +1,5 @@
1
- import{C as e,w as t}from"./sdk-contracts.js";import{r as n}from"./sdk-batch-runner.js";import{S as r,c as i,h as a,l as o,u as s,w as c}from"./sdk-device.js";import{Gt as l,Xt as u,Zt as d}from"./sdk-batch.js";import{c as f,r as p}from"./diagnostics.js";import{n as m}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as h}from"./scoped-provider.js";import{i as ee,n as te,r as ne}from"./ios-snapshot-planning.js";import{t as re}from"./request.js";import{n as ie,r as ae,t as oe}from"./application-lifecycle-runtime.js";import{i as se,t as ce}from"./touch-runtime.js";import{A as le,C as ue,D as de,G as fe,H as pe,I as me,L as he,N as ge,O as _e,P as ve,R as ye,T as be,U as xe,V as Se,a as Ce,b as we,d as Te,g as Ee,i as De,j as Oe,m as ke,s as Ae,t as je,v as Me,w as Ne,x as Pe,z as Fe}from"./alert-runtime.js";import{n as Ie}from"./audio-probe-runtime.js";import{n as Le}from"./perf-runtime.js";import{a as Re,n as ze}from"./durable-resource.js";import{n as Be,t as Ve}from"./async-lifecycle.js";import{a as He,c as Ue,d as We,f as Ge,l as Ke,n as qe,o as Je,s as Ye,t as Xe,u as Ze}from"./src7.js";import{t as Qe}from"./screen-recording-live-handle.js";import{t as $e}from"./screen-recording-completion.js";import{n as et,r as tt,t as nt}from"./audio-probe-support.js";import{n as rt}from"./screen-recording-runtime.js";import{n as it}from"./ios-system-surface.js";import{i as at,r as ot}from"./gesture-admission.js";import{t as st}from"./interactor-operation-catalog.js";import{a as ct,i as lt,n as ut,r as dt,t as ft}from"./perf-runtime-operation-builder.js";import{t as pt}from"./app-log-runtime.js";import{i as mt,r as ht}from"./managed-device-scope.js";import{a as gt,n as _t,o as vt}from"./application-lifecycle-interaction.js";import{a as yt}from"./tool-provider.js";import{n as bt}from"./apps-simctl.js";import{a as xt}from"./simulator.js";import{t as St}from"./multitouch-support.js";import{n as g,t as Ct}from"./simulator-state.js";import{t as wt}from"./snapshot-process.js";import Tt from"node:path";import{randomUUID as Et}from"node:crypto";function Dt(e){let t=mt();return Object.freeze(t?{...h({...e},e=>xt(t,e))}:e)}function Ot(e){return nt(e)?Object.freeze({available:!0}):s(e)||o(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 kt(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...ft({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 lt(t().sampleFrames(n,e)):ut(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await lt(t().sampleMemory(n,e)):ut(`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 ct(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw dt();let c=i??Tt.join(a,`memory-memgraph-${At()}.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 At(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const _=Object.freeze({available:!0}),v=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),y=Pt(`Gestures are supported only for Apple simulators and devices.`),jt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:ot}),Mt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:at}),Nt=Pt(`scroll is supported only for Apple simulators and devices.`);function Pt(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Ft(e){return{...ge({unsupported:It(e),plan:Lt(e),directionalFling:Lt(e),multiTouch:Rt(e),targetAuthoredDrag:zt(e),viewport:Bt(e)}),...le({scroll:Vt(e)})}}function It(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?v:y}function Lt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?v:b(e)?_:y}function Rt(e){if(e.appleOs===`watchos`)return v;if(!b(e))return y;let t=r(e);if(t!==`ios`&&t!==`ipados`){let e=St[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?_:jt}function zt(e){return b(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?_:Mt:y}function Bt(e){return e.appleOs===`watchos`?v:b(e)?_:y}function Vt(e){return b(e)?_:Nt}function b(e){return e.kind===`simulator`||e.kind===`device`}const x=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function S(e){return s(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const Ht=Object.freeze({resourceKind:pt,version:1,encode:e=>({...e}),decode:e=>!Wt(e.transport)||!Gt(e.backend)||!Yt(e.outputPath)||!qt(e.pidPath)||!Kt(e.transport,e.backend)?Ut():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function Ut(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function Wt(e){return e===`apple-log-stream`||e===`coredevice-console`}function Gt(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Kt(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function qt(e){return e===void 0||Yt(e)}function Jt(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return ze({resourceKind:pt,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:Re(Ht,e.descriptor)})}function Yt(e){return typeof e==`string`&&e.trim().length>0}const Xt={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.`},Zt={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 Qt(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 $t(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(s(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await tt(async()=>et(await e.appleTools.run({tool:`simctl`,args:[`help`],allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(x);else{i.devicectlAvailable=await tt(async()=>et(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await Qt(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?Xt:Zt;a.push(`${e.message} ${e.hint}`)}}return{backend:S(t),checks:i,notes:a}}function en(e,t){let n=rn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=rn(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 tn(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,en(e.appBundleId,e.executableName)]}function nn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function rn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function an(e,t,n,r,i){on(t),Je(e,n);let a=S(t),o=await cn(e,t,n.appBundleId,i),s=new Ve,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await sn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=un(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=Ge(d,Jt({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function on(t){if(t.appleOs===`watchos`)throw new e(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(o(t)&&t.kind===`device`&&t.iosPhysicalDeviceBackend===`xctest`)throw new e(`UNSUPPORTED_OPERATION`,x,{hint:x})}async function sn(t,n,r,i,a,s){if(o(n)&&n.kind===`device`){let n=await Qt(t,s);if(!n.supported){let t=n.reason===`unsupported`?Xt:Zt;throw new e(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,t.message,{backend:`ios-device`,hint:t.hint,stderr:n.stderr})}}return s?.throwIfAborted(),await t.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function cn(e,t,n,r){if(s(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,en(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:nn(t.id,n),allowFailure:!0};let i=await ln(e,t,n,r);return{executable:`xcrun`,args:tn({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function ln(e,t,n,r){let i=t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],a=await e.appleTools.run({tool:`simctl`,args:[...i,`get_app_container`,t.id,n,`app`],allowFailure:!0,timeoutMs:4e3},r),o=a.exitCode===0?a.stdout.trim():``;if(!o)return;let s=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,Tt.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function un(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 Ze({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await dn([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 dn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const C=l(`apple`),w=Object.freeze({available:!0});function fn(t){return Object.freeze({owner:C,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>mn(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!u(n.intent.owner,C))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return pn(t,n.device,n.scope.signal)},shutdown:async()=>void 0})}function pn(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=We({codec:Ht,reattach:async(e,r)=>e.backend!==S(n)||!He(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await Ue(t,e.pidPath),cleanup:async(e,r)=>e.backend===S(n)&&He(t,r.sessionId,e)?await Ye(t,e.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:S(n)}),appLogDoctor:async({appBundleId:e})=>await $t(t,n,e,r),appLogStart:async e=>await an(t,n,e,C,r),...i});return Object.freeze({device:n,owner:C,facts:mn(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function mn(e){if(e.appleOs===`watchos`)return hn(e);let t=o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:x}:w;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:w,appLogCleanup:w}})}function hn(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 gn(e,t,n,r){let i=S(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=qe(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(vn(t,n,o.dump)){let i=await yn(e,t,n,a.path,r);i&&(o=_n(s,o,i,n.maxEntries))}return Sn(s,t,n),xn(s,o.dump),o.dump.entries.length===0&&s.push(Cn(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function _n(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).`),Xe(n.scan,t,r))}function vn(e,t,n){return o(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function yn(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,bn(n.appBundleId)],o=n.appLogSnapshot?.startedAt;a.push(...typeof o==`number`&&Number.isFinite(o)&&o>0?[`--start`,`@${Math.floor(o/1e3)}`]:[`--last`,`5m`]);let s=await e.appleTools.run({tool:`simctl`,args:a,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
1
+ import{C as e,w as t}from"./sdk-contracts.js";import{r as n}from"./sdk-batch-runner.js";import{S as r,c as i,h as a,l as o,u as s,w as c}from"./sdk-device.js";import{Gt as l,Xt as u,Zt as d}from"./sdk-batch.js";import{c as f,r as p}from"./diagnostics.js";import{n as m}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as h}from"./scoped-provider.js";import{i as ee,n as te,r as ne}from"./ios-snapshot-planning.js";import{t as re}from"./request.js";import{n as ie,r as ae,t as oe}from"./application-lifecycle-runtime.js";import{i as se,t as ce}from"./touch-runtime.js";import{A as le,C as ue,D as de,G as fe,H as pe,I as me,L as he,N as ge,O as _e,P as ve,R as ye,T as be,U as xe,V as Se,a as Ce,b as we,d as Te,g as Ee,i as De,j as Oe,m as ke,s as Ae,t as je,v as Me,w as Ne,x as Pe,z as Fe}from"./alert-runtime.js";import{n as Ie}from"./audio-probe-runtime.js";import{n as Le}from"./perf-runtime.js";import{a as Re,n as ze}from"./durable-resource.js";import{n as Be,t as Ve}from"./async-lifecycle.js";import{a as He,c as Ue,d as We,f as Ge,l as Ke,n as qe,o as Je,s as Ye,t as Xe,u as Ze}from"./src7.js";import{n as Qe,t as $e}from"./screen-recording-completion.js";import{a as et,i as tt,n as nt,r as rt,t as it}from"./stop-sequence.js";import{n as g}from"./screen-recording-runtime.js";import{t as at}from"./ios-system-surface.js";import{i as ot,r as st}from"./gesture-admission.js";import{t as ct}from"./interactor-operation-catalog.js";import{a as lt,i as ut,n as dt,r as ft,t as pt}from"./perf-runtime-operation-builder.js";import{t as mt}from"./app-log-runtime.js";import{i as ht,r as gt}from"./managed-device-scope.js";import{a as _t,n as vt,o as yt}from"./application-lifecycle-interaction.js";import{a as bt}from"./tool-provider.js";import{n as xt}from"./apps-simctl.js";import{a as St}from"./simulator.js";import{t as Ct}from"./multitouch-support.js";import{n as _,t as wt}from"./simulator-state.js";import{n as Tt,r as Et,t as Dt}from"./snapshot-process.js";import Ot from"node:path";import{randomUUID as kt}from"node:crypto";function At(e){let t=ht();return Object.freeze(t?{...h({...e},e=>St(t,e))}:e)}function jt(e){return rt(e)?Object.freeze({available:!0}):s(e)||o(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 Mt(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...pt({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 ut(t().sampleFrames(n,e)):dt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await ut(t().sampleMemory(n,e)):dt(`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 lt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw ft();let c=i??Ot.join(a,`memory-memgraph-${Nt()}.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 Nt(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const v=Object.freeze({available:!0}),y=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),b=Lt(`Gestures are supported only for Apple simulators and devices.`),Pt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:st}),Ft=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:ot}),It=Lt(`scroll is supported only for Apple simulators and devices.`);function Lt(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Rt(e){return{...ge({unsupported:zt(e),plan:Bt(e),directionalFling:Bt(e),multiTouch:Vt(e),targetAuthoredDrag:Ht(e),viewport:Ut(e)}),...le({scroll:Wt(e)})}}function zt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:b}function Bt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:x(e)?v:b}function Vt(e){if(e.appleOs===`watchos`)return y;if(!x(e))return b;let t=r(e);if(t!==`ios`&&t!==`ipados`){let e=Ct[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?v:Pt}function Ht(e){return x(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?v:Ft:b}function Ut(e){return e.appleOs===`watchos`?y:x(e)?v:b}function Wt(e){return x(e)?v:It}function x(e){return e.kind===`simulator`||e.kind===`device`}const S=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function C(e){return s(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const Gt=Object.freeze({resourceKind:mt,version:1,encode:e=>({...e}),decode:e=>!qt(e.transport)||!Jt(e.backend)||!Qt(e.outputPath)||!Xt(e.pidPath)||!Yt(e.transport,e.backend)?Kt():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function Kt(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function qt(e){return e===`apple-log-stream`||e===`coredevice-console`}function Jt(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Yt(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function Xt(e){return e===void 0||Qt(e)}function Zt(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return ze({resourceKind:mt,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:Re(Gt,e.descriptor)})}function Qt(e){return typeof e==`string`&&e.trim().length>0}const $t={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.`},en={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 tn(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 nn(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(s(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await et(async()=>tt(await e.appleTools.run({tool:`simctl`,args:[`help`],allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(S);else{i.devicectlAvailable=await et(async()=>tt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await tn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?$t:en;a.push(`${e.message} ${e.hint}`)}}return{backend:C(t),checks:i,notes:a}}function rn(e,t){let n=sn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=sn(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 an(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,rn(e.appBundleId,e.executableName)]}function on(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function sn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function cn(e,t,n,r,i){ln(t),Je(e,n);let a=C(t),o=await dn(e,t,n.appBundleId,i),s=new Ve,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await un(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=pn(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=Ge(d,Zt({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function ln(t){if(t.appleOs===`watchos`)throw new e(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(o(t)&&t.kind===`device`&&t.iosPhysicalDeviceBackend===`xctest`)throw new e(`UNSUPPORTED_OPERATION`,S,{hint:S})}async function un(t,n,r,i,a,s){if(o(n)&&n.kind===`device`){let n=await tn(t,s);if(!n.supported){let t=n.reason===`unsupported`?$t:en;throw new e(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,t.message,{backend:`ios-device`,hint:t.hint,stderr:n.stderr})}}return s?.throwIfAborted(),await t.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function dn(e,t,n,r){if(s(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,rn(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:on(t.id,n),allowFailure:!0};let i=await fn(e,t,n,r);return{executable:`xcrun`,args:an({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function fn(e,t,n,r){let i=t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],a=await e.appleTools.run({tool:`simctl`,args:[...i,`get_app_container`,t.id,n,`app`],allowFailure:!0,timeoutMs:4e3},r),o=a.exitCode===0?a.stdout.trim():``;if(!o)return;let s=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,Ot.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function pn(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 Ze({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await mn([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 mn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const w=l(`apple`),T=Object.freeze({available:!0});function hn(t){return Object.freeze({owner:w,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>_n(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!u(n.intent.owner,w))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return gn(t,n.device,n.scope.signal)},shutdown:async()=>void 0})}function gn(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=We({codec:Gt,reattach:async(e,r)=>e.backend!==C(n)||!He(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await Ue(t,e.pidPath),cleanup:async(e,r)=>e.backend===C(n)&&He(t,r.sessionId,e)?await Ye(t,e.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:C(n)}),appLogDoctor:async({appBundleId:e})=>await nn(t,n,e,r),appLogStart:async e=>await cn(t,n,e,w,r),...i});return Object.freeze({device:n,owner:w,facts:_n(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function _n(e){if(e.appleOs===`watchos`)return vn(e);let t=o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:S}:T;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:T,appLogCleanup:T}})}function vn(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 yn(e,t,n,r){let i=C(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=qe(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(xn(t,n,o.dump)){let i=await Sn(e,t,n,a.path,r);i&&(o=bn(s,o,i,n.maxEntries))}return Tn(s,t,n),wn(s,o.dump),o.dump.entries.length===0&&s.push(En(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function bn(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).`),Xe(n.scan,t,r))}function xn(e,t,n){return o(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function Sn(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,Cn(n.appBundleId)],o=n.appLogSnapshot?.startedAt;a.push(...typeof o==`number`&&Number.isFinite(o)&&o>0?[`--start`,`@${Math.floor(o/1e3)}`]:[`--last`,`5m`]);let s=await e.appleTools.run({tool:`simctl`,args:a,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
2
2
  `).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:qe(`${c.join(`
3
- `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function bn(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 xn(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 Sn(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(o(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 Cn(e){return o(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.`:o(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 T(e,n,r,i){if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let a;try{a=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!n.invalidatedReason&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r})}catch(e){throw t(e,`COMMAND_FAILED`)}let o=[...a.warning?[a.warning]:[],...i?[i]:[]];return $e(n,{...a,...o.length>0?{warning:o.join(` `)}:{},...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{}})}const E=Object.freeze({resourceKind:rt,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e}))}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>An(e)});function wn(e){let{device:t,owner:n,input:r,descriptor:i}=e;return ze({resourceKind:rt,sessionId:r.sessionId,device:c(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:Re(E,i)})}async function Tn(e,t,n,r){let i=E.decode(n);return i.status!==`decoded`||!Ln(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await En(e,i.descriptor.processes,r):await On(e,t,i.descriptor)}async function En(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(Dn(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(Dn(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function Dn(e){return{kind:`session`,sessionId:e}}async function On(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 kn(e,t,n){let r=E.decode(n);if(r.status!==`decoded`)return{status:`unreattachable`,reason:`descriptor-invalid`,message:r.message};if(!Ln(t,r.descriptor))return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple screen-recording descriptor does not match the bound device.`};let i=r.descriptor.backend===`simctl`?await Promise.all(r.descriptor.processes.map(async t=>await e.screenRecording.apple.inspectProcess(t))):[await e.screenRecording.apple.inspectRunner(t,r.descriptor.runnerSessionId,r.descriptor.runnerAuthority)];return i.every(e=>e===`missing`)?{status:`missing`}:{status:`unreattachable`,reason:`transport-not-reattachable`,message:i.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`}}function An(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?D():e.backend===`simctl`?jn(e,e.outputPath):e.backend===`runner`?Mn(e,e.outputPath):D()}function jn(e,t){let n=Rn(e.processes);return n?{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n})}:D()}function Mn(e,t){return!Nn(e.appBundleId)||!Nn(e.runnerSessionId)||!Pn(e.runnerAuthority)||!Fn(e.remotePath)?D():{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 Nn(e){return typeof e==`string`&&e.length>0}function Pn(e){return e===`local-lease`||e===`scoped-provider`}function Fn(e){return e===void 0||In(e)}function In(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Ln(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:o(e)?t.remotePath!==void 0&&In(t.remotePath):t.remotePath===void 0:!1}function Rn(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 D(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function zn(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.`)}function Bn(e){return e.appleOs===`watchos`?Qn(`unsupported-platform-leaf`,`watchOS recording is not supported.`):o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Qn(`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 Vn(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Hn({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await kn(t,n,e.envelope.descriptor.body),screenRecordingCleanup:async e=>await Tn(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Hn(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Un(e):await Wn(e)}async function Un(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await zn(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0;await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.startSimulator(n,i.outputPath,a),c=s.markers;if(!c||c.length===0)throw await O(s).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted(),t.screenRecording.ownedProcesses.replace({kind:`session`,sessionId:i.sessionId},c.map(e=>({...e,purpose:`simctl-screen-recording`})))}catch(e){try{t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId})}catch{}throw await O(s).catch(()=>{}),e}return Xn({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:i.outputPath,processes:c},snapshot:Zn(i,`simctl recordVideo`,{},o),finish:async e=>{await s.terminate();let n=await s.wait;t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId});let r=Kn(n);if(r===void 0)return await T(t,e,`iOS recording`);try{return await T(t,e,`iOS recording`,`${r} before record stop; the video covers only what the recorder wrote before it stopped.`)}catch(e){throw qn(e,r,n)}},cleanup:async()=>{let e=await Yn(s);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}async function Wn(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??=Gn(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!Jn(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 Xn({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:Zn(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await T(t,e,n.appleOs===`macos`?`macOS recording`:`iOS recording`)),cleanup:async()=>(await u(),{status:`cleaned`})})}async function Gn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}function Kn(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function qn(n,r,i){let a=t(n,`COMMAND_FAILED`);return a.details?.reason===`recording-output-unplayable`?new e(a.code,`${a.message}; ${r}`,m(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.`})):n}function Jn(e,t){return e.appleOs===`macos`||!o(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function O(e){return await e.terminate(),await e.wait}async function Yn(e){try{return await O(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function Xn(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=Qe(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new Be(c),envelope:wn({device:t,owner:n,input:r,descriptor:i})})}function Zn(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},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}})}function Qn(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const $n=15e3;async function k(e,t,n,r={}){return n.throwIfAborted(),await ht(t)||s(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await er(e,t)?`Booted`:await ir(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await tr(e,t,n,r.deadlineAtMs),await ar(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function er(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function tr(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await nr(e,t,n,r),await rr(e,t,n,r)}catch(a){throw i&&n.aborted&&or(e,t),n.throwIfAborted(),Date.now()>=r?j(t,a):a}}async function nr(t,n,r,i){let a=await t.appleTools.run({tool:`simctl`,args:g(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:A(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 e(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function rr(t,n,r,i){re({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await t.appleTools.run({tool:`simctl`,args:g(n,[`bootstatus`,n.id,`-b`]),allowFailure:!0,timeoutMs:A(i,n)},r);if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(await Ct(t.appleTools,n,r,Math.min($n,A(i,n)))!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:n.id});if(Date.now()>=i)throw j(n)}function A(e,t){let n=e-Date.now();if(n<=0)throw j(t);return n}function j(t,n){return new e(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:`boot_timeout`,deviceId:t.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 ir(e,t,n){return await Ct(e.appleTools,t,n,$n)}async function ar(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function or(e,t){e.appleTools.run({tool:`simctl`,args:g(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const sr=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`,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:`simulator`,setSetting:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`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`,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 cr(e){return e===void 0?`possible`:e.some(e=>sr[e]===`runner`)?`required`:`none`}const lr=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function M(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function ur(e){let t=ee(ne({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!M(n))return`not-eligible`;let a;for(;;){let o=await e.resolveTarget(n,r,i).catch(()=>void 0);if(i.throwIfAborted(),!o)return`unobservable`;if(e.isBridgeDisabled(o))return p({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:o.generation}}),`unobservable`;let s=await e.source.acquire({target:o,hint:t,signal:i});if(s.stage!==`failed`)return`observable`;i.throwIfAborted();let c=lr.get(s.failure.code);if(c===void 0)return`unobservable`;let l=e.clock.now();if(a=Math.min(a??1/0,l+c),l>=a)return`unobservable`;await e.clock.sleep(Math.min(150,a-l),i)}}})}function dr(e,t,n){let r=n&&M(e),i=r?cr(t.execution.plannedOperations):void 0,a=o(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function fr(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function pr(e,t,n,r,i,a){let o=Date.now();r&&M(t.device)&&i&&n.appBundleId&&(a.postOpenObservation=await i.awaitObservable(t.device,n.appBundleId,t.signal)),r&&a.postOpenObservation!==`observable`&&await e.clock.sleep(300,t.signal),a.postOpenSettleDurationMs=Math.max(0,Date.now()-o)}function mr(e){let t=_t({device:e.device,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(e.device,t),prepareApplicationOpen:async t=>{await k(e.host,e.device,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(e.device,t.execution,e.signal).catch(()=>{})}:void 0})},openApplication:async n=>await hr(e.host,t,n,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(e.device,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(e.device,t),closeApplication:async n=>await Tr(e.host,t,n),finalizeApplicationClose:async t=>await Er(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await Dr(e.host,e.device,e.signal,t),configureProviderPortReverse:Mr})}async function hr(e,t,n,r){let i={},a=N(t.device),o=Or(e,t,n,i),s=dr(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),fr(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=wr(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await gr(e,t,n,a,l,i),await _r(n,i),await vr(o,c,n.prewarmRunnerBeforeOpen);let u=o.wasAwaited();return await yr(t,n,a,i),await xr(o,c,s.awaitPrewarmAfterOpen),await Sr(e,t,n,a,u,l),await pr(e,t,n,a,r,i),{appBundleId:n.appBundleId,timing:i}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function gr(e,t,n,r,a,o){if(!Cr(n,r)||!n.target)return;let s=Date.now();i(t.device.platform)&&!r&&!a&&await e.appleApplications.stopRunnerSession(t.device.id),await gt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),o.relaunchCloseDurationMs=P(s)}async function _r(t,n){if(!ae(t.runtimeHints))return;if(!t.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let r=Date.now();await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints}),n.runtimeHintsDurationMs=P(r)}async function vr(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function yr(e,t,n,r){let i=Ar(t,n),a=Date.now();await vt({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:i.positionals,appBundleId:t.appBundleId,execution:t.execution,...n&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),r.openDispatchDurationMs=P(a),await br(e,t,i.followUpUrl,r)}async function br(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},a=Date.now();await vt({device:e.device,interactor:await e.resolveInteractor(i,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:i}),r.launchUrlDurationMs=P(a)}async function xr(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function Sr(e,t,n,r,i,a){!o(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 Cr(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function wr(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&Cr(t,n)}async function Tr(e,t,n){n.ensureReady&&await k(e,t.device,t.signal),i(t.device.platform)&&!N(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await gt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),N(t.device)&&await e.clock.sleep(300,t.signal)}async function Er(e,t,n,r){r.daemonShutdown?await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{}):r.retainRunner?(e.appleApplications.scheduleRunnerIdleStop(t.id),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{})):(await e.appleApplications.stopRunnerSession(t.id),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{}));let i=r.shutdownTarget&&N(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function Dr(e,t,n,r){let i=Date.now()+r.timeoutMs;await k(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function Or(e,t,n,r){let i,a=!1,o=kr(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=P(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function kr(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function Ar(e,t){let r=e.runtimeLaunchUrl?.trim(),i=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!r||!i||n(i)?{positionals:e.positionals}:t&&!jr(e)?{positionals:[i,r]}:{positionals:e.positionals,followUpUrl:r}}function jr(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function N(e){return o(e)&&e.kind===`simulator`}function P(e){return Math.max(0,Date.now()-e)}async function Mr(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const Nr=Object.freeze({available:!0}),Pr=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.`}),Fr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),Ir=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Lr=Object.freeze({available:!1,reason:`unsupported-device-kind`});function Rr(e){let t=Kr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:qr(e)})}function zr(e){let{host:t,device:n,signal:r}=e,i=Rr(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await Br(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Vr(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Wr(t,n,e,r),{})}:{}})}async function Br(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Ur(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Hr(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 Vr(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function Vr(e,t,n,r){return await Hr(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 Hr(e,t,n,r){await k(e,t,r),F(await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:g(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:12e4},r),`Apple app install failed`)}async function Ur(e,t,n,r){await k(e,t,r);let i=await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:g(t,[`uninstall`,t.id,n]),allowFailure:!0}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n],allowFailure:!0},r);i.exitCode===0||Gr(`${i.stdout}\n${i.stderr}`)||F(i,`Apple app uninstall failed for ${n}`)}async function Wr(t,n,r,i){if(n.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await k(t,n,i);let a=await t.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),F(await t.appleTools.run({tool:`simctl`,args:g(n,[`push`,n.id,r.appId,a.path])},i),`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}function Gr(e){let t=e.toLowerCase();return t.includes(`not installed`)||t.includes(`not found`)||t.includes(`no such file`)}function F(t,n){if(t.exitCode!==0)throw new e(`COMMAND_FAILED`,n,{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}function Kr(e){return Jr(e)?e.kind!==`simulator`&&e.kind!==`device`?Lr:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Pr:Nr:Ir}function qr(e){return Jr(e)?e.kind===`simulator`?Nr:Fr:Ir}function Jr(e){return o(e)&&e.appleOs!==`watchos`}const I=Object.freeze({available:!0}),Yr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),Xr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Zr(e){return e.kind!==`simulator`&&e.kind!==`device`?Yr:r(e)===`watchos`?Xr:I}const Qr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),$r=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ei=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function ti(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=r(e);return n===`macos`||n===`watchos`?$r:I}function L(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=r(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const ni=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),ri=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ii(e){return e.kind!==`simulator`&&e.kind!==`device`?ni:L(e)?I:ri}const ai=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function oi(e){return(e.kind===`simulator`||e.kind===`device`)&&a(e)?I:ai}const R=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),si=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 ci(e){return L(e)?si:R}function li(e){return L(e)?I:R}function ui(e){return L(e)?I:R}function di(e){return Object.freeze({...Pe({back:Zr(e)}),...we({home:ti(e,Qr)}),...Ae({appSwitcher:ti(e,ei)}),...Me({orientation:ii(e)}),...Ee({tvRemote:oi(e)}),...ke({unsupported:R,status:ci(e),dismiss:li(e),enter:ui(e)})})}function fi(e){let{host:t,device:n,signal:r}=e;return st({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:di(n)})}const z=Object.freeze({available:!0}),pi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),mi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),hi=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.`}),gi=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.`}),B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function _i(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let i=r(e);return i===`watchos`?B:e.kind===`simulator`||i===`macos`?z:n}function vi(e){return _i(e,pi,gi)}const yi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),bi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),xi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function Si(e){if(e.kind!==`simulator`&&e.kind!==`device`)return bi;let t=r(e);return t===`watchos`?B:e.kind===`simulator`||t===`ios`||t===`macos`?z:xi}function Ci(e){return e.kind!==`simulator`&&e.kind!==`device`?yi:r(e)===`watchos`?B:z}function wi(e){let t=vi(e);return t.available?gi:t}function Ti(e){let t=vi(e),n=Si(e);return Object.freeze({...Te({unsupported:wi(e),read:t,write:t}),...je({read:n,wait:n,accept:n,dismiss:n}),...Ce({triggerAppEvent:Ci(e)}),...De({setSetting:_i(e,mi,hi)})})}function Ei(e){let{host:t,device:n,signal:r}=e;return st({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Ti(n)})}function Di(e,t,n){let r=Fe({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(s(t.device)&&i.options?.surface!==void 0&&i.options.surface!==`app`)return await e.snapshot.captureSurface(t.device,i.options,Se(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=Se(t.signal,i);return await n.capture(t.device,i,a,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function Oi(e,t){return Object.freeze({findText:async n=>{let r=await ki(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 ki(e,t,n){let r=n.options?.appBundleId;if(r===void 0)return;let i=n.options?.surface;if(s(t.device)&&i!==void 0&&i!==`app`)return;let a=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(a.throwIfAborted(),await Ai(e,t.device,n.execution))return{appBundleId:r,signal:a}}async function Ai(e,t,n){return!M(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function ji(){let e,t=!1,n=async()=>(e??=import(`./adapter.js`).then(({createSimulatorSnapshotSource:e})=>e()),await e);return{acquire:async e=>t?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await n()).acquire(e),close:async()=>{t=!0,e&&await(await e).close()}}}const Mi=3e3;function Ni(){let e=new Map,t=new Map,n=new Map;return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);if(c&&o!==`refresh`&&await wt(c.pid,{signal:a,timeoutMs:Mi})===c.processStartTime)return c;e.delete(s);let l=t.get(s);return l||(l=Fi(r,i,n).then(t=>(e.set(s,t),t)).finally(()=>t.delete(s)),l.catch(()=>void 0),t.set(s,l)),await Pi(l,a,r,i)}}async function Pi(e,t,n,r){let i,a,o=new Promise((e,o)=>{i=setTimeout(()=>o(H(`simulator-target-discovery-pending`,n,r)),1500),a=()=>o(t.reason),t.addEventListener(`abort`,a,{once:!0})});try{return await Promise.race([e,o])}finally{clearTimeout(i),a&&t.removeEventListener(`abort`,a)}}async function Fi(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([bt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:V(r)}),Ii(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 H(`simulator-target-probe-failed`,e,t);let c=Li(o.stdout,t);if(!c)throw H(`simulator-target-unavailable`,e,t);let l=await wt(c.pid,{timeoutMs:Math.min(Mi,V(r))});if(!l)throw H(`simulator-target-identity-unavailable`,e,t);return Object.freeze({udid:e.id,runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Ii(e,t,n){let r=t.get(e.id);if(r)return await r;let i=bt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:V(n)}).then(t=>{if(t.exitCode!==0)throw H(`simulator-runtime-probe-failed`,e,``);let n=JSON.parse(t.stdout),r=Object.entries(n.devices??{}).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!r)throw H(`simulator-runtime-unavailable`,e,``);return r});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Li(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 V(e){return Math.max(1,e-Date.now())}function H(t,n,r){return new e(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${t}).`,{reason:t,deviceId:n.id,appBundleId:r})}function Ri(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 zi(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function zi(e,t){let n=!1;for(let r of it){let i=await Bi(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await Vi(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function Bi(e,t){let n=await Hi(`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 Vi(e,t,n){let r=await Hi(`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 Hi(e,t,n){try{let r=await yt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Ui=`system-surface-presented`,Wi=`system-surface-host-lingering`;function Gi(t,n={}){let r=n.source??ji(),i=n.resolveTarget??Ni(),a=n.systemSurfacePresent??Ri(),o=new Set,s=new Map,c=e=>(na(e,s,o),o.has(ra(e))),l=ur({source:r,resolveTarget:i,clock:t.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(n,s,l,u)=>{if(!Ji(n,s))return await Zi(n,s,u);let d=await a(n,l);if(d===`unknown`)return await U(n.id,s,u,W(n.id,s),q(s),`system-surface-probe-unavailable`,[K()]);if(d!==`absent`)return await Xi(n,s,u,d.host.bundleId);let p;try{p=await Ki(t,i,n,s,l)}catch(e){return l.throwIfAborted(),J(`target-resolution-failed`,n,void 0,e),await U(n.id,s,u,W(n.id,s),q(s),`target-resolution-failed`,[K()])}if(c(p))return await U(n.id,s,u,p,q(s),`circuit-disabled`);let m=q(s),h=await r.acquire({target:p,hint:ee(m),signal:l});if(h.stage===`failed`){if(h.failure.kind===`cancelled`)throw l.throwIfAborted(),new e(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:h.failure.code,...h.failure.details});let t=await ta(h.failure,p,n,s.options.appBundleId,l,i);return await Yi(s,u,p,t,m,h.failure,o)}try{return await f(`ios.snapshot-source.present`,async()=>await t.snapshot.presentIosAcquisition(h,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await Yi(s,u,p,{lineage:p,residue:[]},m,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Ki(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!qi(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function qi(t){return t instanceof e&&t.details?.reason===`simulator-target-discovery-pending`}function Ji(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 Yi(e,t,n,r,i,a,o,s){return o.add(ra(n)),J(a.code,{id:n.udid},n.generation,s,a.details),await U(n.udid,e,t,r.lineage,i,a.code,r.residue)}async function U(e,t,n,r,i,a,o=[]){return Qi(e,await n(t),r,i,a,o)}async function Xi(e,t,n,r){let i=await n(t),a=i.systemSurface?Ui:Wi;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),Qi(e.id,i,W(e.id,t),q(t),a)}async function Zi(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:$i(G(e.id,i.bundleId),q(t),[])}:r}function Qi(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:$i(o?G(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],ea(i,n,o!==void 0)]}}function W(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function G(e,t){return{targetId:`${e}:${t}`}}function $i(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:te(t),residue:Object.freeze([...n])})}function ea(e,t,n){return e===Ui?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Wi?`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.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function ta(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:[K()]}}}function K(){return{kind:`unknown-generation`,captureId:Et()}}function q(e){return ne({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 na(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 ra(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){p({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=l(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ia=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`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.`}),aa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`}),oa=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),sa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),ca=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate reads the active session state; a sessionless runtime foreground probe is unavailable.`}),la=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),ua=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),da=Object.freeze({available:!1,reason:`unsupported-device-kind`}),fa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),pa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),ma=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),ha=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),ga=Q(`open is supported only for Apple simulators and devices.`),_a=Q(`prepare is supported only for Apple simulators and devices.`),va=Q(`close is supported only for Apple simulators and devices.`),ya=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),xa=Q(`snapshot is supported only for Apple simulators and devices.`),Sa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Ca=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),wa=Q(`screenshot is supported only for Apple simulators and devices.`),Ta=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Open the app under test before capturing its snapshot.`});function Q(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Ea(e){return!o(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:ba}function Da(e){let t=Oa(e),n=ka(e),r=Aa(e),i=ja(e);return oe({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:ya})}function Oa(e){return r(e)===`watchos`?fa:e.kind===`simulator`||e.kind===`device`?X:ga}function ka(e){return r(e)===`watchos`?pa:e.kind===`simulator`||e.kind===`device`?X:_a}function Aa(e){return r(e)===`watchos`?ma:e.kind===`simulator`||e.kind===`device`?X:va}function ja(e){return r(e)!==`watchos`&&o(e)&&e.kind===`simulator`?X:ha}function Ma(e){return e.appleOs===`watchos`?Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app inventory is not supported.`}):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`App inventory is available only on CoreDevice-backed physical iOS devices.`}):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:sa}function Na(e){let t=fn(e),n=Gi(e),r=async n=>{let r=await t.inspectFacts(n),i=Rr(n),a=Bn(n),c=a.available?await e.screenRecording.apple.availability(n):void 0,l=a.available&&c?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:c.hint}):a,u=n.appleOs===`watchos`?Z:X,d=s(n)||n.appleOs===`watchos`?Z:X,f=Ma(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:ca,networkDump:X,screenRecordingStart:l,screenRecordingReattach:l,screenRecordingCleanup:l,...Ra(n),...fe({capture:La(n)}),...ye({findText:Ia(n)}),...he({setViewport:ia}),...me({focus:$(n)}),...Ft(n),...de({type:$(n)}),...se({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...o(n)?{tapElementSelector:$(n)}:{}}),...Ne({readTextAtPoint:Fa(n)}),...di(n),...Ti(n),...Ie({capture:Ot(n),query:aa}),...Le(Pa(n)),ensureReady:u,bootTarget:d,bootTargetHeadless:la,listApps:f,...Da(n),shutdownTarget:Ea(n)}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:r,bind:async i=>{let a=await t.bind(i),o=await r(i.device),s=o.operations.screenRecordingStart,c={...a.operations,...zr({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await gn(e,i.device,t,i.scope.signal),...d(s,()=>Vn({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...d(o.operations.audioProbeStart,()=>Ke({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...d(o.operations.perfFrames,()=>kt({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...d(o.operations.captureSnapshot,()=>Di(e,{device:i.device,signal:i.scope.signal},n)),...d(o.operations.captureScreenshot,()=>xe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.focusPoint,()=>ve({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...Oe({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...d(o.operations.scrollDirection,()=>_e({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.typeText,()=>be({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.tapPoint,()=>ce({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)})),...d(o.operations.readTextAtPoint,()=>ue({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.findText,()=>Oi(e,{device:i.device,signal:i.scope.signal})),...fi({host:e,device:i.device,signal:i.scope.signal}),...Ei({host:e,device:i.device,signal:i.scope.signal}),...d(o.operations.ensureReady,()=>({ensureReady:async()=>await k(e,i.device,i.scope.signal)})),...d(o.operations.bootTarget,()=>({bootTarget:async()=>await k(e,i.device,i.scope.signal)})),...d(o.operations.listApps,()=>({listApps:async e=>{i.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}))}})),...ie(mr({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...d(o.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(i.device,i.scope.signal)}))};return Object.freeze({device:a.device,owner:Y,facts:o,operations:Dt(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Pa(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&r(e)!==`watchos`?X:oa;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Fa(e){return r(e)===`watchos`?ua:e.kind===`simulator`||e.kind===`device`?X:da}function Ia(e){return r(e)===`watchos`?xa:e.kind===`simulator`||e.kind===`device`?X:xa}function La(e){return r(e)===`watchos`?Ca:e.kind===`simulator`||e.kind===`device`?X:wa}function Ra(e){let t=Ia(e);return pe({capture:t,customActions:t.available&&o(e)&&e.kind===`simulator`?X:Sa,withoutActiveApp:o(e)?Ta:t})}export{Na as createApplePlatformRuntime};
3
+ `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function Cn(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 wn(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 Tn(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(o(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 En(e){return o(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.`:o(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 Dn(e){let{host:n,snapshot:r,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=e,s=r.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:e.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`,targetLabel:i})}catch(e){throw t(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return $e(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function On(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;try{await t.screenRecording.outputs.copy({from:i,to:a}),s=await kn(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:!n.invalidatedReason&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...s,...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function kn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}const E=Object.freeze({resourceKind:g,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e}))}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>In(e)});function An(e){let{device:t,owner:n,input:r,descriptor:i}=e;return ze({resourceKind:g,sessionId:r.sessionId,device:c(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:Re(E,i)})}async function jn(e,t,n,r){let i=E.decode(n);return i.status!==`decoded`||!Un(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await Mn(e,i.descriptor.processes,r):await Pn(e,t,i.descriptor)}async function Mn(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(Nn(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(Nn(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function Nn(e){return{kind:`session`,sessionId:e}}async function Pn(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 Fn(e,t,n){let r=E.decode(n);if(r.status!==`decoded`)return{status:`unreattachable`,reason:`descriptor-invalid`,message:r.message};if(!Un(t,r.descriptor))return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple screen-recording descriptor does not match the bound device.`};let i=r.descriptor.backend===`simctl`?await Promise.all(r.descriptor.processes.map(async t=>await e.screenRecording.apple.inspectProcess(t))):[await e.screenRecording.apple.inspectRunner(t,r.descriptor.runnerSessionId,r.descriptor.runnerAuthority)];return i.every(e=>e===`missing`)?{status:`missing`}:{status:`unreattachable`,reason:`transport-not-reattachable`,message:i.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`}}function In(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?D():e.backend===`simctl`?Ln(e,e.outputPath):e.backend===`runner`?Rn(e,e.outputPath):D()}function Ln(e,t){let n=Wn(e.processes);return n?{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n})}:D()}function Rn(e,t){return!zn(e.appBundleId)||!zn(e.runnerSessionId)||!Bn(e.runnerAuthority)||!Vn(e.remotePath)?D():{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 zn(e){return typeof e==`string`&&e.length>0}function Bn(e){return e===`local-lease`||e===`scoped-provider`}function Vn(e){return e===void 0||Hn(e)}function Hn(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Un(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:o(e)?t.remotePath!==void 0&&Hn(t.remotePath):t.remotePath===void 0:!1}function Wn(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 D(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Gn(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.`)}function Kn(e){return e.appleOs===`watchos`?ir(`unsupported-platform-leaf`,`watchOS recording is not supported.`):o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?ir(`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 qn(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Jn({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await Fn(t,n,e.envelope.descriptor.body),screenRecordingCleanup:async e=>await jn(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Jn(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Yn(e):await Xn(e)}async function Yn(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Gn(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=nt(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 O(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 O(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Qn(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.`}}};return nr({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l},snapshot:rr(i,`simctl recordVideo`,{},o),finish:(e,n)=>it({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await t.screenRecording.outputs.copy({from:s,to:e}),await t.screenRecording.finalize.sniff({outputPath:e})}catch(e){throw $n(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await On({host:t,snapshot:e,targetLabel:`iOS recording`,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw $n(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await tr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}async function Xn(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??=Zn(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!er(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 nr({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:rr(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await Dn({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 Zn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}function Qn(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function $n(n,r,i){let a=t(n,`COMMAND_FAILED`);return r===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?n:new e(a.code,`${a.message}; ${r}`,m(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 er(e,t){return e.appleOs===`macos`||!o(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function O(e){return await e.terminate(),await e.wait}async function tr(e){try{return await O(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function nr(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=Qe(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new Be(c),envelope:An({device:t,owner:n,input:r,descriptor:i})})}function rr(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},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}})}function ir(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const ar=15e3;async function k(e,t,n,r={}){return n.throwIfAborted(),await gt(t)||s(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await or(e,t)?`Booted`:await ur(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await sr(e,t,n,r.deadlineAtMs),await dr(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function or(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function sr(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await cr(e,t,n,r),await lr(e,t,n,r)}catch(a){throw i&&n.aborted&&fr(e,t),n.throwIfAborted(),Date.now()>=r?j(t,a):a}}async function cr(t,n,r,i){let a=await t.appleTools.run({tool:`simctl`,args:_(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:A(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 e(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function lr(t,n,r,i){re({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await t.appleTools.run({tool:`simctl`,args:_(n,[`bootstatus`,n.id,`-b`]),allowFailure:!0,timeoutMs:A(i,n)},r);if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(await wt(t.appleTools,n,r,Math.min(ar,A(i,n)))!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:n.id});if(Date.now()>=i)throw j(n)}function A(e,t){let n=e-Date.now();if(n<=0)throw j(t);return n}function j(t,n){return new e(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:`boot_timeout`,deviceId:t.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 ur(e,t,n){return await wt(e.appleTools,t,n,ar)}async function dr(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function fr(e,t){e.appleTools.run({tool:`simctl`,args:_(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const pr=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`,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:`simulator`,setSetting:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`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`,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 mr(e){return e===void 0?`possible`:e.some(e=>pr[e]===`runner`)?`required`:`none`}const hr=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function M(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function gr(e){let t=ee(ne({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!M(n))return`not-eligible`;let a;for(;;){let o=await e.resolveTarget(n,r,i).catch(()=>void 0);if(i.throwIfAborted(),!o)return`unobservable`;if(e.isBridgeDisabled(o))return p({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:o.generation}}),`unobservable`;let s=await e.source.acquire({target:o,hint:t,signal:i});if(s.stage!==`failed`)return`observable`;i.throwIfAborted();let c=hr.get(s.failure.code);if(c===void 0)return`unobservable`;let l=e.clock.now();if(a=Math.min(a??1/0,l+c),l>=a)return`unobservable`;await e.clock.sleep(Math.min(150,a-l),i)}}})}function _r(e,t,n){let r=n&&M(e),i=r?mr(t.execution.plannedOperations):void 0,a=o(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function vr(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function yr(e,t,n,r,i,a){let o=Date.now();r&&M(t.device)&&i&&n.appBundleId&&(a.postOpenObservation=await i.awaitObservable(t.device,n.appBundleId,t.signal)),r&&a.postOpenObservation!==`observable`&&await e.clock.sleep(300,t.signal),a.postOpenSettleDurationMs=Math.max(0,Date.now()-o)}function br(e){let t=vt({device:e.device,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(e.device,t),prepareApplicationOpen:async t=>{await k(e.host,e.device,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(e.device,t.execution,e.signal).catch(()=>{})}:void 0})},openApplication:async n=>await xr(e.host,t,n,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(e.device,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(e.device,t),closeApplication:async n=>await jr(e.host,t,n),finalizeApplicationClose:async t=>await Mr(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await Nr(e.host,e.device,e.signal,t),configureProviderPortReverse:Rr})}async function xr(e,t,n,r){let i={},a=N(t.device),o=Pr(e,t,n,i),s=_r(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),vr(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=Ar(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Sr(e,t,n,a,l,i),await Cr(n,i),await wr(o,c,n.prewarmRunnerBeforeOpen);let u=o.wasAwaited();return await Tr(t,n,a,i),await Dr(o,c,s.awaitPrewarmAfterOpen),await Or(e,t,n,a,u,l),await yr(e,t,n,a,r,i),{appBundleId:n.appBundleId,timing:i}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Sr(e,t,n,r,a,o){if(!kr(n,r)||!n.target)return;let s=Date.now();i(t.device.platform)&&!r&&!a&&await e.appleApplications.stopRunnerSession(t.device.id),await _t({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),o.relaunchCloseDurationMs=P(s)}async function Cr(t,n){if(!ae(t.runtimeHints))return;if(!t.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let r=Date.now();await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints}),n.runtimeHintsDurationMs=P(r)}async function wr(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Tr(e,t,n,r){let i=Ir(t,n),a=Date.now();await yt({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:i.positionals,appBundleId:t.appBundleId,execution:t.execution,...n&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),r.openDispatchDurationMs=P(a),await Er(e,t,i.followUpUrl,r)}async function Er(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},a=Date.now();await yt({device:e.device,interactor:await e.resolveInteractor(i,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:i}),r.launchUrlDurationMs=P(a)}async function Dr(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function Or(e,t,n,r,i,a){!o(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 kr(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function Ar(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&kr(t,n)}async function jr(e,t,n){n.ensureReady&&await k(e,t.device,t.signal),i(t.device.platform)&&!N(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await _t({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),N(t.device)&&await e.clock.sleep(300,t.signal)}async function Mr(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&&N(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function Nr(e,t,n,r){let i=Date.now()+r.timeoutMs;await k(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function Pr(e,t,n,r){let i,a=!1,o=Fr(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=P(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function Fr(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function Ir(e,t){let r=e.runtimeLaunchUrl?.trim(),i=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!r||!i||n(i)?{positionals:e.positionals}:t&&!Lr(e)?{positionals:[i,r]}:{positionals:e.positionals,followUpUrl:r}}function Lr(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function N(e){return o(e)&&e.kind===`simulator`}function P(e){return Math.max(0,Date.now()-e)}async function Rr(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const zr=Object.freeze({available:!0}),Br=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.`}),Vr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),Hr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ur=Object.freeze({available:!1,reason:`unsupported-device-kind`});function Wr(e){let t=Qr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:$r(e)})}function Gr(e){let{host:t,device:n,signal:r}=e,i=Wr(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await Kr(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await qr(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Xr(t,n,e,r),{})}:{}})}async function Kr(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Yr(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Jr(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 qr(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function qr(e,t,n,r){return await Jr(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 Jr(e,t,n,r){await k(e,t,r),F(await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:_(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:12e4},r),`Apple app install failed`)}async function Yr(e,t,n,r){await k(e,t,r);let i=await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:_(t,[`uninstall`,t.id,n]),allowFailure:!0}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n],allowFailure:!0},r);i.exitCode===0||Zr(`${i.stdout}\n${i.stderr}`)||F(i,`Apple app uninstall failed for ${n}`)}async function Xr(t,n,r,i){if(n.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await k(t,n,i);let a=await t.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),F(await t.appleTools.run({tool:`simctl`,args:_(n,[`push`,n.id,r.appId,a.path])},i),`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}function Zr(e){let t=e.toLowerCase();return t.includes(`not installed`)||t.includes(`not found`)||t.includes(`no such file`)}function F(t,n){if(t.exitCode!==0)throw new e(`COMMAND_FAILED`,n,{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}function Qr(e){return ei(e)?e.kind!==`simulator`&&e.kind!==`device`?Ur:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Br:zr:Hr}function $r(e){return ei(e)?e.kind===`simulator`?zr:Vr:Hr}function ei(e){return o(e)&&e.appleOs!==`watchos`}const I=Object.freeze({available:!0}),ti=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),ni=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ri(e){return e.kind!==`simulator`&&e.kind!==`device`?ti:r(e)===`watchos`?ni:I}const ii=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),ai=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),oi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function si(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=r(e);return n===`macos`||n===`watchos`?ai:I}function L(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=r(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const ci=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),li=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ui(e){return e.kind!==`simulator`&&e.kind!==`device`?ci:L(e)?I:li}const di=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function fi(e){return(e.kind===`simulator`||e.kind===`device`)&&a(e)?I:di}const R=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),pi=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 mi(e){return L(e)?pi:R}function hi(e){return L(e)?I:R}function gi(e){return L(e)?I:R}function _i(e){return Object.freeze({...Pe({back:ri(e)}),...we({home:si(e,ii)}),...Ae({appSwitcher:si(e,oi)}),...Me({orientation:ui(e)}),...Ee({tvRemote:fi(e)}),...ke({unsupported:R,status:mi(e),dismiss:hi(e),enter:gi(e)})})}function vi(e){let{host:t,device:n,signal:r}=e;return ct({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:_i(n)})}const z=Object.freeze({available:!0}),yi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),bi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),xi=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.`}),Si=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.`}),B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ci(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let i=r(e);return i===`watchos`?B:e.kind===`simulator`||i===`macos`?z:n}function wi(e){return Ci(e,yi,Si)}const Ti=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),Ei=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),Di=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function Oi(e){if(e.kind!==`simulator`&&e.kind!==`device`)return Ei;let t=r(e);return t===`watchos`?B:e.kind===`simulator`||t===`ios`||t===`macos`?z:Di}function ki(e){return e.kind!==`simulator`&&e.kind!==`device`?Ti:r(e)===`watchos`?B:z}function Ai(e){let t=wi(e);return t.available?Si:t}function ji(e){let t=wi(e),n=Oi(e);return Object.freeze({...Te({unsupported:Ai(e),read:t,write:t}),...je({read:n,wait:n,accept:n,dismiss:n}),...Ce({triggerAppEvent:ki(e)}),...De({setSetting:Ci(e,bi,xi)})})}function Mi(e){let{host:t,device:n,signal:r}=e;return ct({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:ji(n)})}function Ni(e,t,n){let r=Fe({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(s(t.device)&&i.options?.surface!==void 0&&i.options.surface!==`app`)return await e.snapshot.captureSurface(t.device,i.options,Se(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=Se(t.signal,i);return await n.capture(t.device,i,a,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function Pi(e,t){return Object.freeze({findText:async n=>{let r=await Fi(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 Fi(e,t,n){let r=n.options?.appBundleId;if(r===void 0)return;let i=n.options?.surface;if(s(t.device)&&i!==void 0&&i!==`app`)return;let a=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(a.throwIfAborted(),await Ii(e,t.device,n.execution))return{appBundleId:r,signal:a}}async function Ii(e,t,n){return!M(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Li(){let e,t=!1,n=async()=>(e??=import(`./adapter.js`).then(({createSimulatorSnapshotSource:e})=>e()),await e);return{acquire:async e=>t?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await n()).acquire(e),close:async()=>{t=!0,e&&await(await e).close()}}}const Ri=3e3;function zi(){let e=new Map,t=new Map,n=Tt({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);return c&&o!==`refresh`&&await Dt(c.pid,{signal:a,timeoutMs:Ri})===c.processStartTime?c:(e.delete(s),await n.value(s,{start:async()=>{let n=await Bi(r,i,t);return e.set(s,n),n},wait:(e,t)=>Et({waitMs:e,signal:a,stop:t,cancelled:()=>a.reason}),pending:()=>H(`simulator-target-discovery-pending`,r,i)}))}}async function Bi(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([xt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:V(r)}),Vi(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 H(`simulator-target-probe-failed`,e,t);let c=Hi(o.stdout,t);if(!c)throw H(`simulator-target-unavailable`,e,t);let l=await Dt(c.pid,{timeoutMs:Math.min(Ri,V(r))});if(!l)throw H(`simulator-target-identity-unavailable`,e,t);return Object.freeze({udid:e.id,runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Vi(e,t,n){let r=t.get(e.id);if(r)return await r;let i=xt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:V(n)}).then(t=>{if(t.exitCode!==0)throw H(`simulator-runtime-probe-failed`,e,``);let n=JSON.parse(t.stdout),r=Object.entries(n.devices??{}).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!r)throw H(`simulator-runtime-unavailable`,e,``);return r});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Hi(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 V(e){return Math.max(1,e-Date.now())}function H(t,n,r){return new e(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${t}).`,{reason:t,deviceId:n.id,appBundleId:r})}function Ui(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 Wi(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function Wi(e,t){let n=!1;for(let r of at){let i=await Gi(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await Ki(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function Gi(e,t){let n=await qi(`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 Ki(e,t,n){let r=await qi(`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 qi(e,t,n){try{let r=await bt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Ji=`system-surface-presented`,Yi=`system-surface-host-lingering`;function Xi(t,n={}){let r=n.source??Li(),i=n.resolveTarget??zi(),a=n.systemSurfacePresent??Ui(),o=new Set,s=new Map,c=e=>(sa(e,s,o),o.has(ca(e))),l=gr({source:r,resolveTarget:i,clock:t.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(n,s,l,u)=>{if(!$i(n,s))return await na(n,s,u);let d=await a(n,l);if(d===`unknown`)return await U(n.id,s,u,W(n.id,s),q(s),`system-surface-probe-unavailable`,[K()]);if(d!==`absent`)return await ta(n,s,u,d.host.bundleId);let p;try{p=await Zi(t,i,n,s,l)}catch(e){return l.throwIfAborted(),J(`target-resolution-failed`,n,void 0,e),await U(n.id,s,u,W(n.id,s),q(s),`target-resolution-failed`,[K()])}if(c(p))return await U(n.id,s,u,p,q(s),`circuit-disabled`);let m=q(s),h=await r.acquire({target:p,hint:ee(m),signal:l});if(h.stage===`failed`){if(h.failure.kind===`cancelled`)throw l.throwIfAborted(),new e(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:h.failure.code,...h.failure.details});let t=await oa(h.failure,p,n,s.options.appBundleId,l,i);return await ea(s,u,p,t,m,h.failure,o)}try{return await f(`ios.snapshot-source.present`,async()=>await t.snapshot.presentIosAcquisition(h,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await ea(s,u,p,{lineage:p,residue:[]},m,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Zi(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!Qi(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function Qi(t){return t instanceof e&&t.details?.reason===`simulator-target-discovery-pending`}function $i(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 ea(e,t,n,r,i,a,o,s){return a.kind!==`preparing`&&o.add(ca(n)),J(a.code,{id:n.udid},n.generation,s,a.details),await U(n.udid,e,t,r.lineage,i,a.code,r.residue)}async function U(e,t,n,r,i,a,o=[]){return ra(e,await n(t),r,i,a,o)}async function ta(e,t,n,r){let i=await n(t),a=i.systemSurface?Ji:Yi;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),ra(e.id,i,W(e.id,t),q(t),a)}async function na(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:ia(G(e.id,i.bundleId),q(t),[])}:r}function ra(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:ia(o?G(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],aa(i,n,o!==void 0)]}}function W(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function G(e,t){return{targetId:`${e}:${t}`}}function ia(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:te(t),residue:Object.freeze([...n])})}function aa(e,t,n){return e===Ji?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Yi?`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.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function oa(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:[K()]}}}function K(){return{kind:`unknown-generation`,captureId:kt()}}function q(e){return ne({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 sa(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 ca(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){p({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=l(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),la=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`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.`}),ua=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`}),da=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),fa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),pa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate reads the active session state; a sessionless runtime foreground probe is unavailable.`}),ma=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),ha=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),ga=Object.freeze({available:!1,reason:`unsupported-device-kind`}),_a=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),va=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),ya=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),xa=Q(`open is supported only for Apple simulators and devices.`),Sa=Q(`prepare is supported only for Apple simulators and devices.`),Ca=Q(`close is supported only for Apple simulators and devices.`),wa=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),Ta=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Ea=Q(`snapshot is supported only for Apple simulators and devices.`),Da=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Oa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),ka=Q(`screenshot is supported only for Apple simulators and devices.`),Aa=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Open the app under test before capturing its snapshot.`});function Q(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function ja(e){return!o(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:Ta}function Ma(e){let t=Na(e),n=Pa(e),r=Fa(e),i=Ia(e);return oe({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:wa})}function Na(e){return r(e)===`watchos`?_a:e.kind===`simulator`||e.kind===`device`?X:xa}function Pa(e){return r(e)===`watchos`?va:e.kind===`simulator`||e.kind===`device`?X:Sa}function Fa(e){return r(e)===`watchos`?ya:e.kind===`simulator`||e.kind===`device`?X:Ca}function Ia(e){return r(e)!==`watchos`&&o(e)&&e.kind===`simulator`?X:ba}function La(e){return e.appleOs===`watchos`?Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app inventory is not supported.`}):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`App inventory is available only on CoreDevice-backed physical iOS devices.`}):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:fa}function Ra(e){let t=hn(e),n=Xi(e),r=async n=>{let r=await t.inspectFacts(n),i=Wr(n),a=Kn(n),c=a.available?await e.screenRecording.apple.availability(n):void 0,l=a.available&&c?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:c.hint}):a,u=n.appleOs===`watchos`?Z:X,d=s(n)||n.appleOs===`watchos`?Z:X,f=La(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:pa,networkDump:X,screenRecordingStart:l,screenRecordingReattach:l,screenRecordingCleanup:l,...Ua(n),...fe({capture:Ha(n)}),...ye({findText:Va(n)}),...he({setViewport:la}),...me({focus:$(n)}),...Rt(n),...de({type:$(n)}),...se({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...o(n)?{tapElementSelector:$(n)}:{}}),...Ne({readTextAtPoint:Ba(n)}),..._i(n),...ji(n),...Ie({capture:jt(n),query:ua}),...Le(za(n)),ensureReady:u,bootTarget:d,bootTargetHeadless:ma,listApps:f,...Ma(n),shutdownTarget:ja(n)}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:r,bind:async i=>{let a=await t.bind(i),o=await r(i.device),s=o.operations.screenRecordingStart,c={...a.operations,...Gr({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await yn(e,i.device,t,i.scope.signal),...d(s,()=>qn({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...d(o.operations.audioProbeStart,()=>Ke({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...d(o.operations.perfFrames,()=>Mt({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...d(o.operations.captureSnapshot,()=>Ni(e,{device:i.device,signal:i.scope.signal},n)),...d(o.operations.captureScreenshot,()=>xe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.focusPoint,()=>ve({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...Oe({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...d(o.operations.scrollDirection,()=>_e({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.typeText,()=>be({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.tapPoint,()=>ce({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)})),...d(o.operations.readTextAtPoint,()=>ue({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.findText,()=>Pi(e,{device:i.device,signal:i.scope.signal})),...vi({host:e,device:i.device,signal:i.scope.signal}),...Mi({host:e,device:i.device,signal:i.scope.signal}),...d(o.operations.ensureReady,()=>({ensureReady:async()=>await k(e,i.device,i.scope.signal)})),...d(o.operations.bootTarget,()=>({bootTarget:async()=>await k(e,i.device,i.scope.signal)})),...d(o.operations.listApps,()=>({listApps:async e=>{i.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}))}})),...ie(br({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...d(o.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(i.device,i.scope.signal)}))};return Object.freeze({device:a.device,owner:Y,facts:o,operations:At(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function za(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&r(e)!==`watchos`?X:da;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Ba(e){return r(e)===`watchos`?ha:e.kind===`simulator`||e.kind===`device`?X:ga}function Va(e){return r(e)===`watchos`?Ea:e.kind===`simulator`||e.kind===`device`?X:Ea}function Ha(e){return r(e)===`watchos`?Oa:e.kind===`simulator`||e.kind===`device`?X:ka}function Ua(e){let t=Va(e);return pe({capture:t,customActions:t.available&&o(e)&&e.kind===`simulator`?X:Da,withoutActiveApp:o(e)?Aa:t})}export{Ra as createApplePlatformRuntime};