agent-device 0.21.19 → 0.21.20

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 (114) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.19.apk → agent-device-android-ime-helper-0.21.20.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.20.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.19.manifest.json → agent-device-android-ime-helper-0.21.20.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.19.apk → agent-device-android-snapshot-helper-0.21.20.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.20.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.19.manifest.json → agent-device-android-snapshot-helper-0.21.20.manifest.json} +6 -6
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +12 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -14
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +14 -16
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +40 -14
  11. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -5
  12. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +2 -15
  13. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +10 -25
  14. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFoldProjection.swift +1 -18
  15. package/dist/src/adapter.js +1 -1
  16. package/dist/src/adb-failure.js +1 -1
  17. package/dist/src/agent-browser-process-record.js +1 -1
  18. package/dist/src/agent-browser-provider.js +1 -1
  19. package/dist/src/agent-browser-tool.js +1 -1
  20. package/dist/src/agent-device-client.js +2 -2
  21. package/dist/src/alert-runtime.js +1 -1
  22. package/dist/src/alert.js +1 -0
  23. package/dist/src/android-input-ownership.js +1 -1
  24. package/dist/src/app-launch.js +2 -2
  25. package/dist/src/app-lifecycle.js +1 -1
  26. package/dist/src/app-resolution.js +2 -2
  27. package/dist/src/apple-runner-platform.js +1 -1
  28. package/dist/src/archive.js +2 -2
  29. package/dist/src/browser-launch.js +1 -1
  30. package/dist/src/cache.js +1 -1
  31. package/dist/src/cli-config.js +1 -1
  32. package/dist/src/cli-help.js +287 -301
  33. package/dist/src/cli-runner.js +1 -1
  34. package/dist/src/cli.js +1 -1
  35. package/dist/src/client-metro-companion.js +1 -1
  36. package/dist/src/client-metro.js +1 -1
  37. package/dist/src/client-types.d.ts +14 -2
  38. package/dist/src/{scroll-command.d.ts → cloud-artifacts.d.ts} +242 -238
  39. package/dist/src/command-schema.js +3 -3
  40. package/dist/src/command-tools.js +2 -2
  41. package/dist/src/command.js +1 -1
  42. package/dist/src/config.js +1 -1
  43. package/dist/src/connection-runtime.js +1 -1
  44. package/dist/src/daemon-client-lifecycle.js +1 -1
  45. package/dist/src/daemon-client-transport.js +1 -1
  46. package/dist/src/daemon-registration.js +1 -1
  47. package/dist/src/debug-symbols-facade.js +3 -3
  48. package/dist/src/device-rotation.js +1 -1
  49. package/dist/src/devicectl.js +1 -1
  50. package/dist/src/display-inventory.js +1 -1
  51. package/dist/src/exec.js +1 -1
  52. package/dist/src/hdc.js +1 -1
  53. package/dist/src/helper.js +2 -2
  54. package/dist/src/host.js +1 -1
  55. package/dist/src/index.d.ts +1 -1
  56. package/dist/src/interactor.js +5 -5
  57. package/dist/src/interactor2.js +1 -1
  58. package/dist/src/internal/bin.js +1 -1
  59. package/dist/src/internal/daemon.js +2 -2
  60. package/dist/src/launch-confirmation.js +1 -0
  61. package/dist/src/limrun-runtime-dependencies.js +1 -1
  62. package/dist/src/limrun.d.ts +50 -42
  63. package/dist/src/mechanics.js +16 -16
  64. package/dist/src/owner-identity.js +1 -1
  65. package/dist/src/perf-facade.js +1 -1
  66. package/dist/src/perf-target.js +1 -1
  67. package/dist/src/physical-device-control.js +1 -1
  68. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  69. package/dist/src/platform-runtime-app-log-process.js +1 -1
  70. package/dist/src/platform-runtime-host.js +1 -1
  71. package/dist/src/platform-runtime-operation-host.js +2 -2
  72. package/dist/src/platform-runtime-runtime-hints.js +1 -1
  73. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  74. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  75. package/dist/src/provider-session-ownership.js +1 -1
  76. package/dist/src/provider-webdriver.js +1 -1
  77. package/dist/src/registry.js +20 -4
  78. package/dist/src/result-serialization.js +1 -1
  79. package/dist/src/runner-cache-metadata.js +3 -3
  80. package/dist/src/runner-client.js +1 -1
  81. package/dist/src/runner-dev-tools-security.js +1 -1
  82. package/dist/src/runner-device-readiness.js +1 -1
  83. package/dist/src/runner-disposal.js +1 -1
  84. package/dist/src/runner-error-classification.js +1 -1
  85. package/dist/src/runner-exchange.js +1 -1
  86. package/dist/src/runner-operations-facade.js +1 -1
  87. package/dist/src/runner-session-types.js +1 -1
  88. package/dist/src/runner-start-budget.js +1 -1
  89. package/dist/src/runner-startup-transport.js +1 -1
  90. package/dist/src/runner-xctestrun.js +1 -1
  91. package/dist/src/runtime.js +1 -1
  92. package/dist/src/runtime10.js +1 -1
  93. package/dist/src/runtime2.js +1 -1
  94. package/dist/src/runtime4.js +5 -5
  95. package/dist/src/screenshot-result.js +1 -1
  96. package/dist/src/screenshot-runtime.js +1 -1
  97. package/dist/src/screenshot3.js +1 -1
  98. package/dist/src/sdk-contracts.d.ts +2 -0
  99. package/dist/src/sdk-contracts.js +2 -2
  100. package/dist/src/sdk-selectors.d.ts +4 -4
  101. package/dist/src/session2.js +1 -1
  102. package/dist/src/simulator-boot.js +1 -1
  103. package/dist/src/simulator.js +1 -1
  104. package/dist/src/snapshot-runtime.js +1 -1
  105. package/dist/src/tool-provider.js +3 -3
  106. package/dist/src/tool-provider2.js +1 -1
  107. package/dist/src/tool-provider3.js +1 -1
  108. package/dist/src/toolchain-probe.js +1 -1
  109. package/dist/src/update-check.js +1 -1
  110. package/dist/src/video.js +1 -1
  111. package/package.json +1 -1
  112. package/server.json +2 -2
  113. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.19.apk.sha256 +0 -1
  114. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.19.apk.sha256 +0 -1
@@ -1,5 +1,5 @@
1
1
  import{N as e,q as t}from"./sdk-contracts.js";import{i as n}from"./sdk-batch-runner.js";import{A as r}from"./sdk-device.js";import{Xt as i,nn as a}from"./sdk-batch.js";import{n as o}from"./device-shell.js";import{n as s,t as c}from"./android-snapshot-quality.js";import{i as l,n as u}from"./recording-stop-observation.js";import{n as d,r as f,t as p}from"./application-lifecycle-runtime.js";import{A as m,B as h,C as g,D as ee,G as te,H as ne,I as re,J as ie,N as ae,V as oe,d as se,h as ce,n as le,o as ue,s as de,v as fe,w as pe,x as me,z as he}from"./alert-runtime.js";import{n as ge}from"./audio-probe-runtime.js";import{n as _e}from"./perf-runtime.js";import{i as ve}from"./touch-runtime.js";import{a as ye,n as be}from"./durable-resource.js";import{n as xe}from"./async-lifecycle.js";import{i as Se,l as Ce,n as we,r as Te,t as Ee}from"./src7.js";import{n as De}from"./screen-recording-completion.js";import{a as _,c as Oe,n as ke,o as Ae,s as je,t as Me}from"./device-readiness-runtime.js";import{n as Ne}from"./screen-recording-runtime.js";import{readAndroidAppStateWithExecutor as Pe}from"./app-state.js";import{ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_HINT as Fe}from"./clipboard-shell-response.js";import{i as Ie,t as Le}from"./gesture-admission.js";import{t as Re}from"./local-interactor-operation-set.js";import{a as ze,i as v,n as y,r as Be,t as Ve}from"./perf-runtime-operation-builder.js";import{t as He}from"./app-log-runtime.js";import{t as Ue}from"./mp4-duration.js";import{n as b,r as We}from"./managed-device-scope.js";import{a as Ge,i as Ke,n as qe,o as Je}from"./application-lifecycle-interaction.js";import x from"node:path";function Ye(e){return Ae(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 Xe(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Ve({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 v(t().sampleFrames(n,e)):y(`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 v(t().sampleMemory(n,e)):y(`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=Ze();if(o!==`android-hprof`)return ze(`Android`,o,s,`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`);if(!e)throw Be();let c=i??x.join(a,`memory-android-hprof-${Qe()}.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 Ze(){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 Qe(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function $e(t){if(!/^[a-zA-Z0-9._:-]+$/.test(t))throw new e(`INVALID_ARGS`,`Invalid Android package name for logs: ${t}`)}const S=Object.freeze({resourceKind:He,version:1,encode:e=>({...e}),decode:e=>e.transport!==`android-logcat-local`&&e.transport!==`android-logcat-transport-composed`||!tt(e.outputPath)||!tt(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 et(e){let t=S.decode(e.descriptor);if(t.status!==`decoded`)throw TypeError(t.message);return be({resourceKind:He,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:ye(S,t.descriptor)})}function tt(e){return typeof e==`string`&&e.trim().length>0}function nt(e){return Te(e,{family:`android`,backend:`android`,label:`Android`,codec:S,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 rt(e,t.id,r,n),validateStart:({input:e})=>$e(e.appBundleId),process:async({host:e,device:t,input:n})=>({resolvePid:async r=>await Se(e,it(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})=>et({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function rt(e,t,n,r){let i={};return i.adbAvailable=await Oe(async()=>je(await e.commands.run({executable:`adb`,args:o(`adb`,`shell`,[`echo`,`ok`],[`-s`,t]),allowFailure:!0,timeoutMs:1e3},r)),r),n&&(i.androidPidVisible=await Oe(async()=>!!await Se(e,it(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 it(e,t){return{executable:`adb`,args:o(`adb`,`shell`,[`pidof`,t],[`-s`,e]),allowFailure:!0,timeoutMs:5e3}}async function at(e,t,n,r){let i=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),a=we(i.text,{...n,path:i.path,exists:i.exists,lineNumberOffset:i.skippedLines,backend:`android`}),o=[],s=await st(e,t,n,r);if(s&&n.appBundleId){$e(n.appBundleId);let c=await lt(e,t,n.appBundleId,r);if(c){let e=we(c.text,{...n,path:`${i.path} (adb logcat recovery)`,exists:!0,backend:`android`});e.dump.entries.length>0&&(a=Ee(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 ot(e,t,n){n.throwIfAborted();try{let r=await e.commands.run(t,n);return n.throwIfAborted(),r}catch{n.throwIfAborted();return}}async function st(e,t,n,r){if(!n.appBundleId||n.appLogSnapshot?.state===void 0)return;if(n.appLogSnapshot.state!==`active`)return{reason:`inactive`};let i=ct(await e.appLogs.readProcessMarker(n.sessionId));if(!i)return;let a=await ut(e,t.id,n.appBundleId,r);if(!(!a||a===i))return{reason:`stale-active`,trackedPid:i}}function ct(e){if(e.status===`decoded`)return/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(e.marker.command)?.[1]}async function lt(e,t,n,r){let i=await ut(e,t.id,n,r),a=await ot(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=dt(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
3
  `);return c.trim()?{text:c,pids:o}:void 0}async function ut(e,t,n,r){let i=await ot(e,{executable:`adb`,args:o(`adb`,`shell`,[`pidof`,n],[`-s`,t]),allowFailure:!0},r);if(!i)return;let a=i.stdout.trim().split(/\s+/)[0];return a&&/^\d+$/.test(a)?a:void 0}function dt(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 C(e,t){if(t===1)return e;let n=x.parse(e);return x.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const ft=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,pt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function mt(e){return _t(e)&&vt(e)&&yt(e)}function ht(e){if(!w(e))return!1;let t=e;return bt(t)&&xt(t)&&St(t)&&Ct(t)&&(t.completion===void 0||At(t))}function gt(e,t){return jt(e,t)&&Mt(e,t.outputPath,t.clientOutputPath)}function _t(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&pt.test(e.manifestPath)&&typeof e.outputPath==`string`}function vt(e){return Pt(e.clientOutputPath)&&_(e)}function yt(e){return Nt(e.transportMode)}function bt(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 xt(e){return typeof e.outputPath==`string`&&Pt(e.clientOutputPath)&&_(e)}function St(e){return Nt(e.transportMode)&&(e.pendingRemotePath===void 0||Ft(e.pendingRemotePath))}function Ct(e){return Array.isArray(e.chunks)&&e.chunks.every(wt)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||Tt(e.completion))}function wt(e,t){if(!w(e))return!1;let n=e;return n.index===t+1&&Ft(n.remotePath)&&It(n.remotePid)&&It(n.remoteStartTime)}function Tt(e){if(!w(e))return!1;let t=e;return Dt(t)&&Ot(t)&&Et(t)&&(t.chunks===void 0||t.chunks.every(kt))}function Et(e){return(e.stopObservation===void 0||u(e.stopObservation))&&(e.nativePathDisposition===void 0||l(e.nativePathDisposition))}function Dt(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 Ot(e){return _(e)}function kt(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function At(e){let t=e.completion;return t!==void 0&&jt(t,e)&&t.startedAt===e.startedAt&&Mt(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function jt(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&&Lt(e.activeSessionApp,t.activeSessionApp)}function Mt(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===C(t,r+1)&&e.clientOutPath===(n===void 0?void 0:C(n,r+1)))}function w(e){return typeof e==`object`&&!!e}function Nt(e){return e===`local`||e===`transport-composed`}function Pt(e){return e===void 0||typeof e==`string`}function Ft(e){return typeof e==`string`&&ft.test(e)}function It(e){return typeof e==`string`&&/^\d+$/.test(e)}function Lt(e,t){return JSON.stringify(e)===JSON.stringify(t)}const T=Object.freeze({resourceKind:Ne,version:1,encode:e=>({...e}),decode:e=>mt(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 Rt(e,t){return Object.freeze({...e,completion:t})}function D(e){try{let t=e&&JSON.parse(e);return ht(t)?t:void 0}catch{return}}function zt(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 Bt(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||gt(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 Vt(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const Ht=1e4,k=1e3;var A=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}};function j(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 Ut(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 Yt(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&&Wt(i)&&!await Xt(e,i)?new A(t):r?.aborted?r.reason:t}}function Wt(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function M(e,t){let n=t.at(-1),r=!1,i;for(let a of[...t].reverse())try{let t=await P(e,a);a===n&&(r=t)}catch(e){i??=e}if(i)throw i;return r}async function Gt(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 Kt(e,t,n){for(let[r,i]of t.entries())await Zt(e,i.remotePath,C(n,r+1))}async function N(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 qt(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function Jt(e,t){try{await M(e,t)}finally{await N(e,t)}}async function Yt(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 Xt(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 P(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 Qt(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 Zt(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 $t(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function Qt(e,t){for(let n=0;n<=Ht;n+=k){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<Ht&&await $t(k)}return!1}function $t(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 en(e,t){let n=(await tn(e)).flatMap(n=>nn(n,t,e.mode));for(let t of n)await an(e,t.evidence,t.manifestPath)}async function tn(e){return await Promise.all(j(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function nn(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw cn(e.manifestPath,e.read.message);let r=D(e.read.contents);if(r===void 0)throw ln(e.manifestPath);if(r.transportMode!==n)throw un(e.manifestPath,r,n);if(!rn(r,t))throw dn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function rn(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function an(e,t,n){if(await on(e,t),await N(e,t.chunks),await sn(e,t),await I(e,n),(await e.readManifest(n)).status!==`missing`)throw mn(n)}async function on(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!Vt(t))throw t===`uncertain`?hn(n.remotePath):fn(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 fn(n,`other-recorder`);if(!r.conclusive)throw hn(n)}async function sn(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw pn(n)}function cn(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 ln(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 un(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 dn(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 fn(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 pn(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 mn(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 hn(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 gn(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await en(t,n),await o();let s;for(let e of j(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 Ut(t,e,r,a)}catch(e){if(a.aborted)throw await _n(t,o,e),a.reason;await bn(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 vn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function _n(e,t,n){n instanceof A||await I(e,t).catch(()=>{})}async function vn(e,t,n){try{await Jt(e,[n])}catch{return}await I(e,t).catch(()=>{})}async function yn(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s}=e,c;for(let e of j(s)){await F(t,o,E(n,r,i,a,e,t.mode));try{return await Ut(t,e,r)}catch(e){if(e instanceof A)throw e;try{await F(t,o,E(n,r,i,a,void 0,t.mode))}catch{throw new A(e)}c=e}}throw c??Error(`failed to start next Android recording chunk`)}async function bn(e,t,n){if(n instanceof A)throw n;try{await I(e,t)}catch{throw new A(n)}}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:[]})}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=Ue(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 ke({snapshot:i,progress:o,steps:{stop:async()=>(s=await M(n,r.chunks)||s,await Gt(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=>Kt(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(C(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,Rt(r,t.result)),await N(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await qt(n,r.chunks)}}}function jn(e){return Object.freeze(Array.from({length:e.count},(t,n)=>({collected:Object.freeze({index:n+1,path:C(e.collectedPath,n+1)}),served:Object.freeze({index:n+1,path:C(e.exportPath,n+1),...e.exportClientPath===void 0?{}:{clientOutPath:C(e.exportClientPath,n+1)}})})))}async function Mn(e,t,n){try{let r=t.pendingRemotePath;if(await M(e,[...t.chunks,...await Nn(e,t)]),await N(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&&zt(o,n,r)&&Bt(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:De(xn(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 qt(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:t,transport:n,device:i,owner:a,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await gn({transport:n,device:i,input:o,startedAt:c,signal:s,prepareOutput:async()=>await t.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,r;try{r=await yn({transport:n,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:x.posix.dirname(e.remotePath)})}catch(a){await P(n,e),t=!0;try{r=await yn({transport:n,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:x.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:a}}let a=[...d,{...r,index:d.length+1}];try{await F(n,u,E(i,o,c,a,void 0,n.mode))}catch(a){if(await Jt(n,[r]).catch(()=>{}),t)await F(n,u,E(i,o,c,d,r.remotePath,n.mode)).catch(()=>{});else try{await F(n,u,E(i,o,c,d,void 0,n.mode))}catch{await P(n,e).catch(()=>{}),await F(n,u,E(i,o,c,d,r.remotePath,n.mode)).catch(()=>{})}throw a}d=a,t||await P(n,e),g()};g();let te=De(xn(o,c),{finish:async(e,r)=>{if(f&&clearTimeout(f),await p,m)throw m;let a=await Tn({host:t,transport:n,evidence:E(i,o,c,d,void 0,n.mode),manifestPath:u,recording:e,startedAtMs:l.startedAtMs,progress:r});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:n,deviceId:i.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await Mn(n,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new xe(te),envelope:be({resourceKind:Ne,sessionId:o.sessionId,device:r(i),owner:a,fence:o.fence,lifecycle:`open`,descriptor:ye(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:n.mode})})})}const Gn=1e3;async function z(e,t,n,r){return r.throwIfAborted(),await We(t)?{...t,booted:!0}:t.kind===`emulator`&&(t.booted!==!0||!B(t))?await Kn(e,t,n,r):(t.booted!==!0&&await Xn(e,t.id,Qn(e,n),r),{...t,booted:!0})}async function Kn(e,t,n,r){await qn(e);let i=$n(n),a=Qn(e,n),o=Jn(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),s=B(o)?o:void 0,c=s?void 0:e.deviceReadiness.androidEmulator.launch(o.name,n.headless);try{let t=s??await Yn(e,o.name,i,n.serial,a,r);return await Xn(e,t.id,a,r),{...(await e.deviceReadiness.androidEmulator.discover(i,r)).find(e=>e.id===t.id)??t,name:o.name,booted:!0}}catch(t){throw c!==void 0&&r.aborted&&await e.deviceReadiness.androidEmulator.terminate(c),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=er(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(e,t,n,r,i,a){for(;e.clock.now()<i;){let i=er(await e.deviceReadiness.androidEmulator.discover(n,a),t,r);if(i&&B(i))return i;await e.clock.sleep(Gn,a)}throw Zn(`Android emulator did not appear in time`,{avdName:t,serial:r})}async function Xn(e,t,n,r){for(;e.clock.now()<n;){if((await e.commands.run({executable:`adb`,args:o(`adb`,`shell`,[`getprop`,`sys.boot_completed`],[`-s`,t]),allowFailure:!0,timeoutMs:Math.min(1e4,Math.max(1e3,n-e.clock.now()))},r)).stdout.trim()===`1`)return;await e.clock.sleep(Gn,r)}throw Zn(`Android device failed to finish booting`,{serial:t})}function Zn(t,n){return new e(`COMMAND_FAILED`,t,{...n,reason:Me,hint:`The emulator keeps booting in the background. Retry once it is up, or pass a larger --timeout.`})}function Qn(e,t){return t.deadlineAtMs??e.clock.now()+12e4}function $n(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function er(e,t,n){let r=tr(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&tr(e.name)===r&&(!n||!B(e)||e.id===n))}function B(e){return e.id.startsWith(`emulator-`)}function tr(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}async function nr(e,t,n){try{let r=await e.snapshot({appBundleId:t,signal:n,transient:{settleBy:Date.now()+6e3}});return{observation:`androidSnapshot`in r&&r.androidSnapshot?.systemSurfaceOnly===!0?`unobservable`:`observable`}}catch(e){return n.throwIfAborted(),c(e)?{observation:`unobservable`}:{observation:`probe-failed`,failure:rr(e)}}}function rr(e){let n=t(e),r=s(n)??n.details?.reason;return typeof r==`string`?{code:n.code,reason:r}:{code:n.code}}function ir(e){let{host:t,device:n,signal:r}=e,i=qe({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,deadlineAtMs:e.execution.startupDeadlineAtMs},r)},openApplication:async e=>await ar(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 Ge({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:sr,configureProviderPortReverse:sr})}async function ar(t,n,r){let i={};if(r.relaunch&&r.target){let e=Date.now();await Ge({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:[r.appBundleId??r.target]}),i.relaunchCloseDurationMs=V(e)}if(f(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 a=Date.now();await Je({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution}),i.openDispatchDurationMs=V(a),r.enableTestIme&&await t.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let o=Ke(r);if(o){let e=Date.now();await Je({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=V(e)}else i.launchUrlDurationMs=0;let s=await t.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId);s&&await t.androidApplications.resetFramePerfStats(n.device,s);let c=Date.now();return Object.assign(i,await or(n,r,s)),i.postOpenSettleDurationMs=V(c),{appBundleId:s,timing:i}}async function or(e,t,r){if(!t.target||n(t.target))return{};if(!r)return{postOpenObservation:`app-unidentified`};let i=await nr(await e.resolveInteractor(t.execution,r),r,e.signal);return i.observation===`probe-failed`?{postOpenObservation:`probe-failed`,postOpenObservationFailure:i.failure}:{postOpenObservation:i.observation}}function V(e){return Math.max(0,Date.now()-e)}async function sr(){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 W(e,t,i);if(x.extname(n).toLowerCase()===`.aab`?await dr(e,t,n,i):K(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await W(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}function U(t){if(b()&&x.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 cr(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 lr(t,n,r,i){let a=r.payload,s=typeof a.action==`string`&&a.action.trim()?a.action.trim():`${r.appId}.TEST_PUSH`,c=[`am`,`broadcast`,`-a`,s,`-p`,r.appId];typeof a.receiver==`string`&&a.receiver.trim()&&c.push(`-n`,a.receiver.trim());let l=a.extras??{};if(typeof l!=`object`||!l||Array.isArray(l))throw new e(`INVALID_ARGS`,`Android push payload extras must be an object`);let u=0;for(let[e,t]of Object.entries(l))e&&(fr(c,e,t),u+=1);return K(await G(t,n,o(`adb`,`shell`,c),i),`adb push broadcast failed`),{action:s,extrasCount:u}}function ur(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 dr(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 W(e,t,n){let r=await G(e,t,o(`adb`,`shell`,[`pm`,`list`,`packages`]),n);return K(r,`adb package inventory failed`),new Set(r.stdout.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 C(e,t){if(t===1)return e;let n=x.parse(e);return x.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const ft=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,pt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function mt(e){return _t(e)&&vt(e)&&yt(e)}function ht(e){if(!w(e))return!1;let t=e;return bt(t)&&xt(t)&&St(t)&&Ct(t)&&(t.completion===void 0||At(t))}function gt(e,t){return jt(e,t)&&Mt(e,t.outputPath,t.clientOutputPath)}function _t(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&pt.test(e.manifestPath)&&typeof e.outputPath==`string`}function vt(e){return Pt(e.clientOutputPath)&&_(e)}function yt(e){return Nt(e.transportMode)}function bt(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 xt(e){return typeof e.outputPath==`string`&&Pt(e.clientOutputPath)&&_(e)}function St(e){return Nt(e.transportMode)&&(e.pendingRemotePath===void 0||Ft(e.pendingRemotePath))}function Ct(e){return Array.isArray(e.chunks)&&e.chunks.every(wt)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||Tt(e.completion))}function wt(e,t){if(!w(e))return!1;let n=e;return n.index===t+1&&Ft(n.remotePath)&&It(n.remotePid)&&It(n.remoteStartTime)}function Tt(e){if(!w(e))return!1;let t=e;return Dt(t)&&Ot(t)&&Et(t)&&(t.chunks===void 0||t.chunks.every(kt))}function Et(e){return(e.stopObservation===void 0||u(e.stopObservation))&&(e.nativePathDisposition===void 0||l(e.nativePathDisposition))}function Dt(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 Ot(e){return _(e)}function kt(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function At(e){let t=e.completion;return t!==void 0&&jt(t,e)&&t.startedAt===e.startedAt&&Mt(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function jt(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&&Lt(e.activeSessionApp,t.activeSessionApp)}function Mt(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===C(t,r+1)&&e.clientOutPath===(n===void 0?void 0:C(n,r+1)))}function w(e){return typeof e==`object`&&!!e}function Nt(e){return e===`local`||e===`transport-composed`}function Pt(e){return e===void 0||typeof e==`string`}function Ft(e){return typeof e==`string`&&ft.test(e)}function It(e){return typeof e==`string`&&/^\d+$/.test(e)}function Lt(e,t){return JSON.stringify(e)===JSON.stringify(t)}const T=Object.freeze({resourceKind:Ne,version:1,encode:e=>({...e}),decode:e=>mt(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 Rt(e,t){return Object.freeze({...e,completion:t})}function D(e){try{let t=e&&JSON.parse(e);return ht(t)?t:void 0}catch{return}}function zt(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 Bt(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||gt(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 Vt(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const Ht=1e4,k=1e3;var A=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}};function j(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 Ut(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 Yt(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&&Wt(i)&&!await Xt(e,i)?new A(t):r?.aborted?r.reason:t}}function Wt(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function M(e,t){let n=t.at(-1),r=!1,i;for(let a of[...t].reverse())try{let t=await P(e,a);a===n&&(r=t)}catch(e){i??=e}if(i)throw i;return r}async function Gt(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 Kt(e,t,n){for(let[r,i]of t.entries())await Zt(e,i.remotePath,C(n,r+1))}async function N(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 qt(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function Jt(e,t){try{await M(e,t)}finally{await N(e,t)}}async function Yt(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 Xt(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 P(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 Qt(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 Zt(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 $t(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function Qt(e,t){for(let n=0;n<=Ht;n+=k){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<Ht&&await $t(k)}return!1}function $t(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 en(e,t){let n=(await tn(e)).flatMap(n=>nn(n,t,e.mode));for(let t of n)await an(e,t.evidence,t.manifestPath)}async function tn(e){return await Promise.all(j(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function nn(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw cn(e.manifestPath,e.read.message);let r=D(e.read.contents);if(r===void 0)throw ln(e.manifestPath);if(r.transportMode!==n)throw un(e.manifestPath,r,n);if(!rn(r,t))throw dn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function rn(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function an(e,t,n){if(await on(e,t),await N(e,t.chunks),await sn(e,t),await I(e,n),(await e.readManifest(n)).status!==`missing`)throw mn(n)}async function on(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!Vt(t))throw t===`uncertain`?hn(n.remotePath):fn(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 fn(n,`other-recorder`);if(!r.conclusive)throw hn(n)}async function sn(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw pn(n)}function cn(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 ln(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 un(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 dn(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 fn(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 pn(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 mn(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 hn(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 gn(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await en(t,n),await o();let s;for(let e of j(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 Ut(t,e,r,a)}catch(e){if(a.aborted)throw await _n(t,o,e),a.reason;await bn(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 vn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function _n(e,t,n){n instanceof A||await I(e,t).catch(()=>{})}async function vn(e,t,n){try{await Jt(e,[n])}catch{return}await I(e,t).catch(()=>{})}async function yn(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s}=e,c;for(let e of j(s)){await F(t,o,E(n,r,i,a,e,t.mode));try{return await Ut(t,e,r)}catch(e){if(e instanceof A)throw e;try{await F(t,o,E(n,r,i,a,void 0,t.mode))}catch{throw new A(e)}c=e}}throw c??Error(`failed to start next Android recording chunk`)}async function bn(e,t,n){if(n instanceof A)throw n;try{await I(e,t)}catch{throw new A(n)}}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:[]})}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=Ue(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 ke({snapshot:i,progress:o,steps:{stop:async()=>(s=await M(n,r.chunks)||s,await Gt(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=>Kt(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(C(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,Rt(r,t.result)),await N(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await qt(n,r.chunks)}}}function jn(e){return Object.freeze(Array.from({length:e.count},(t,n)=>({collected:Object.freeze({index:n+1,path:C(e.collectedPath,n+1)}),served:Object.freeze({index:n+1,path:C(e.exportPath,n+1),...e.exportClientPath===void 0?{}:{clientOutPath:C(e.exportClientPath,n+1)}})})))}async function Mn(e,t,n){try{let r=t.pendingRemotePath;if(await M(e,[...t.chunks,...await Nn(e,t)]),await N(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&&zt(o,n,r)&&Bt(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:De(xn(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 qt(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:t,transport:n,device:i,owner:a,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await gn({transport:n,device:i,input:o,startedAt:c,signal:s,prepareOutput:async()=>await t.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,r;try{r=await yn({transport:n,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:x.posix.dirname(e.remotePath)})}catch(a){await P(n,e),t=!0;try{r=await yn({transport:n,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:x.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:a}}let a=[...d,{...r,index:d.length+1}];try{await F(n,u,E(i,o,c,a,void 0,n.mode))}catch(a){if(await Jt(n,[r]).catch(()=>{}),t)await F(n,u,E(i,o,c,d,r.remotePath,n.mode)).catch(()=>{});else try{await F(n,u,E(i,o,c,d,void 0,n.mode))}catch{await P(n,e).catch(()=>{}),await F(n,u,E(i,o,c,d,r.remotePath,n.mode)).catch(()=>{})}throw a}d=a,t||await P(n,e),g()};g();let te=De(xn(o,c),{finish:async(e,r)=>{if(f&&clearTimeout(f),await p,m)throw m;let a=await Tn({host:t,transport:n,evidence:E(i,o,c,d,void 0,n.mode),manifestPath:u,recording:e,startedAtMs:l.startedAtMs,progress:r});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:n,deviceId:i.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await Mn(n,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new xe(te),envelope:be({resourceKind:Ne,sessionId:o.sessionId,device:r(i),owner:a,fence:o.fence,lifecycle:`open`,descriptor:ye(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:n.mode})})})}const Gn=1e3;async function z(e,t,n,r){return r.throwIfAborted(),await We(t)?{...t,booted:!0}:t.kind===`emulator`&&(t.booted!==!0||!B(t))?await Kn(e,t,n,r):(t.booted!==!0&&await Xn(e,t.id,Qn(e,n),r),{...t,booted:!0})}async function Kn(e,t,n,r){await qn(e);let i=$n(n),a=Qn(e,n),o=Jn(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),s=B(o)?o:void 0,c=s?void 0:e.deviceReadiness.androidEmulator.launch(o.name,n.headless);try{let t=s??await Yn(e,o.name,i,n.serial,a,r);return await Xn(e,t.id,a,r),{...(await e.deviceReadiness.androidEmulator.discover(i,r)).find(e=>e.id===t.id)??t,name:o.name,booted:!0}}catch(t){throw c!==void 0&&r.aborted&&await e.deviceReadiness.androidEmulator.terminate(c),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=er(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(e,t,n,r,i,a){for(;e.clock.now()<i;){let i=er(await e.deviceReadiness.androidEmulator.discover(n,a),t,r);if(i&&B(i))return i;await e.clock.sleep(Gn,a)}throw Zn(`Android emulator did not appear in time`,{avdName:t,serial:r})}async function Xn(e,t,n,r){for(;e.clock.now()<n;){if((await e.commands.run({executable:`adb`,args:o(`adb`,`shell`,[`getprop`,`sys.boot_completed`],[`-s`,t]),allowFailure:!0,timeoutMs:Math.min(1e4,Math.max(1e3,n-e.clock.now()))},r)).stdout.trim()===`1`)return;await e.clock.sleep(Gn,r)}throw Zn(`Android device failed to finish booting`,{serial:t})}function Zn(t,n){return new e(`COMMAND_FAILED`,t,{...n,reason:Me,hint:`The emulator keeps booting in the background. Retry once it is up, or pass a larger --timeout.`})}function Qn(e,t){return t.deadlineAtMs??e.clock.now()+12e4}function $n(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function er(e,t,n){let r=tr(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&tr(e.name)===r&&(!n||!B(e)||e.id===n))}function B(e){return e.id.startsWith(`emulator-`)}function tr(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}async function nr(e,t,n){try{let r=await e.snapshot({appBundleId:t,signal:n,transient:{settleBy:Date.now()+6e3}});return{observation:`androidSnapshot`in r&&r.androidSnapshot?.systemSurfaceOnly===!0?`unobservable`:`observable`}}catch(e){return n.throwIfAborted(),c(e)?{observation:`unobservable`}:{observation:`probe-failed`,failure:rr(e)}}}function rr(e){let n=t(e),r=s(n)??n.details?.reason,{code:i}=n;return typeof r==`string`?{source:`capture`,code:i,reason:r}:{source:`capture`,code:i}}function ir(e){let{host:t,device:n,signal:r}=e,i=qe({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,deadlineAtMs:e.execution.startupDeadlineAtMs},r)},openApplication:async e=>await ar(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 Ge({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:sr,configureProviderPortReverse:sr})}async function ar(t,n,r){let i={};if(r.relaunch&&r.target){let e=Date.now();await Ge({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:[r.appBundleId??r.target]}),i.relaunchCloseDurationMs=V(e)}if(f(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 a=Date.now();await Je({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution}),i.openDispatchDurationMs=V(a),r.enableTestIme&&await t.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let o=Ke(r);if(o){let e=Date.now();await Je({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=V(e)}else i.launchUrlDurationMs=0;let s=await t.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId);s&&await t.androidApplications.resetFramePerfStats(n.device,s);let c=Date.now();return Object.assign(i,await or(n,r,s)),i.postOpenSettleDurationMs=V(c),{appBundleId:s,timing:i}}async function or(e,t,r){if(!t.target||n(t.target))return{};if(!r)return{postOpenObservation:`app-unidentified`};let i=await nr(await e.resolveInteractor(t.execution,r),r,e.signal);return i.observation===`probe-failed`?{postOpenObservation:`probe-failed`,postOpenObservationFailure:i.failure}:{postOpenObservation:i.observation}}function V(e){return Math.max(0,Date.now()-e)}async function sr(){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 W(e,t,i);if(x.extname(n).toLowerCase()===`.aab`?await dr(e,t,n,i):K(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await W(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}function U(t){if(b()&&x.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 cr(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 lr(t,n,r,i){let a=r.payload,s=typeof a.action==`string`&&a.action.trim()?a.action.trim():`${r.appId}.TEST_PUSH`,c=[`am`,`broadcast`,`-a`,s,`-p`,r.appId];typeof a.receiver==`string`&&a.receiver.trim()&&c.push(`-n`,a.receiver.trim());let l=a.extras??{};if(typeof l!=`object`||!l||Array.isArray(l))throw new e(`INVALID_ARGS`,`Android push payload extras must be an object`);let u=0;for(let[e,t]of Object.entries(l))e&&(fr(c,e,t),u+=1);return K(await G(t,n,o(`adb`,`shell`,c),i),`adb push broadcast failed`),{action:s,extrasCount:u}}function ur(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 dr(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 W(e,t,n){let r=await G(e,t,o(`adb`,`shell`,[`pm`,`list`,`packages`]),n);return K(r,`adb package inventory failed`),new Set(r.stdout.split(`
5
5
  `).map(e=>e.replace(`package:`,``).trim()).filter(Boolean))}function fr(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 pr=Object.freeze({available:!0});function mr(e){let t=vr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:t})}function hr(e){let{host:t,device:n,signal:r}=e;return mr(n).deployApp.available?Object.freeze({deployApp:async e=>await gr(t,n,e,r),materializeAppSource:async e=>await t.androidDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await _r(t,n,e,r),sendPushNotification:async e=>await lr(t,n,e,r)}):Object.freeze({})}async function gr(e,t,n,r){if(n.replaceExisting)return await e.androidDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i;try{b()&&(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 cr(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{b()&&(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:ur(a),launchTarget:a}:{}}finally{await i?.cleanup()}}async function _r(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:ur(a),launchTarget:a}}function vr(e){return e.kind===`emulator`||e.kind===`device`?pr:Object.freeze({available:!1,reason:`unsupported-device-kind`})}const q=i(`android`),J=Object.freeze({available:!0}),yr=Object.freeze({available:!1,reason:`unsupported-device-kind`}),br=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Android emulators and physical devices.`}),xr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`keyboard actions are supported on Android emulators and physical devices.`}),Sr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Cr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Android has no key event for this system button.`}),wr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold drives the hinge of a foldable iPhone simulator; the Android emulator posture control is not driven by agent-device yet.`}),Tr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Headless boot is supported only for Android emulators.`}),Er=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Android appstate is supported only for Android emulators and devices.`}),Dr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),Or=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for Android emulators and devices.`}),kr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for Android emulators and devices.`}),Ar=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for Android emulators and devices.`}),jr=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),Mr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Nr=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.`}),Pr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Fr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web).`}),Ir=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 Lr(e){let t=Rr(e),n=zr(e),r=Br(e);return p({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:r,clearRuntimeHints:r,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Dr,configureProviderPortReverse:jr})}function Rr(e){return e.kind===`emulator`||e.kind===`device`?J:Or}function zr(e){return e.kind===`emulator`||e.kind===`device`?J:kr}function Br(e){return e.kind===`emulator`||e.kind===`device`?J:Ar}const X=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Gestures are supported on Android emulators and physical devices.`}),Vr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Le}),Hr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Ie});function Ur(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`?br:J}const $=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:Fe}),Wr=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 Gr(e,t){let n=e.androidTools?.probeClipboardShellSupport;return n?await n.call(e.androidTools,t):`probe-failed`}const Kr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`tv-remote is supported only on Android TV targets.`});function qr(e){return e.kind!==`simulator`&&e.target===`tv`?J:Kr}function Jr(e){let t=nt(e),n=new Map,r=async t=>{if(t.kind===`simulator`)return $;let r=n.get(t.id)??await Gr(e,t);return r!==`probe-failed`&&n.set(t.id,r),r===`supported`?J:r===`unsupported`?$:Wr},i=async e=>{let n=await t.inspectFacts(e),i=mr(e),a=await r(e);return Object.freeze({device:n.device,operations:{...n.operations,...i,appState:e.kind===`simulator`?Er:J,networkDump:J,screenRecordingStart:J,screenRecordingReattach:J,screenRecordingCleanup:J,...te({capture:e.kind===`simulator`?Y:J,customActions:Pr,withoutActiveApp:e.kind===`simulator`?Y:J}),...ie({capture:e.kind===`simulator`?Nr:J}),...oe({findText:Y}),...h({setViewport:Fr}),...he({focus:Q(e)}),...re({unsupported:X,plan:Z(e),directionalFling:Z(e),multiTouch:Ur(e,Vr),targetAuthoredDrag:Ur(e,Hr),viewport:Z(e)}),...ae({scroll:Z(e)}),...m({type:Q(e)}),...ve({unsupported:br,tap:Q(e),longPress:Q(e),hover:Sr,fill:Q(e)}),...ee({readTextAtPoint:e.kind===`simulator`?yr:J}),...pe({back:Q(e)}),...se({unsupported:Cr,home:Q(e),appSwitcher:Q(e)}),setFoldPose:wr,...de({triggerAppEvent:Q(e)}),...ue({setSetting:Q(e),readSetting:Q(e)}),...le({read:Q(e),wait:Q(e),accept:Q(e),dismiss:Q(e)}),...g({orientation:Q(e)}),...me({tvRemote:qr(e)}),...fe({unsupported:xr,status:Q(e),dismiss:Q(e),enter:Q(e)}),...ce({unsupported:a.available?$:a,read:a,write:a}),...ge({capture:Ye(e),query:Ir}),..._e({frames:Q(e),memorySample:Q(e),memorySnapshot:Q(e),nativeCapture:Q(e),profileReport:Q(e)}),ensureReady:J,bootTarget:J,bootTargetHeadless:e.kind===`emulator`?J:Tr,listApps:J,...Lr(e),shutdownTarget:e.kind===`emulator`?J:Mr}})};return Object.freeze({owner:q,ownsDevice:e=>e.platform===`android`,inspectFacts:i,bind:async n=>{let r=await t.bind(n),o=await i(n.device),s=await Un({host:e,device:n.device,owner:q,signal:n.scope.signal});return Object.freeze({device:r.device,owner:q,facts:o,operations:Object.freeze({...r.operations,...hr({host:e,device:n.device,signal:n.scope.signal}),...o.operations.appState.available?{appState:async()=>{n.scope.signal.throwIfAborted();let{runAndroidAdb:e}=await import(`./adb.js`).then(e=>e.t);return await Pe(async(t,r)=>await e(n.device,t,{...r,signal:n.scope.signal}),n.scope.signal)}}:{},networkDump:async t=>await at(e,n.device,t,n.scope.signal),...s,...a(o.operations.audioProbeStart,()=>Ce({host:e.audioProbe.hostCapture,device:n.device,owner:q})),...a(o.operations.perfFrames,()=>Xe({resolveHost:()=>e.perf.android,device:n.device,owner:q})),...Yr(e,n,o),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),...o.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}))},...d(ir({host:e,device:n.device,signal:n.scope.signal}),o.operations),...o.operations.shutdownTarget.available?{shutdownTarget:async()=>await e.deviceShutdown.android.shutdownTarget(n.device,n.scope.signal)}:{}}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}function Yr(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return{...n.operations.captureSnapshot.available?ne(r):{},...Re({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}}export{Jr as createAndroidPlatformRuntime};
@@ -1,5 +1,5 @@
1
- import{F as e,G as t,N as n,P as r}from"./sdk-contracts.js";import{_ as i,i as a}from"./sdk-batch-runner.js";import{A as o,D as s,c,d as l,f as u,m as d,p as f,y as p}from"./sdk-device.js";import{Xt as m,nn as h,rn as ee,tn as te}from"./sdk-batch.js";import{r as ne}from"./session.js";import"./device.js";import{a as re,l as g}from"./device-rotation.js";import{c as ie,r as ae}from"./diagnostics.js";import{a as oe,n as _}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{r as se}from"./version.js";import{n as ce}from"./scoped-provider.js";import{i as le,n as ue,r as de}from"./ios-snapshot-planning.js";import{t as fe}from"./request.js";import{n as pe,r as me,t as he}from"./application-lifecycle-runtime.js";import{A as ge,B as _e,C as ve,D as ye,E as be,G as xe,H as Se,I as Ce,J as we,K as Te,L as Ee,N as De,O as Oe,P as ke,V as Ae,W as je,d as Me,h as Ne,j as Pe,n as Fe,o as Ie,s as Le,v as Re,w as ze,x as Be,z as Ve}from"./alert-runtime.js";import{n as He}from"./audio-probe-runtime.js";import{n as Ue}from"./perf-runtime.js";import{i as We,t as Ge}from"./touch-runtime.js";import{a as Ke,n as qe}from"./durable-resource.js";import{n as Je,t as Ye}from"./async-lifecycle.js";import{a as Xe,c as Ze,d as Qe,f as $e,l as et,n as tt,o as nt,s as rt,t as it,u as at}from"./src7.js";import{n as ot,t as st}from"./screen-recording-completion.js";import{a as ct,c as lt,i as ut,n as dt,o as ft,r as pt,s as mt,t as ht}from"./device-readiness-runtime.js";import{n as gt}from"./screen-recording-runtime.js";import{t as _t}from"./ios-system-surface.js";import{i as vt,r as yt}from"./gesture-admission.js";import{t as bt}from"./interactor-operation-catalog.js";import{a as xt,i as St,n as Ct,r as wt,t as Tt}from"./perf-runtime-operation-builder.js";import{t as Et}from"./app-log-runtime.js";import{n as Dt}from"./artifact-paths.js";import{i as Ot,r as kt}from"./managed-device-scope.js";import{a as At,n as jt,o as Mt}from"./application-lifecycle-interaction.js";import{f as Nt}from"./host-file.js";import{a as Pt,o as Ft,s as It}from"./config.js";import{a as Lt,o as Rt}from"./tool-provider.js";import{o as zt}from"./devicectl.js";import{t as Bt}from"./physical-device-apps.js";import{t as Vt}from"./apple-runner-platform.js";import{a as Ht,i as Ut,l as Wt,n as Gt,o as v,s as Kt}from"./simctl.js";import{a as qt,r as Jt}from"./simulator.js";import{r as Yt}from"./display-inventory.js";import{t as Xt}from"./multitouch-support.js";import{t as Zt}from"./simulator-state.js";import{a as Qt,c as $t,d as en,i as tn,l as nn,n as rn,o as an,r as on,t as sn,u as cn}from"./cache.js";import y from"node:path";import{randomUUID as ln}from"node:crypto";function un(e){let t=Ot();return Object.freeze(t?{...ce({...e},e=>qt(t,e))}:e)}function dn(e,t){return Object.freeze({appState:async n=>{if(t.signal.throwIfAborted(),!await e.appleApplications.hasLiveRunnerSession(t.device,{}))return{};let r=await t.resolveInteractor(t.device,{appBundleId:n?.appBundleId,signal:t.signal});if(typeof r.appState!=`function`)throw ee(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function fn(e){return ft(e)?Object.freeze({available:!0}):d(e)||f(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 pn(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Tt({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 St(t().sampleFrames(n,e)):Ct(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await St(t().sampleMemory(n,e)):Ct(`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 xt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw wt();let c=i??y.join(a,`memory-memgraph-${mn()}.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 mn(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const b=Object.freeze({available:!0}),x=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),S=vn(`Gestures are supported only for Apple simulators and devices.`),hn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:yt}),gn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:vt}),_n=vn(`scroll is supported only for Apple simulators and devices.`);function vn(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function yn(e){return{...Ce({unsupported:bn(e),plan:xn(e),directionalFling:xn(e),multiTouch:Sn(e),targetAuthoredDrag:Cn(e),viewport:wn(e)}),...De({scroll:Tn(e)})}}function bn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?x:S}function xn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?x:C(e)?b:S}function Sn(e){if(e.appleOs===`watchos`)return x;if(!C(e))return S;let t=s(e);if(t!==`ios`&&t!==`ipados`){let e=Xt[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?b:hn}function Cn(e){return C(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?b:gn:S}function wn(e){return e.appleOs===`watchos`?x:C(e)?b:S}function Tn(e){return C(e)?b:_n}function C(e){return e.kind===`simulator`||e.kind===`device`}const w=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function T(e){return d(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const En=Object.freeze({resourceKind:Et,version:1,encode:e=>({...e}),decode:e=>!On(e.transport)||!kn(e.backend)||!Nn(e.outputPath)||!jn(e.pidPath)||!An(e.transport,e.backend)?Dn():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function Dn(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function On(e){return e===`apple-log-stream`||e===`coredevice-console`}function kn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function An(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function jn(e){return e===void 0||Nn(e)}function Mn(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return qe({resourceKind:Et,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:Ke(En,e.descriptor)})}function Nn(e){return typeof e==`string`&&e.trim().length>0}const Pn={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.`},Fn={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 In(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 Ln(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(d(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await lt(async()=>mt(await e.appleTools.run({tool:`simctl`,args:Kt(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(w);else{i.devicectlAvailable=await lt(async()=>mt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await In(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?Pn:Fn;a.push(`${e.message} ${e.hint}`)}}return{backend:T(t),checks:i,notes:a}}function Rn(e,t){let n=Vn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=Vn(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 zn(e,t){return Gt(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,Rn(t.appBundleId,t.executableName)])}function Bn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function Vn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function Hn(e,t,n,r,i){Un(t),nt(e,n);let a=T(t),o=await Gn(e,t,n.appBundleId,i),s=new Ye,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await Wn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=qn(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=$e(d,Mn({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function Un(e){if(e.appleOs===`watchos`)throw new n(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(f(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new n(`UNSUPPORTED_OPERATION`,w,{hint:w})}async function Wn(e,t,r,i,a,o){if(f(t)&&t.kind===`device`){let t=await In(e,o);if(!t.supported){let e=t.reason===`unsupported`?Pn:Fn;throw new n(t.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,e.message,{backend:`ios-device`,hint:e.hint,stderr:t.stderr})}}return o?.throwIfAborted(),await e.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function Gn(e,t,n,r){return d(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,Rn(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:Bn(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:zn(t,{appBundleId:n,executableName:await Kn(e,t,n,r)}),allowFailure:!0}}async function Kn(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:v(t,[`get_app_container`,t.id,n,`app`]),allowFailure:!0,timeoutMs:4e3},r),a=i.exitCode===0?i.stdout.trim():``;if(!a)return;let o=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,y.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function qn(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 at({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Jn([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 Jn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const E=m(`apple`),D=Object.freeze({available:!0});function Yn(e){return Object.freeze({owner:E,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>Zn(e),bind:async t=>{if(t.intent.kind===`exact-owner`&&!te(t.intent.owner,E))throw new n(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return Xn(e,t.device,t.scope.signal)},shutdown:async()=>void 0})}function Xn(e,t,r){if(t.platform!==`apple`)throw new n(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${t.platform}`);let i=Qe({codec:En,reattach:async(n,r)=>n.backend!==T(t)||!Xe(e,r.sessionId,n)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await Ze(e,n.pidPath),cleanup:async(n,r)=>n.backend===T(t)&&Xe(e,r.sessionId,n)?await rt(e,n.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:T(t)}),appLogDoctor:async({appBundleId:n})=>await Ln(e,t,n,r),appLogStart:async n=>await Hn(e,t,n,E,r),...i});return Object.freeze({device:t,owner:E,facts:Zn(t),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function Zn(e){if(e.appleOs===`watchos`)return Qn(e);let t=f(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:w}:D;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:D,appLogCleanup:D}})}function Qn(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 $n(e,t,n,r){let i=T(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=tt(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(tr(t,n,o.dump)){let i=await nr(e,t,n,a.path,r);i&&(o=er(s,o,i,n.maxEntries))}return ar(s,t,n),ir(s,o.dump),o.dump.entries.length===0&&s.push(or(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function er(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).`),it(n.scan,t,r))}function tr(e,t,n){return f(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function nr(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=v(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,rr(n.appBundleId),...typeof a==`number`&&Number.isFinite(a)&&a>0?[`--start`,`@${Math.floor(a/1e3)}`]:[`--last`,`5m`]]),s=await e.appleTools.run({tool:`simctl`,args:o,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
2
- `).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:tt(`${c.join(`
3
- `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function rr(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 ir(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 ar(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(f(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 or(e){return f(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.`:f(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 sr(e){let{host:t,snapshot:n,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=e,s=n.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:e.stopObservation;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let c;try{c=await t.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!n.invalidatedReason&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:i})}catch(e){throw r(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return st(n,{...c,...l.length>0?{warning:l.join(` `)}:{},...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function cr(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await lr(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function lr(e){try{return await e()}catch(e){throw r(e,`COMMAND_FAILED`)}}const ur=[`outPath`,`startedAt`,`clientOutPath`,...ut],O=Object.freeze({resourceKind:gt,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>Sr(e)});function dr(e){let{device:t,owner:n,input:r,descriptor:i}=e;return qe({resourceKind:gt,sessionId:r.sessionId,device:o(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:Ke(O,i)})}function fr(e){let t={};for(let n of ur)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function pr(e,t,n,r){let i=O.decode(n);return i.status!==`decoded`||!Mr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await mr(e,i.descriptor.processes,r):await gr(e,t,i.descriptor)}async function mr(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(hr(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(hr(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function hr(e){return{kind:`session`,sessionId:e}}async function gr(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 _r(e){let{host:t,device:n,envelope:r}=e,i=O.decode(r.descriptor.body);return i.status===`decoded`?Mr(n,i.descriptor)?i.descriptor.backend===`simctl`?await vr(e,i.descriptor):await br(t,n,i.descriptor):k(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):k(`descriptor-invalid`,i.message)}async function vr(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return k(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=yr(pt(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await xr(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await mr(e.host,t.processes,e.envelope.sessionId)}}function yr(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function br(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:k(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function xr(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function k(e,t){return{status:`unreattachable`,reason:e,message:t}}function Sr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?j():e.backend===`simctl`?Cr(e,e.outputPath):e.backend===`runner`?Er(e,e.outputPath):j()}function Cr(e,t){let n=Nr(e.processes),r=wr(e.recording);return!n||r===`invalid`?j():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function wr(e){if(e!==void 0)return i(e)&&Tr(e)?Object.freeze(e):`invalid`}function Tr(e){return A(e.outPath)&&Or(e.startedAt)&&Dr(e.clientOutPath)&&ct(e)}function Er(e,t){return!A(e.appBundleId)||!A(e.runnerSessionId)||!kr(e.runnerAuthority)||!Ar(e.remotePath)?j():{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 A(e){return typeof e==`string`&&e.length>0}function Dr(e){return e===void 0||A(e)}function Or(e){return typeof e==`number`&&Number.isFinite(e)}function kr(e){return e===`local-lease`||e===`scoped-provider`}function Ar(e){return e===void 0||jr(e)}function jr(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Mr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:f(e)?t.remotePath!==void 0&&jr(t.remotePath):t.remotePath===void 0:!1}function Nr(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 j(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Pr(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const Fr=`iOS recording`,Ir=`simctl recordVideo`;function Lr(e){return e.appleOs===`watchos`?Zr(`unsupported-platform-leaf`,`watchOS recording is not supported.`):f(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Zr(`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 Rr(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await zr({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await _r({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:Vr({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await pr(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function zr(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Br(e):await Ur(e)}async function Br(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Pr(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=Dt(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 M(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 M(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Gr(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=Xr(i,Ir,{},o);return Yr({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:fr(p)},snapshot:p,finish:(e,n)=>dt({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await Hr(t,s,e)}catch(e){throw Kr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await cr({host:t,snapshot:e,targetLabel:Fr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Kr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await Jr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function Vr(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:Ir,gestureEvents:[]});return ot(a,{finish:(e,i)=>dt({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await Hr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await cr({host:t,snapshot:e,targetLabel:Fr,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function Hr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Ur(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??=Wr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!qr(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return Yr({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:Xr(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await sr({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 Wr(e){try{return await e()}catch(e){throw r(e,`COMMAND_FAILED`)}}function Gr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Kr(e,t,i){let a=r(e,`COMMAND_FAILED`);return t===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?e:new n(a.code,`${a.message}; ${t}`,_(i,{...a.details??{},...i.signal===void 0?{}:{signal:i.signal},retriable:!1,hint:`The recorder exited before record stop, so the next record stop reads the same file. Close this session to release the device, then record again.`}))}function qr(e,t){return e.appleOs===`macos`||!f(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function M(e){return await e.terminate(),await e.wait}async function Jr(e){try{return await M(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function Yr(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=ot(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new Je(c),envelope:dr({device:t,owner:n,input:r,descriptor:i})})}function Xr(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 Zr(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const Qr=15e3;async function N(e,t,n,r={}){return n.throwIfAborted(),await kt(t)||d(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await $r(e,t)?`Booted`:await ii(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await ei(e,t,n,r.deadlineAtMs),await ai(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function $r(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function ei(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await ti(e,t,n,r),await ni(e,t,n,r)}catch(a){throw i&&n.aborted&&oi(e,t),n.throwIfAborted(),Date.now()>=r?ri(t,a):a}}async function ti(e,t,r,i){let a=await e.appleTools.run({tool:`simctl`,args:v(t,[`boot`,t.id]),allowFailure:!0,timeoutMs:P(i,t)},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 n(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function ni(e,t,r,i){fe({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await e.appleTools.run({tool:`simctl`,args:v(t,[`bootstatus`,t.id,`-b`]),allowFailure:!0,timeoutMs:P(i,t)},r);if(a.exitCode!==0)throw new n(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(await Zt(e.appleTools,t,r,Math.min(Qr,P(i,t)))!==`Booted`)throw new n(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:t.id});if(Date.now()>=i)throw ri(t)}function P(e,t){let n=e-Date.now();if(n<=0)throw ri(t);return n}function ri(e,t){return new n(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:ht,deviceId:e.id,hint:`The Simulator keeps booting in the background; a first boot can take several minutes. Retry once it is up, or pass a larger --timeout.`},t instanceof Error?t:void 0)}async function ii(e,t,n){return await Zt(e.appleTools,t,n,Qr)}async function ai(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function oi(e,t){e.appleTools.run({tool:`simctl`,args:v(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const si=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:`runner`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`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`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function ci(e){return e===void 0?`possible`:e.some(e=>si[e]===`runner`)?`required`:`none`}const li=3e3,ui=`simulator-target-discovery-pending`;function di(){let e=new Map,t=new Map,n=cn({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);if(c&&o!==`refresh`){let e=await nn(c.pid,{signal:a,timeoutMs:li});if(a.throwIfAborted(),e===c.processStartTime)return c}return e.delete(s),await n.value(s,{start:async()=>{let n=await mi(r,i,t);return e.set(s,n),n},wait:(e,t)=>en({waitMs:e,signal:a,stop:t,cancelled:()=>fi(a)}),pending:()=>F(ui,r,i)})}}function fi(t){return e({readinessPhase:`target-discovery`},t.reason)}function pi(e){return e instanceof n&&e.details?.reason===ui}async function mi(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([Ht(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:_i(r)}),hi(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 F(`simulator-target-probe-failed`,e,t);let c=gi(o.stdout,t);if(!c)throw F(`simulator-target-unavailable`,e,t);let l=await nn(c.pid,{timeoutMs:Math.min(li,_i(r))});if(!l)throw F(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:Wt(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function hi(e,t,n){let r=t.get(e.id);if(r)return await r;let i=Ht(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:_i(n)}).then(t=>{if(t.exitCode!==0)throw F(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(Ut(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw F(`simulator-runtime-unavailable`,e,``);return n});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function gi(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 _i(e){return Math.max(1,e-Date.now())}function F(e,t,r){return new n(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:t.id,appBundleId:r})}const vi=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function I(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function yi(e){let t=le(de({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!I(n))return`not-eligible`;let a;for(;;){let o=await bi(e.resolveTarget,n,r,i);if(!o)return`unobservable`;if(e.isBridgeDisabled(o))return ae({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=vi.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)}}})}async function bi(e,t,n,r){for(;;)try{return await e(t,n,r)}catch(e){if(r.throwIfAborted(),!pi(e))return}}function xi(e,t,n){let r=n&&I(e),i=r?ci(t.execution.plannedOperations):void 0,a=f(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function Si(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function Ci(e,t,n,r,i,a){let o=Date.now();r&&I(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 wi(e){let t=jt({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 N(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 Ti(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 Fi(e.host,t,n),finalizeApplicationClose:async t=>await Ii(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await Li(e.host,e.device,e.signal,t),configureProviderPortReverse:Hi})}async function Ti(e,t,n,r){let i={},a=L(t.device),o=Ri(e,t,n,i),s=xi(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),Si(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=Pi(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Ei(e,t,n,a,l,i),await Di(n,i),await Oi(o,c,n.prewarmRunnerBeforeOpen);let u=o.wasAwaited();return await ki(t,n,a,i),await ji(o,c,s.awaitPrewarmAfterOpen),await Mi(e,t,n,a,u,l),await Ci(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 Ei(e,t,n,r,i,a){if(!Ni(n,r)||!n.target)return;let o=Date.now();l(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await At({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=R(o)}async function Di(e,t){if(!me(e.runtimeHints))return;if(!e.applyRuntimeHints)throw new n(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let r=Date.now();await e.applyRuntimeHints({appId:e.appBundleId,values:e.runtimeHints}),t.runtimeHintsDurationMs=R(r)}async function Oi(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function ki(e,t,n,r){let i=Bi(t,n),a=Date.now();await Mt({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=R(a),await Ai(e,t,i.followUpUrl,r)}async function Ai(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 Mt({device:e.device,interactor:await e.resolveInteractor(i,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:i}),r.launchUrlDurationMs=R(a)}async function ji(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function Mi(e,t,n,r,i,a){!f(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 Ni(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function Pi(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&Ni(t,n)}async function Fi(e,t,n){n.ensureReady&&await N(e,t.device,t.signal),l(t.device.platform)&&!L(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await At({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),L(t.device)&&await e.clock.sleep(300,t.signal)}async function Ii(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&&L(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function Li(e,t,n,r){let i=Date.now()+r.timeoutMs;await N(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function Ri(e,t,n,r){let i,a=!1,o=zi(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=R(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function zi(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function Bi(e,t){let n=e.runtimeLaunchUrl?.trim(),r=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!n||!r||a(r)?{positionals:e.positionals}:t&&!Vi(e)?{positionals:[r,n]}:{positionals:e.positionals,followUpUrl:n}}function Vi(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function L(e){return f(e)&&e.kind===`simulator`}function R(e){return Math.max(0,Date.now()-e)}async function Hi(){throw new n(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const Ui=Object.freeze({available:!0}),Wi=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.`}),Gi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),Ki=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),qi=Object.freeze({available:!1,reason:`unsupported-device-kind`});function Ji(e){let t=na(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:ra(e)})}function Yi(e){let{host:t,device:n,signal:r}=e,i=Ji(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await Xi(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Zi(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await ea(t,n,e,r),{})}:{}})}async function Xi(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await $i(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Qi(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 Zi(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function Zi(e,t,n,r){return await Qi(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 Qi(e,t,n,r){await N(e,t,r),await ta(e,t.kind===`simulator`?{tool:`simctl`,args:v(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:Pt},r,`Apple app install failed`)}async function $i(e,t,n,r){await N(e,t,r),await ta(e,t.kind===`simulator`?{tool:`simctl`,args:v(t,[`uninstall`,t.id,n])}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n]},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>Bt(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function ea(e,t,r,i){if(t.kind!==`simulator`)throw new n(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await N(e,t,i);let a=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),await ta(e,{tool:`simctl`,args:v(t,[`push`,t.id,r.appId,a.path])},i,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}async function ta(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:oe(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:zt(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function na(e){return ia(e)?e.kind!==`simulator`&&e.kind!==`device`?qi:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Wi:Ui:Ki}function ra(e){return ia(e)?e.kind===`simulator`?Ui:Gi:Ki}function ia(e){return f(e)&&e.appleOs!==`watchos`}const z=Object.freeze({available:!0}),aa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),oa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function sa(e){return e.kind!==`simulator`&&e.kind!==`device`?aa:s(e)===`watchos`?oa:z}const ca=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),la=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ua=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function da(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=s(e);return n===`macos`||n===`watchos`?la:z}function B(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=s(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const fa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),pa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ma(e){return e.kind!==`simulator`&&e.kind!==`device`?fa:B(e)?z:pa}const ha=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function ga(e){return(e.kind===`simulator`||e.kind===`device`)&&p(e)?z:ha}const V=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),_a=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 va(e){return B(e)?_a:V}function ya(e){return B(e)?z:V}function ba(e){return B(e)?z:V}const xa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Sa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),Ca=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.`});function wa(e){return e.kind!==`simulator`&&e.kind!==`device`?Sa:c(e)?z:Ca}function Ta(e){return Object.freeze({...ze({back:sa(e)}),...Me({unsupported:xa,home:da(e,ca),appSwitcher:da(e,ua),actionButton:wa(e)}),...ve({orientation:ma(e)}),...Be({tvRemote:ga(e)}),...Re({unsupported:V,status:va(e),dismiss:ya(e),enter:ba(e)})})}function Ea(e){let{host:t,device:n,signal:r}=e;return bt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Ta(n)})}const H=Object.freeze({available:!0}),Da=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),Oa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),ka=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.`}),Aa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Apple targets answer a settings read only on iPhone and iPad simulators, where `simctl ui` reports the value the device holds."}),ja=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.`}),U=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ma(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=s(e);return r===`watchos`?U:e.kind===`simulator`||r===`macos`?H:n}function Na(e){return Ma(e,Da,ja)}const Pa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),Fa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),Ia=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function La(e){if(e.kind!==`simulator`&&e.kind!==`device`)return Fa;let t=s(e);return t===`watchos`?U:e.kind===`simulator`||t===`ios`||t===`macos`?H:Ia}function Ra(e){return e.kind!==`simulator`&&e.kind!==`device`?Pa:s(e)===`watchos`?U:H}function za(e){let t=Na(e);return t.available?ja:t}function Ba(e){return e.kind!==`simulator`&&e.kind!==`device`?Oa:s(e)===`watchos`?U:u(e)?H:Aa}function Va(e){let t=Na(e),n=La(e);return Object.freeze({...Ne({unsupported:za(e),read:t,write:t}),...Fe({read:n,wait:n,accept:n,dismiss:n}),...Le({triggerAppEvent:Ra(e)}),...Ie({setSetting:Ma(e,Oa,ka),readSetting:Ba(e)})})}function Ha(e){let{host:t,device:n,signal:r}=e;return bt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Va(n)})}function Ua(e){return Object.freeze({setFoldPose:e.fold})}const Wa=/Angle:\s*(-?\d+(?:[.,]\d+)?)\s*°/g;async function Ga(e,t={}){let r=[`devicectl`,`device`,`motion`,`hinge-angle`,`--device`,e.id,`--session-timeout`,`1`,`--timeout`,`5`],i=await Rt(r,{allowFailure:!0,signal:t.signal,timeoutMs:It}),a=Ka(i.stdout)??Ka(i.stderr);if(a!==void 0)return a;throw new n(`COMMAND_FAILED`,`CoreDevice reported no hinge angle sample`,_(i,{cmd:`xcrun`,args:r,stdout:i.stdout,stderr:i.stderr,deviceId:e.id,hint:`This Xcode/CoreDevice toolchain does not stream 'devicectl device motion hinge-angle' for this device. Foldable poses can be verified only through that stream; update Xcode to a version that ships it.`}))}function Ka(e){let t;for(let n of e.matchAll(Wa)){let e=Number.parseFloat(n[1].replace(`,`,`.`));Number.isFinite(e)&&(t=e)}return t}const qa=`Fold.m`,Ja=3e4,Ya=Vt+Ja;async function Xa(e={}){let t=e.host??Za(),n=an(Ya,e.signal);try{let r=e.sourceRoot??y.join(se(),`apple`,`fold-helper`),i=await on(t,r,[qa],n),a=await tn(t,n),o=e.cacheRoot??y.join(Nt(),`.agent-device`,`fold-helper`);return await sn({host:t,deadline:n,lockDescription:`iOS Simulator fold helper cache`,cacheRoot:o,binaryFilename:`fold-helper`,keyInputs:{schemaVersion:1,sourceHash:i,toolchain:a,compileArgv:Qa({sourceRoot:``,outputPath:``})},build:e=>$a(t,n,r,e)})}catch(e){throw eo(e)}}function Za(){return Qt(Lt)}function Qa(e){return[`--sdk`,`iphonesimulator`,`clang`,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`IOKit`,y.join(e.sourceRoot,qa),`-o`,e.outputPath]}async function $a(e,t,n,r){let i=await rn({host:e,deadline:t,argv:Qa({sourceRoot:n,outputPath:r}),budgetMs:Ja,label:`fold helper`});if(i.exitCode!==0||!e.exists(r))throw to(_(i))}function eo(e){return!(e instanceof $t)||e.buildFailureKind===`cancelled`?e:to({...e.buildDetails,cause:e.buildFailureCode},e)}function to(e,t){return new n(`COMMAND_FAILED`,`Unable to build the simulator fold helper`,{hint:`Select an Xcode with the iOS simulator SDK and foldable HID support using DEVELOPER_DIR.`,...e,reason:`fold-helper-build-failed`},t)}async function no(e,t,r){r?.throwIfAborted();let i=await Xa({signal:r});r?.throwIfAborted();let a=typeof t==`string`?0:t.at(-1).atMs,o=typeof t==`string`?t:JSON.stringify(t),s=await Ht(e,[`spawn`,e.id,i.path,o],{signal:r,timeoutMs:a+1e4,kill:{signal:`SIGTERM`,graceMs:1e3},allowFailure:!0});if(s.exitCode!==0)throw new n(`COMMAND_FAILED`,`Unable to send the simulator hinge pose`,_(s,{reason:`fold-hid-dispatch-failed`,deviceId:e.id}))}async function ro(e,t,n={}){n.signal?.throwIfAborted(),Jt(e,`fold`);let r=t,i=r.keyframes?.at(-1)?.angle,a=r.pose??g(i);io(e,await Yt(e,{signal:n.signal})),await no(e,r.keyframes??a,n.signal),ae({level:`info`,phase:`apple_fold_pose_dispatched`,data:{deviceId:e.id,pose:a}});let o=await ao(e,a,n.signal,i),s=await ho(e,n.signal);return{pose:g(o),hingeAngleDegrees:o,...s?{screen:go(s)}:{}}}function io(e,t){if(t.unresolved)throw new n(`COMMAND_FAILED`,`CoreDevice reported no display table for this simulator`,{deviceId:e.id,hint:`fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.`});if(!t.multiScreen)throw new n(`UNSUPPORTED_OPERATION`,`${e.name} is not a foldable simulator: fold requires more than one integrated panel`,{deviceId:e.id,reason:`single-panel-device`,hint:`fold sets the hinge angle of a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.`})}async function ao(e,t,n,r){let i,a;for(let o=1;o<=4;o+=1)if(n?.throwIfAborted(),a=i,i=await Ga(e,{signal:n}),oo(i,a,t,r))return i;throw lo(e,t,i,a,r)}function oo(e,t,n,r){return r===void 0?g(e)===n?n!==`half-open`||t!==void 0&&uo(e,t):!1:so(e,t,r)}function so(e,t,n){return co(e,n)?n===0||n===180||t!==void 0&&co(t,n)&&Math.abs(e-t)<=.5:!1}function co(e,t){return t===void 0||e!==void 0&&Math.abs(e-t)<=.5}function lo(e,t,r,i,a){return co(r,a)?a!==void 0&&r!==void 0?mo(e,g(r),r,i):r!==void 0&&t===`half-open`&&g(r)===t?mo(e,t,r,i):po(e,t,r):new n(`COMMAND_FAILED`,`The hinge did not reach the final keyframe angle`,{reason:`fold-angle-unverified`,targetAngleDegrees:a,hingeAngleDegrees:r,deviceId:e.id})}function uo(e,t){return g(e)===`half-open`&&g(t)===`half-open`&&Math.abs(e-t)<=.5}function fo(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:g(n),hingeAngleDegrees:n}}function po(e,t,r){return new n(`COMMAND_FAILED`,`${e.name} did not reach the ${t} pose: CoreDevice still reports a hinge angle of ${r}°`,{...fo(e,t,r),reason:`fold-pose-unverified`,hint:`The simulator HID command completed, but the hinge did not follow. Verify that the selected Xcode and simulator runtime support foldable HID control, then retry.`})}function mo(e,t,r,i){return new n(`COMMAND_FAILED`,`${e.name} was observed ${t} at ${r}° but did not settle: 4 hinge reads never held two consecutive angles within ${Ft}° of each other`,{...fo(e,t,r),reason:`fold-pose-unsettled`,...i===void 0?{}:{previousHingeAngleDegrees:i},hint:`The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.`})}async function ho(e,t){let n=await Yt(e,{signal:t});if(!(n.unresolved||n.ambiguous))return n.activeDisplay}function go(e){return{display:e.name,coordinateSpace:re,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const _o=Object.freeze({available:!0}),vo=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold is supported on foldable iPhone simulators controlled through simulator HID; a physical device is folded by hand.`}),yo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.`});function bo(e){return{available:!1,reason:`unsupported-device-scope`,hint:`fold cannot resolve a simulator scoped to the set at "${e}": CoreDevice's display inventory and hinge-angle readback need a simulator in the default set, so the pose could not be verified. Run fold without --ios-simulator-device-set.`}}function xo(e){if(e.kind!==`simulator`)return vo;let t=s(e);return t!==`ios`&&t!==`ipados`?yo:e.simulatorSetPath?bo(e.simulatorSetPath):_o}function So(e){return Ua({fold:xo(e)})}function Co(e){let{device:t,signal:n}=e;return h(So(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await ro(t,e,{signal:n}))}))}function wo(e,t,n){let r=Se({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(d(t.device)&&ne(i.options?.surface)===`macos-helper`)return await e.snapshot.captureSurface(t.device,i.options,je(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=je(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 To(e,t){return Object.freeze({findText:async n=>{let r=await Eo(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 Eo(e,t,n){let r=n.options?.appBundleId;if(r===void 0||d(t.device)&&ne(n.options?.surface)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await Do(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function Do(e,t,n){return!I(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Oo(){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()}}}function ko(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 Ao(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function Ao(e,t){let n=!1;for(let r of _t){let i=await jo(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await Mo(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function jo(e,t){let n=await No(`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 Mo(e,t,n){let r=await No(`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 No(e,t,n){try{let r=await Lt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Po=`system-surface-presented`,Fo=`system-surface-host-lingering`,Io=`window-coordinate-space-unresolved`;function Lo(e,t={}){let r=t.source??Oo(),i=t.resolveTarget??di(),a=t.systemSurfacePresent??ko(),o=new Set,s=new Map,c=e=>(Xo(e,s,o),o.has(Zo(e))),l=yi({source:r,resolveTarget:i,clock:e.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(t,s,l,u)=>{if(!Bo(t,s))return await Wo(t,s,u);let d=await a(t,l);if(d===`unknown`)return await W(t.id,s,u,G(t.id,s),q(s),`system-surface-probe-unavailable`,[K()]);if(d!==`absent`)return await Uo(t,s,u,d.host.bundleId);let f;try{f=await Ro(e,i,t,s,l)}catch(e){return zo(l,e),J(`target-resolution-failed`,t,void 0,e),await W(t.id,s,u,G(t.id,s),q(s),`target-resolution-failed`,[K()])}if(c(f))return J(`circuit-disabled`,t,f.generation),await W(t.id,s,u,f,q(s),`circuit-disabled`);let p=q(s),m=await r.acquire({target:f,hint:le(p),signal:l});if(m.stage===`failed`){if(m.failure.kind===`cancelled`)throw l.throwIfAborted(),new n(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:m.failure.code,...m.failure.details});let e=await Yo(m.failure,f,t,s.options.appBundleId,l,i);return await Vo(s,u,f,e,p,m.failure,o)}try{return await ie(`ios.snapshot-source.present`,async()=>await e.snapshot.presentIosAcquisition(m,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await Vo(s,u,f,{lineage:f,residue:[]},p,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Ro(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!pi(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function zo(e,n){if(e.aborted)throw t(n)?n:e.reason}function Bo(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 Vo(e,t,n,r,i,a,o,s){return Ho(a)&&o.add(Zo(n)),J(a.code,{id:n.simulator.udid},n.generation,s,a.details),await W(n.simulator.udid,e,t,r.lineage,i,a.code,r.residue)}function Ho(e){return e.kind!==`preparing`&&e.code!==Io}async function W(e,t,n,r,i,a,o=[]){return Go(e,await n(t),r,i,a,o)}async function Uo(e,t,n,r){let i=await n(t),a=i.systemSurface?Po:Fo;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),Go(e.id,i,G(e.id,t),q(t),a)}async function Wo(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:qo(Ko(e.id,i.bundleId),q(t),[])}:r}function Go(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:qo(o?Ko(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],Jo(i,n,o!==void 0)]}}function G(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function Ko(e,t){return{targetId:`${e}:${t}`}}function qo(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:ue(t),residue:Object.freeze([...n])})}function Jo(e,t,n){return e===Po?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Fo?`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`:n?`Simulator AX snapshot unavailable (${e}); used XCTest, which read the system surface presented over the app.`:e===`bridge-preparation-pending`?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture while the bridge is still being prepared.`:e===Io?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture, which reports captured geometry in the app's own orientation space.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function Yo(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:ln()}}function q(e){return de({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 Xo(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 Zo(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){ae({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=m(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Qo=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.`}),$o=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.`}),es=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),ts=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),ns=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`});function rs(e){return!f(e)||e.appleOs===`watchos`?ns:e.kind===`simulator`||e.kind===`device`?X:ns}const is=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),as=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),os=Object.freeze({available:!1,reason:`unsupported-device-kind`}),ss=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),cs=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),ls=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),us=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),ds=Q(`open is supported only for Apple simulators and devices.`),fs=Q(`prepare is supported only for Apple simulators and devices.`),ps=Q(`close is supported only for Apple simulators and devices.`),ms=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),hs=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),gs=Q(`snapshot is supported only for Apple simulators and devices.`),_s=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),vs=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),ys=Q(`screenshot is supported only for Apple simulators and devices.`),bs=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 xs(e){return!f(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:hs}function Ss(e){let t=Cs(e),n=ws(e),r=Ts(e),i=Es(e);return he({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:ms})}function Cs(e){return s(e)===`watchos`?ss:e.kind===`simulator`||e.kind===`device`?X:ds}function ws(e){return s(e)===`watchos`?cs:e.kind===`simulator`||e.kind===`device`?X:fs}function Ts(e){return s(e)===`watchos`?ls:e.kind===`simulator`||e.kind===`device`?X:ps}function Es(e){return s(e)!==`watchos`&&f(e)&&e.kind===`simulator`?X:us}function Ds(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:ts}function Os(e){let t=Yn(e),n=Lo(e),r=async n=>{let r=await t.inspectFacts(n),i=Ji(n),a=Lr(n),o=a.available?await e.screenRecording.apple.availability(n):void 0,s=a.available&&o?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:o.hint}):a,c=n.appleOs===`watchos`?Z:X,l=d(n)||n.appleOs===`watchos`?Z:X,u=Ds(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:rs(n),networkDump:X,screenRecordingStart:s,screenRecordingReattach:s,screenRecordingCleanup:s,...Ns(n),...we({capture:Ms(n)}),...Ae({findText:js(n)}),..._e({setViewport:Qo}),...Ve({focus:$(n)}),...yn(n),...ge({type:$(n)}),...We({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...f(n)?{tapElementSelector:$(n)}:{}}),...ye({readTextAtPoint:As(n)}),...Ta(n),...So(n),...Va(n),...He({capture:fn(n),query:$o}),...Ue(ks(n)),ensureReady:c,bootTarget:l,bootTargetHeadless:is,listApps:u,...Ss(n),shutdownTarget:xs(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={...h(o.operations.appState,()=>dn(e,{device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...a.operations,...Yi({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await $n(e,i.device,t,i.scope.signal),...h(s,()=>Rr({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...h(o.operations.audioProbeStart,()=>et({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...h(o.operations.perfFrames,()=>pn({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...h(o.operations.captureSnapshot,()=>wo(e,{device:i.device,signal:i.scope.signal},n)),...h(o.operations.captureScreenshot,()=>Te({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.focusPoint,()=>Ee({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...ke({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...h(o.operations.scrollDirection,()=>Pe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.typeText,()=>Oe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.tapPoint,()=>Ge({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)})),...h(o.operations.readTextAtPoint,()=>be({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.findText,()=>To(e,{device:i.device,signal:i.scope.signal})),...Ea({host:e,device:i.device,signal:i.scope.signal}),...Ha({host:e,device:i.device,signal:i.scope.signal}),...Co({device:i.device,signal:i.scope.signal}),...h(o.operations.ensureReady,()=>({ensureReady:async()=>await N(e,i.device,i.scope.signal)})),...h(o.operations.bootTarget,()=>({bootTarget:async t=>await N(e,i.device,i.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...h(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}))}})),...pe(wi({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...h(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:un(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function ks(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&s(e)!==`watchos`?X:es;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function As(e){return s(e)===`watchos`?as:e.kind===`simulator`||e.kind===`device`?X:os}function js(e){return s(e)===`watchos`?gs:e.kind===`simulator`||e.kind===`device`?X:gs}function Ms(e){return s(e)===`watchos`?vs:e.kind===`simulator`||e.kind===`device`?X:ys}function Ns(e){let t=js(e);return xe({capture:t,customActions:t.available&&f(e)&&e.kind===`simulator`?X:_s,withoutActiveApp:f(e)?bs:t})}export{Os as createApplePlatformRuntime};
1
+ import{F as e,G as t,N as n,P as r,q as i}from"./sdk-contracts.js";import{_ as a,a as o,i as s}from"./sdk-batch-runner.js";import{A as c,D as l,c as u,d,f,m as p,p as m,y as ee}from"./sdk-device.js";import{Xt as te,nn as h,rn as ne,tn as re}from"./sdk-batch.js";import{r as ie}from"./session.js";import"./device.js";import{a as ae,u as g}from"./device-rotation.js";import{c as oe,r as se}from"./diagnostics.js";import{o as ce,r as _}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{r as le}from"./version.js";import{n as ue}from"./scoped-provider.js";import{i as de,n as fe,r as pe}from"./ios-snapshot-planning.js";import{t as me}from"./request.js";import{n as he,r as ge,t as _e}from"./application-lifecycle-runtime.js";import{A as ve,B as ye,C as be,D as xe,E as Se,G as Ce,H as we,I as Te,J as Ee,K as De,L as Oe,N as ke,O as Ae,P as je,V as Me,W as Ne,d as Pe,h as Fe,j as Ie,n as Le,o as Re,s as ze,v as Be,w as Ve,x as He,z as Ue}from"./alert-runtime.js";import{n as We}from"./audio-probe-runtime.js";import{n as Ge}from"./perf-runtime.js";import{i as Ke,t as qe}from"./touch-runtime.js";import{a as Je,n as Ye}from"./durable-resource.js";import{n as Xe,t as Ze}from"./async-lifecycle.js";import{a as Qe,c as $e,d as et,f as tt,l as nt,n as rt,o as it,s as at,t as ot,u as st}from"./src7.js";import{n as ct,t as lt}from"./screen-recording-completion.js";import{a as ut,c as dt,i as ft,n as pt,o as mt,r as ht,s as gt,t as _t}from"./device-readiness-runtime.js";import{n as vt}from"./screen-recording-runtime.js";import{t as yt}from"./ios-system-surface.js";import{i as bt,r as xt}from"./gesture-admission.js";import{t as St}from"./interactor-operation-catalog.js";import{a as Ct,i as wt,n as Tt,r as Et,t as Dt}from"./perf-runtime-operation-builder.js";import{t as Ot}from"./app-log-runtime.js";import{n as kt}from"./artifact-paths.js";import{i as At,r as jt}from"./managed-device-scope.js";import{a as Mt,n as Nt,o as Pt}from"./application-lifecycle-interaction.js";import{f as Ft}from"./host-file.js";import{a as It,o as Lt,s as Rt}from"./config.js";import{a as zt,o as Bt}from"./tool-provider.js";import{o as Vt}from"./devicectl.js";import{t as Ht}from"./physical-device-apps.js";import{t as Ut}from"./apple-runner-platform.js";import{a as Wt,i as Gt,l as Kt,n as qt,o as v,s as Jt}from"./simctl.js";import{a as Yt,r as Xt}from"./simulator.js";import{r as Zt}from"./display-inventory.js";import{t as Qt}from"./multitouch-support.js";import{t as $t}from"./simulator-state.js";import{a as en,c as tn,d as nn,i as rn,l as an,n as on,o as sn,r as cn,t as ln,u as un}from"./cache.js";import y from"node:path";import{randomUUID as dn}from"node:crypto";function fn(e){let t=At();return Object.freeze(t?{...ue({...e},e=>Yt(t,e))}:e)}function pn(e,t){return Object.freeze({appState:async n=>{if(t.signal.throwIfAborted(),!await e.appleApplications.hasLiveRunnerSession(t.device,{}))return{};let r=await t.resolveInteractor(t.device,{appBundleId:n?.appBundleId,signal:t.signal});if(typeof r.appState!=`function`)throw ne(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function mn(e){return mt(e)?Object.freeze({available:!0}):p(e)||m(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 hn(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Dt({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 wt(t().sampleFrames(n,e)):Tt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await wt(t().sampleMemory(n,e)):Tt(`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 Et();let c=i??y.join(a,`memory-memgraph-${gn()}.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 gn(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const b=Object.freeze({available:!0}),x=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),S=bn(`Gestures are supported only for Apple simulators and devices.`),_n=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:xt}),vn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:bt}),yn=bn(`scroll is supported only for Apple simulators and devices.`);function bn(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function xn(e){return{...Te({unsupported:Sn(e),plan:Cn(e),directionalFling:Cn(e),multiTouch:wn(e),targetAuthoredDrag:Tn(e),viewport:En(e)}),...ke({scroll:Dn(e)})}}function Sn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?x:S}function Cn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?x:C(e)?b:S}function wn(e){if(e.appleOs===`watchos`)return x;if(!C(e))return S;let t=l(e);if(t!==`ios`&&t!==`ipados`){let e=Qt[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?b:_n}function Tn(e){return C(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?b:vn:S}function En(e){return e.appleOs===`watchos`?x:C(e)?b:S}function Dn(e){return C(e)?b:yn}function C(e){return e.kind===`simulator`||e.kind===`device`}const w=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function T(e){return p(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const On=Object.freeze({resourceKind:Ot,version:1,encode:e=>({...e}),decode:e=>!An(e.transport)||!jn(e.backend)||!Fn(e.outputPath)||!Nn(e.pidPath)||!Mn(e.transport,e.backend)?kn():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function kn(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function An(e){return e===`apple-log-stream`||e===`coredevice-console`}function jn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Mn(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function Nn(e){return e===void 0||Fn(e)}function Pn(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return Ye({resourceKind:Ot,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:Je(On,e.descriptor)})}function Fn(e){return typeof e==`string`&&e.trim().length>0}const In={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.`},Ln={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 Rn(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 zn(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(p(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await dt(async()=>gt(await e.appleTools.run({tool:`simctl`,args:Jt(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(w);else{i.devicectlAvailable=await dt(async()=>gt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await Rn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?In:Ln;a.push(`${e.message} ${e.hint}`)}}return{backend:T(t),checks:i,notes:a}}function Bn(e,t){let n=Un(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=Un(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 Vn(e,t){return qt(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,Bn(t.appBundleId,t.executableName)])}function Hn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function Un(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function Wn(e,t,n,r,i){Gn(t),it(e,n);let a=T(t),o=await qn(e,t,n.appBundleId,i),s=new Ze,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await Kn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=Yn(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=tt(d,Pn({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function Gn(e){if(e.appleOs===`watchos`)throw new n(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(m(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new n(`UNSUPPORTED_OPERATION`,w,{hint:w})}async function Kn(e,t,r,i,a,o){if(m(t)&&t.kind===`device`){let t=await Rn(e,o);if(!t.supported){let e=t.reason===`unsupported`?In:Ln;throw new n(t.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,e.message,{backend:`ios-device`,hint:e.hint,stderr:t.stderr})}}return o?.throwIfAborted(),await e.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function qn(e,t,n,r){return p(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,Bn(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:Hn(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:Vn(t,{appBundleId:n,executableName:await Jn(e,t,n,r)}),allowFailure:!0}}async function Jn(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:v(t,[`get_app_container`,t.id,n,`app`]),allowFailure:!0,timeoutMs:4e3},r),a=i.exitCode===0?i.stdout.trim():``;if(!a)return;let o=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,y.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function Yn(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 st({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Xn([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 Xn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const E=te(`apple`),D=Object.freeze({available:!0});function Zn(e){return Object.freeze({owner:E,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>$n(e),bind:async t=>{if(t.intent.kind===`exact-owner`&&!re(t.intent.owner,E))throw new n(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return Qn(e,t.device,t.scope.signal)},shutdown:async()=>void 0})}function Qn(e,t,r){if(t.platform!==`apple`)throw new n(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${t.platform}`);let i=et({codec:On,reattach:async(n,r)=>n.backend!==T(t)||!Qe(e,r.sessionId,n)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await $e(e,n.pidPath),cleanup:async(n,r)=>n.backend===T(t)&&Qe(e,r.sessionId,n)?await at(e,n.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:T(t)}),appLogDoctor:async({appBundleId:n})=>await zn(e,t,n,r),appLogStart:async n=>await Wn(e,t,n,E,r),...i});return Object.freeze({device:t,owner:E,facts:$n(t),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function $n(e){if(e.appleOs===`watchos`)return er(e);let t=m(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:w}:D;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:D,appLogCleanup:D}})}function er(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 tr(e,t,n,r){let i=T(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=rt(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(rr(t,n,o.dump)){let i=await ir(e,t,n,a.path,r);i&&(o=nr(s,o,i,n.maxEntries))}return sr(s,t,n),or(s,o.dump),o.dump.entries.length===0&&s.push(cr(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function nr(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).`),ot(n.scan,t,r))}function rr(e,t,n){return m(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function ir(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=v(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,ar(n.appBundleId),...typeof a==`number`&&Number.isFinite(a)&&a>0?[`--start`,`@${Math.floor(a/1e3)}`]:[`--last`,`5m`]]),s=await e.appleTools.run({tool:`simctl`,args:o,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
2
+ `).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:rt(`${c.join(`
3
+ `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function ar(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 or(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 sr(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(m(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 cr(e){return m(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.`:m(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 lr(e){let{host:t,snapshot:n,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=e,s=n.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:e.stopObservation;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let c;try{c=await t.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!n.invalidatedReason&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:i})}catch(e){throw r(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return lt(n,{...c,...l.length>0?{warning:l.join(` `)}:{},...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function ur(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await dr(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function dr(e){try{return await e()}catch(e){throw r(e,`COMMAND_FAILED`)}}const fr=[`outPath`,`startedAt`,`clientOutPath`,...ft],pr=Object.freeze({resourceKind:vt,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>Tr(e)});function mr(e){let{device:t,owner:n,input:r,descriptor:i}=e;return Ye({resourceKind:vt,sessionId:r.sessionId,device:c(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:Je(pr,i)})}function hr(e){let t={};for(let n of fr)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function gr(e,t,n,r){let i=pr.decode(n);return i.status!==`decoded`||!Fr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await _r(e,i.descriptor.processes,r):await yr(e,t,i.descriptor)}async function _r(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(vr(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(vr(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function vr(e){return{kind:`session`,sessionId:e}}async function yr(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 br(e){let{host:t,device:n,envelope:r}=e,i=pr.decode(r.descriptor.body);return i.status===`decoded`?Fr(n,i.descriptor)?i.descriptor.backend===`simctl`?await xr(e,i.descriptor):await Cr(t,n,i.descriptor):O(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):O(`descriptor-invalid`,i.message)}async function xr(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return O(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=Sr(ht(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await wr(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await _r(e.host,t.processes,e.envelope.sessionId)}}function Sr(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function Cr(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:O(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function wr(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function O(e,t){return{status:`unreattachable`,reason:e,message:t}}function Tr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?A():e.backend===`simctl`?Er(e,e.outputPath):e.backend===`runner`?kr(e,e.outputPath):A()}function Er(e,t){let n=Ir(e.processes),r=Dr(e.recording);return!n||r===`invalid`?A():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function Dr(e){if(e!==void 0)return a(e)&&Or(e)?Object.freeze(e):`invalid`}function Or(e){return k(e.outPath)&&jr(e.startedAt)&&Ar(e.clientOutPath)&&ut(e)}function kr(e,t){return!k(e.appBundleId)||!k(e.runnerSessionId)||!Mr(e.runnerAuthority)||!Nr(e.remotePath)?A():{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 k(e){return typeof e==`string`&&e.length>0}function Ar(e){return e===void 0||k(e)}function jr(e){return typeof e==`number`&&Number.isFinite(e)}function Mr(e){return e===`local-lease`||e===`scoped-provider`}function Nr(e){return e===void 0||Pr(e)}function Pr(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Fr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:m(e)?t.remotePath!==void 0&&Pr(t.remotePath):t.remotePath===void 0:!1}function Ir(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 A(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Lr(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const Rr=`iOS recording`,zr=`simctl recordVideo`;function Br(e){return e.appleOs===`watchos`?ei(`unsupported-platform-leaf`,`watchOS recording is not supported.`):m(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?ei(`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 Vr(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Hr({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await br({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:Wr({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await gr(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Hr(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Ur(e):await Kr(e)}async function Ur(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Lr(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=kt(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 j(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 j(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Jr(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=$r(i,zr,{},o);return Qr({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:hr(p)},snapshot:p,finish:(e,n)=>pt({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await Gr(t,s,e)}catch(e){throw Yr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await ur({host:t,snapshot:e,targetLabel:Rr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Yr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await Zr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function Wr(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:zr,gestureEvents:[]});return ct(a,{finish:(e,i)=>pt({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await Gr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await ur({host:t,snapshot:e,targetLabel:Rr,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function Gr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Kr(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??=qr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!Xr(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 Qr({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:$r(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await lr({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 qr(e){try{return await e()}catch(e){throw r(e,`COMMAND_FAILED`)}}function Jr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Yr(e,t,i){let a=r(e,`COMMAND_FAILED`);return t===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?e:new n(a.code,`${a.message}; ${t}`,_(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 Xr(e,t){return e.appleOs===`macos`||!m(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function j(e){return await e.terminate(),await e.wait}async function Zr(e){try{return await j(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function Qr(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=ct(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new Xe(c),envelope:mr({device:t,owner:n,input:r,descriptor:i})})}function $r(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 ei(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const ti=15e3;async function M(e,t,n,r={}){return n.throwIfAborted(),await jt(t)||p(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await ni(e,t)?`Booted`:await ci(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await ri(e,t,n,r.deadlineAtMs),await li(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function ni(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function ri(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await ii(e,t,n,r),await ai(e,t,n,r)}catch(a){throw i&&n.aborted&&ui(e,t),n.throwIfAborted(),Date.now()>=r?si(t,a):a}}async function ii(e,t,r,i){let a=await e.appleTools.run({tool:`simctl`,args:v(t,[`boot`,t.id]),allowFailure:!0,timeoutMs:oi(i,t)},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 n(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function ai(e,t,r,i){me({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await e.appleTools.run({tool:`simctl`,args:v(t,[`bootstatus`,t.id,`-b`]),allowFailure:!0,timeoutMs:oi(i,t)},r);if(a.exitCode!==0)throw new n(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(await $t(e.appleTools,t,r,Math.min(ti,oi(i,t)))!==`Booted`)throw new n(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:t.id});if(Date.now()>=i)throw si(t)}function oi(e,t){let n=e-Date.now();if(n<=0)throw si(t);return n}function si(e,t){return new n(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:_t,deviceId:e.id,hint:`The Simulator keeps booting in the background; a first boot can take several minutes. Retry once it is up, or pass a larger --timeout.`},t instanceof Error?t:void 0)}async function ci(e,t,n){return await $t(e.appleTools,t,n,ti)}async function li(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function ui(e,t){e.appleTools.run({tool:`simctl`,args:v(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const di=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:`runner`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`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`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function fi(e){return e===void 0?`possible`:e.some(e=>di[e]===`runner`)?`required`:`none`}const pi=3e3,mi=`simulator-target-discovery-pending`,hi=`simulator-target-unavailable`;function gi(){let e=new Map,t=new Map,n=un({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);if(c&&o!==`refresh`){let e=await an(c.pid,{signal:a,timeoutMs:pi});if(a.throwIfAborted(),e===c.processStartTime)return c}return 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)=>nn({waitMs:e,signal:a,stop:t,cancelled:()=>_i(a)}),pending:()=>N(mi,r,i)})}}function _i(t){return e({readinessPhase:`target-discovery`},t.reason)}function vi(e){return e instanceof n&&e.details?.reason===mi}function yi(e){return e instanceof n&&e.details?.reason===hi}async function bi(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([Wt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:Ci(r)}),xi(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 N(`simulator-target-probe-failed`,e,t);let c=Si(o.stdout,t);if(!c)throw N(hi,e,t);let l=await an(c.pid,{timeoutMs:Math.min(pi,Ci(r))});if(!l)throw N(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:Kt(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function xi(e,t,n){let r=t.get(e.id);if(r)return await r;let i=Wt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:Ci(n)}).then(t=>{if(t.exitCode!==0)throw N(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(Gt(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw N(`simulator-runtime-unavailable`,e,``);return n});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Si(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 Ci(e){return Math.max(1,e-Date.now())}function N(e,t,r){return new n(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:t.id,appBundleId:r})}function wi(e){return e?.observation===`unobservable`&&e.proof===`no-running-process`}const Ti=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function P(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function Ei(e){let t=de(pe({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!P(n))return{observation:`not-eligible`};let a;for(;;){let o=await Di(e.resolveTarget,n,r,i);if(`verdict`in o)return o.verdict;let{target:s}=o;if(e.isBridgeDisabled(s))return se({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:s.generation}}),F({source:`circuit`});let c=await e.source.acquire({target:s,hint:t,signal:i});if(c.stage!==`failed`)return{observation:`observable`};i.throwIfAborted();let{kind:l,code:u}=c.failure,d=Ti.get(u);if(d===void 0)return F({source:`bridge`,kind:l,code:u});let f=e.clock.now();if(a=Math.min(a??1/0,f+d),f>=a)return{observation:`unobservable`,proof:`launch-transition`};await e.clock.sleep(Math.min(150,a-f),i)}}})}function F(e){return{observation:`probe-failed`,failure:e}}async function Di(e,t,n,r){for(;;)try{return{target:await e(t,n,r)}}catch(e){if(r.throwIfAborted(),vi(e))continue;if(yi(e))return{verdict:{observation:`unobservable`,proof:`no-running-process`}};let{code:t,details:n}=i(e),a=n?.reason;return{verdict:F(typeof a==`string`?{source:`target`,code:t,reason:a}:{source:`target`,code:t})}}}function Oi(e,t,n){let r=n&&P(e),i=r?fi(t.execution.plannedOperations):void 0,a=m(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function ki(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function Ai(e,t,r,i,a,o){let s=Date.now(),c=async()=>await Fi(t,r,i,a.observation),l=await c(),u,d=a.answerConfirmation,f=d&&l?.observation!==`observable`?await ji(d,a.redispatchLaunchUrl,c,l):void 0;if(f&&(o.runnerDemand=`required`,u=f.launchConfirmation,l=f.observed,f.unanswered))throw new n(`COMMAND_FAILED`,`The launch URL was handed to the Simulator but ${r.appBundleId} never came up.`,{reason:`launch_confirmation_unanswered`,appBundleId:r.appBundleId,hint:`iOS may still be holding an "Open in" prompt, or the answer died with the runner session that raised it. Answer it with alert accept, or re-run open with the same --launch-url.`});return i&&l?.observation!==`observable`&&await e.clock.sleep(300,t.signal),l&&(o.postOpenObservation=l.observation,l.observation===`probe-failed`&&(o.postOpenObservationFailure=l.failure)),o.postOpenSettleDurationMs=Math.max(0,Date.now()-s),u}async function ji(e,t,n,r){let i={observed:r,acceptAttempted:!1};for(let r=0;r<2&&(i=await Mi(e,n,i),!(r===1||!Ni(i)||!t));r+=1)await t();return{observed:i.observed,launchConfirmation:i.launchConfirmation,unanswered:Ni(i)}}async function Mi(e,t,n){let r=await e(),i=n.acceptAttempted||Pi(r),a=r.outcome===`accepted`?`accepted`:n.launchConfirmation;return i?{observed:await t(),launchConfirmation:a,acceptAttempted:i}:{observed:n.observed,launchConfirmation:a,acceptAttempted:i}}function Ni(e){return e.acceptAttempted&&wi(e.observed)}function Pi(e){return e.outcome===`accepted`||e.outcome===`unreadable`&&e.step===`alert-accept`}async function Fi(e,t,n,r){if(!(!n||!P(e.device))&&!(!r||!t.appBundleId))return await r.awaitObservable(e.device,t.appBundleId,e.signal)}let Ii;const Li=()=>Ii??=import(`./launch-confirmation.js`);function Ri(e){let t=Nt({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 M(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 zi(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 Qi(e.host,t,n),finalizeApplicationClose:async t=>await $i(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await ea(e.host,e.device,e.signal,t),configureProviderPortReverse:oa})}async function zi(e,t,n,r){let i={},a=I(t.device),o=ra(t.device,n,a),s=ta(e,t,n,i),c=Oi(t.device,n,a);c.runnerDemand&&(i.runnerDemand=c.runnerDemand),ki(e,t,n,c);let{shouldPrewarmRunner:l}=c,u=Zi(t.device,n,a);a&&l&&!n.prewarmRunnerBeforeOpen&&s.schedule();try{await Bi(e,t,n,a,u,i),await Vi(n,i),await Hi(s,l,n.prewarmRunnerBeforeOpen);let d=s.wasAwaited();await Ui(t,n,o,a,i),await Ji(s,l,c.awaitPrewarmAfterOpen),await Yi(e,t,n,a,d,u);let f=await Ai(e,t,n,a,{observation:r,answerConfirmation:Ki(t,n,o),redispatchLaunchUrl:qi(t,n,o)},i);return{appBundleId:n.appBundleId,timing:i,...f?{launchConfirmation:f}:{}}}catch(n){throw u&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Bi(e,t,n,r,i,a){if(!Xi(n,r)||!n.target)return;let o=Date.now();d(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await Mt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=L(o)}async function Vi(e,t){if(!ge(e.runtimeHints))return;if(!e.applyRuntimeHints)throw new n(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let r=Date.now();await e.applyRuntimeHints({appId:e.appBundleId,values:e.runtimeHints}),t.runtimeHintsDurationMs=L(r)}async function Hi(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Ui(e,t,n,r,i){let a=Date.now();await Pt({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:n.positionals,appBundleId:t.appBundleId,execution:t.execution,...r&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),i.openDispatchDurationMs=L(a),await Wi(e,t,n.followUpUrl,i)}async function Wi(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i=Date.now();await Gi(e,t,n),r.launchUrlDurationMs=L(i)}async function Gi(e,t,n){let r={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0};await Pt({device:e.device,interactor:await e.resolveInteractor(r,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:r})}function Ki(e,t,{confirmation:n}){if(n)return async()=>{let{answerSimulatorLaunchConfirmation:r}=await Li();return await r(e.device,n,e.resolveInteractor(t.execution,n.appBundleId),e.signal)}}function qi(e,t,{confirmation:n}){if(n)return async()=>{await Gi(e,t,n.url)}}async function Ji(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function Yi(e,t,n,r,i,a){!m(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 Xi(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function Zi(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&Xi(t,n)}async function Qi(e,t,n){n.ensureReady&&await M(e,t.device,t.signal),d(t.device.platform)&&!I(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await Mt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),I(t.device)&&await e.clock.sleep(300,t.signal)}async function $i(e,t,n,r){r.daemonShutdown||await e.appleApplications.releaseRunnerOnClose(t.id,{retain:r.retainRunner}),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{});let i=r.shutdownTarget&&I(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function ea(e,t,n,r){let i=Date.now()+r.timeoutMs;await M(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function ta(e,t,n,r){let i,a=!1,o=na(t.device,n)?{healthCheck:!1}:void 0;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,o?e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a,o):e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=L(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function na(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function ra(e,t,n){let r=t.runtimeLaunchUrl?.trim(),i=t.positionals.length===1?t.positionals[0]?.trim():void 0;if(!r||!i||s(i))return{positionals:t.positionals};let a=ia(e,t.appBundleId,r),o=a?{confirmation:a}:{};return n&&!aa(t)?{positionals:[i,r],...o}:{positionals:t.positionals,followUpUrl:r,...o}}function ia(e,t,n){if(e.appleOs===`ios`&&e.kind===`simulator`&&!(t===void 0||o(n)))return{url:n,appBundleId:t}}function aa(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function I(e){return m(e)&&e.kind===`simulator`}function L(e){return Math.max(0,Date.now()-e)}async function oa(){throw new n(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const sa=Object.freeze({available:!0}),ca=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.`}),la=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),ua=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),da=Object.freeze({available:!1,reason:`unsupported-device-kind`});function fa(e){let t=ba(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:xa(e)})}function pa(e){let{host:t,device:n,signal:r}=e,i=fa(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await ma(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await ha(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await va(t,n,e,r),{})}:{}})}async function ma(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await _a(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await ga(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 ha(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function ha(e,t,n,r){return await ga(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 ga(e,t,n,r){await M(e,t,r),await ya(e,t.kind===`simulator`?{tool:`simctl`,args:v(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:It},r,`Apple app install failed`)}async function _a(e,t,n,r){await M(e,t,r),await ya(e,t.kind===`simulator`?{tool:`simctl`,args:v(t,[`uninstall`,t.id,n])}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n]},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>Ht(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function va(e,t,r,i){if(t.kind!==`simulator`)throw new n(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await M(e,t,i);let a=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),await ya(e,{tool:`simctl`,args:v(t,[`push`,t.id,r.appId,a.path])},i,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}async function ya(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:ce(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:Vt(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function ba(e){return Sa(e)?e.kind!==`simulator`&&e.kind!==`device`?da:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?ca:sa:ua}function xa(e){return Sa(e)?e.kind===`simulator`?sa:la:ua}function Sa(e){return m(e)&&e.appleOs!==`watchos`}const R=Object.freeze({available:!0}),Ca=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),wa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ta(e){return e.kind!==`simulator`&&e.kind!==`device`?Ca:l(e)===`watchos`?wa:R}const Ea=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),Da=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Oa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function ka(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=l(e);return n===`macos`||n===`watchos`?Da:R}function z(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=l(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const Aa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),ja=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ma(e){return e.kind!==`simulator`&&e.kind!==`device`?Aa:z(e)?R:ja}const Na=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function Pa(e){return(e.kind===`simulator`||e.kind===`device`)&&ee(e)?R:Na}const B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Fa=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 Ia(e){return z(e)?Fa:B}function La(e){return z(e)?R:B}function Ra(e){return z(e)?R:B}const za=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),Va=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.`});function Ha(e){return e.kind!==`simulator`&&e.kind!==`device`?Ba:u(e)?R:Va}function Ua(e){return Object.freeze({...Ve({back:Ta(e)}),...Pe({unsupported:za,home:ka(e,Ea),appSwitcher:ka(e,Oa),actionButton:Ha(e)}),...be({orientation:Ma(e)}),...He({tvRemote:Pa(e)}),...Be({unsupported:B,status:Ia(e),dismiss:La(e),enter:Ra(e)})})}function Wa(e){let{host:t,device:n,signal:r}=e;return St({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Ua(n)})}const V=Object.freeze({available:!0}),Ga=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),Ka=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),qa=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.`}),Ja=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Apple targets answer a settings read only on iPhone and iPad simulators, where `simctl ui` reports the value the device holds."}),Ya=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.`}),H=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Xa(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=l(e);return r===`watchos`?H:e.kind===`simulator`||r===`macos`?V:n}function Za(e){return Xa(e,Ga,Ya)}const Qa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),$a=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),eo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function to(e){if(e.kind!==`simulator`&&e.kind!==`device`)return $a;let t=l(e);return t===`watchos`?H:e.kind===`simulator`||t===`ios`||t===`macos`?V:eo}function no(e){return e.kind!==`simulator`&&e.kind!==`device`?Qa:l(e)===`watchos`?H:V}function ro(e){let t=Za(e);return t.available?Ya:t}function io(e){return e.kind!==`simulator`&&e.kind!==`device`?Ka:l(e)===`watchos`?H:f(e)?V:Ja}function ao(e){let t=Za(e),n=to(e);return Object.freeze({...Fe({unsupported:ro(e),read:t,write:t}),...Le({read:n,wait:n,accept:n,dismiss:n}),...ze({triggerAppEvent:no(e)}),...Re({setSetting:Xa(e,Ka,qa),readSetting:io(e)})})}function oo(e){let{host:t,device:n,signal:r}=e;return St({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:ao(n)})}function so(e){return Object.freeze({setFoldPose:e.fold})}const co=/Angle:\s*(-?\d+(?:[.,]\d+)?)\s*°/g;async function lo(e,t={}){let r=[`devicectl`,`device`,`motion`,`hinge-angle`,`--device`,e.id,`--session-timeout`,`1`,`--timeout`,`5`],i=await Bt(r,{allowFailure:!0,signal:t.signal,timeoutMs:Rt}),a=uo(i.stdout)??uo(i.stderr);if(a!==void 0)return a;throw new n(`COMMAND_FAILED`,`CoreDevice reported no hinge angle sample`,_(i,{cmd:`xcrun`,args:r,stdout:i.stdout,stderr:i.stderr,deviceId:e.id,hint:`This Xcode/CoreDevice toolchain does not stream 'devicectl device motion hinge-angle' for this device. Foldable poses can be verified only through that stream; update Xcode to a version that ships it.`}))}function uo(e){let t;for(let n of e.matchAll(co)){let e=Number.parseFloat(n[1].replace(`,`,`.`));Number.isFinite(e)&&(t=e)}return t}const fo=`Fold.m`,po=3e4,mo=Ut+po;async function ho(e={}){let t=e.host??go(),n=sn(mo,e.signal);try{let r=e.sourceRoot??y.join(le(),`apple`,`fold-helper`),i=await cn(t,r,[fo],n),a=await rn(t,n),o=e.cacheRoot??y.join(Ft(),`.agent-device`,`fold-helper`);return await ln({host:t,deadline:n,lockDescription:`iOS Simulator fold helper cache`,cacheRoot:o,binaryFilename:`fold-helper`,keyInputs:{schemaVersion:1,sourceHash:i,toolchain:a,compileArgv:_o({sourceRoot:``,outputPath:``})},build:e=>vo(t,n,r,e)})}catch(e){throw yo(e)}}function go(){return en(zt)}function _o(e){return[`--sdk`,`iphonesimulator`,`clang`,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`IOKit`,y.join(e.sourceRoot,fo),`-o`,e.outputPath]}async function vo(e,t,n,r){let i=await on({host:e,deadline:t,argv:_o({sourceRoot:n,outputPath:r}),budgetMs:po,label:`fold helper`});if(i.exitCode!==0||!e.exists(r))throw bo(_(i))}function yo(e){return!(e instanceof tn)||e.buildFailureKind===`cancelled`?e:bo({...e.buildDetails,cause:e.buildFailureCode},e)}function bo(e,t){return new n(`COMMAND_FAILED`,`Unable to build the simulator fold helper`,{hint:`Select an Xcode with the iOS simulator SDK and foldable HID support using DEVELOPER_DIR.`,...e,reason:`fold-helper-build-failed`},t)}async function xo(e,t,r){r?.throwIfAborted();let i=await ho({signal:r});r?.throwIfAborted();let a=typeof t==`string`?0:t.at(-1).atMs,o=typeof t==`string`?t:JSON.stringify(t),s=await Wt(e,[`spawn`,e.id,i.path,o],{signal:r,timeoutMs:a+1e4,kill:{signal:`SIGTERM`,graceMs:1e3},allowFailure:!0});if(s.exitCode!==0)throw new n(`COMMAND_FAILED`,`Unable to send the simulator hinge pose`,_(s,{reason:`fold-hid-dispatch-failed`,deviceId:e.id}))}async function So(e,t,n={}){n.signal?.throwIfAborted(),Xt(e,`fold`);let r=t,i=r.keyframes?.at(-1)?.angle,a=r.pose??g(i);Co(e,await Zt(e,{signal:n.signal})),await xo(e,r.keyframes??a,n.signal),se({level:`info`,phase:`apple_fold_pose_dispatched`,data:{deviceId:e.id,pose:a}});let o=await wo(e,a,n.signal,i),s=await Mo(e,n.signal);return{pose:g(o),hingeAngleDegrees:o,...s?{screen:No(s)}:{}}}function Co(e,t){if(t.unresolved)throw new n(`COMMAND_FAILED`,`CoreDevice reported no display table for this simulator`,{deviceId:e.id,hint:`fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.`});if(!t.multiScreen)throw new n(`UNSUPPORTED_OPERATION`,`${e.name} is not a foldable simulator: fold requires more than one integrated panel`,{deviceId:e.id,reason:`single-panel-device`,hint:`fold sets the hinge angle of a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.`})}async function wo(e,t,n,r){let i,a;for(let o=1;o<=4;o+=1)if(n?.throwIfAborted(),a=i,i=await lo(e,{signal:n}),To(i,a,t,r))return i;throw Do(e,t,i,a,r)}function To(e,t,n,r){return r===void 0?g(e)===n?n!==`half-open`||t!==void 0&&Oo(e,t):!1:Eo(e,t,r)}function Eo(e,t,n){return U(e,n)?n===0||n===180||t!==void 0&&U(t,n)&&Math.abs(e-t)<=.5:!1}function U(e,t){return t===void 0||e!==void 0&&Math.abs(e-t)<=.5}function Do(e,t,r,i,a){return U(r,a)?a!==void 0&&r!==void 0?jo(e,g(r),r,i):r!==void 0&&t===`half-open`&&g(r)===t?jo(e,t,r,i):Ao(e,t,r):new n(`COMMAND_FAILED`,`The hinge did not reach the final keyframe angle`,{reason:`fold-angle-unverified`,targetAngleDegrees:a,hingeAngleDegrees:r,deviceId:e.id})}function Oo(e,t){return g(e)===`half-open`&&g(t)===`half-open`&&Math.abs(e-t)<=.5}function ko(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:g(n),hingeAngleDegrees:n}}function Ao(e,t,r){return new n(`COMMAND_FAILED`,`${e.name} did not reach the ${t} pose: CoreDevice still reports a hinge angle of ${r}°`,{...ko(e,t,r),reason:`fold-pose-unverified`,hint:`The simulator HID command completed, but the hinge did not follow. Verify that the selected Xcode and simulator runtime support foldable HID control, then retry.`})}function jo(e,t,r,i){return new n(`COMMAND_FAILED`,`${e.name} was observed ${t} at ${r}° but did not settle: 4 hinge reads never held two consecutive angles within ${Lt}° of each other`,{...ko(e,t,r),reason:`fold-pose-unsettled`,...i===void 0?{}:{previousHingeAngleDegrees:i},hint:`The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.`})}async function Mo(e,t){let n=await Zt(e,{signal:t});if(!(n.unresolved||n.ambiguous))return n.activeDisplay}function No(e){return{display:e.name,coordinateSpace:ae,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const Po=Object.freeze({available:!0}),Fo=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold is supported on foldable iPhone simulators controlled through simulator HID; a physical device is folded by hand.`}),Io=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.`});function Lo(e){return{available:!1,reason:`unsupported-device-scope`,hint:`fold cannot resolve a simulator scoped to the set at "${e}": CoreDevice's display inventory and hinge-angle readback need a simulator in the default set, so the pose could not be verified. Run fold without --ios-simulator-device-set.`}}function Ro(e){if(e.kind!==`simulator`)return Fo;let t=l(e);return t!==`ios`&&t!==`ipados`?Io:e.simulatorSetPath?Lo(e.simulatorSetPath):Po}function zo(e){return so({fold:Ro(e)})}function Bo(e){let{device:t,signal:n}=e;return h(zo(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await So(t,e,{signal:n}))}))}function Vo(e,t,n){let r=we({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(p(t.device)&&ie(i.options?.surface)===`macos-helper`)return await e.snapshot.captureSurface(t.device,i.options,Ne(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=Ne(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 Ho(e,t){return Object.freeze({findText:async n=>{let r=await Uo(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 Uo(e,t,n){let r=n.options?.appBundleId;if(r===void 0||p(t.device)&&ie(n.options?.surface)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await Wo(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function Wo(e,t,n){return!P(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Go(){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()}}}function Ko(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 qo(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function qo(e,t){let n=!1;for(let r of yt){let i=await Jo(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await Yo(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function Jo(e,t){let n=await Xo(`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 Yo(e,t,n){let r=await Xo(`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 Xo(e,t,n){try{let r=await zt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Zo=`system-surface-presented`,Qo=`system-surface-host-lingering`,$o=`window-coordinate-space-unresolved`;function es(e,t={}){let r=t.source??Go(),i=t.resolveTarget??gi(),a=t.systemSurfacePresent??Ko(),o=new Set,s=new Map,c=e=>(ps(e,s,o),o.has(ms(e))),l=Ei({source:r,resolveTarget:i,clock:e.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(t,s,l,u)=>{if(!rs(t,s))return await ss(t,s,u);let d=await a(t,l);if(d===`unknown`)return await W(t.id,s,u,G(t.id,s),q(s),`system-surface-probe-unavailable`,[K()]);if(d!==`absent`)return await os(t,s,u,d.host.bundleId);let f;try{f=await ts(e,i,t,s,l)}catch(e){return ns(l,e),J(`target-resolution-failed`,t,void 0,e),await W(t.id,s,u,G(t.id,s),q(s),`target-resolution-failed`,[K()])}if(c(f))return J(`circuit-disabled`,t,f.generation),await W(t.id,s,u,f,q(s),`circuit-disabled`);let p=q(s),m=await r.acquire({target:f,hint:de(p),signal:l});if(m.stage===`failed`){if(m.failure.kind===`cancelled`)throw l.throwIfAborted(),new n(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:m.failure.code,...m.failure.details});let e=await fs(m.failure,f,t,s.options.appBundleId,l,i);return await is(s,u,f,e,p,m.failure,o)}try{return await oe(`ios.snapshot-source.present`,async()=>await e.snapshot.presentIosAcquisition(m,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await is(s,u,f,{lineage:f,residue:[]},p,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function ts(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!vi(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function ns(e,n){if(e.aborted)throw t(n)?n:e.reason}function rs(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 is(e,t,n,r,i,a,o,s){return as(a)&&o.add(ms(n)),J(a.code,{id:n.simulator.udid},n.generation,s,a.details),await W(n.simulator.udid,e,t,r.lineage,i,a.code,r.residue)}function as(e){return e.kind!==`preparing`&&e.code!==$o}async function W(e,t,n,r,i,a,o=[]){return cs(e,await n(t),r,i,a,o)}async function os(e,t,n,r){let i=await n(t),a=i.systemSurface?Zo:Qo;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),cs(e.id,i,G(e.id,t),q(t),a)}async function ss(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:us(ls(e.id,i.bundleId),q(t),[])}:r}function cs(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:us(o?ls(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],ds(i,n,o!==void 0)]}}function G(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function ls(e,t){return{targetId:`${e}:${t}`}}function us(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:fe(t),residue:Object.freeze([...n])})}function ds(e,t,n){return e===Zo?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Qo?`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`:n?`Simulator AX snapshot unavailable (${e}); used XCTest, which read the system surface presented over the app.`:e===`bridge-preparation-pending`?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture while the bridge is still being prepared.`:e===$o?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture, which reports captured geometry in the app's own orientation space.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function fs(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:dn()}}function q(e){return pe({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 ps(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 ms(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){se({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=te(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),hs=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.`}),gs=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.`}),_s=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),vs=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),ys=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`});function bs(e){return!m(e)||e.appleOs===`watchos`?ys:e.kind===`simulator`||e.kind===`device`?X:ys}const xs=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),Ss=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),Cs=Object.freeze({available:!1,reason:`unsupported-device-kind`}),ws=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),Ts=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),Es=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),Ds=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),Os=Q(`open is supported only for Apple simulators and devices.`),ks=Q(`prepare is supported only for Apple simulators and devices.`),As=Q(`close is supported only for Apple simulators and devices.`),js=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),Ms=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Ns=Q(`snapshot is supported only for Apple simulators and devices.`),Ps=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Fs=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),Is=Q(`screenshot is supported only for Apple simulators and devices.`),Ls=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 Rs(e){return!m(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:Ms}function zs(e){let t=Bs(e),n=Vs(e),r=Hs(e),i=Us(e);return _e({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:js})}function Bs(e){return l(e)===`watchos`?ws:e.kind===`simulator`||e.kind===`device`?X:Os}function Vs(e){return l(e)===`watchos`?Ts:e.kind===`simulator`||e.kind===`device`?X:ks}function Hs(e){return l(e)===`watchos`?Es:e.kind===`simulator`||e.kind===`device`?X:As}function Us(e){return l(e)!==`watchos`&&m(e)&&e.kind===`simulator`?X:Ds}function Ws(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:vs}function Gs(e){let t=Zn(e),n=es(e),r=async n=>{let r=await t.inspectFacts(n),i=fa(n),a=Br(n),o=a.available?await e.screenRecording.apple.availability(n):void 0,s=a.available&&o?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:o.hint}):a,c=n.appleOs===`watchos`?Z:X,l=p(n)||n.appleOs===`watchos`?Z:X,u=Ws(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:bs(n),networkDump:X,screenRecordingStart:s,screenRecordingReattach:s,screenRecordingCleanup:s,...Xs(n),...Ee({capture:Ys(n)}),...Me({findText:Js(n)}),...ye({setViewport:hs}),...Ue({focus:$(n)}),...xn(n),...ve({type:$(n)}),...Ke({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...m(n)?{tapElementSelector:$(n)}:{}}),...xe({readTextAtPoint:qs(n)}),...Ua(n),...zo(n),...ao(n),...We({capture:mn(n),query:gs}),...Ge(Ks(n)),ensureReady:c,bootTarget:l,bootTargetHeadless:xs,listApps:u,...zs(n),shutdownTarget:Rs(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={...h(o.operations.appState,()=>pn(e,{device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...a.operations,...pa({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await tr(e,i.device,t,i.scope.signal),...h(s,()=>Vr({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...h(o.operations.audioProbeStart,()=>nt({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...h(o.operations.perfFrames,()=>hn({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...h(o.operations.captureSnapshot,()=>Vo(e,{device:i.device,signal:i.scope.signal},n)),...h(o.operations.captureScreenshot,()=>De({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.focusPoint,()=>Oe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...je({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...h(o.operations.scrollDirection,()=>Ie({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.typeText,()=>Ae({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.tapPoint,()=>qe({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)})),...h(o.operations.readTextAtPoint,()=>Se({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...h(o.operations.findText,()=>Ho(e,{device:i.device,signal:i.scope.signal})),...Wa({host:e,device:i.device,signal:i.scope.signal}),...oo({host:e,device:i.device,signal:i.scope.signal}),...Bo({device:i.device,signal:i.scope.signal}),...h(o.operations.ensureReady,()=>({ensureReady:async()=>await M(e,i.device,i.scope.signal)})),...h(o.operations.bootTarget,()=>({bootTarget:async t=>await M(e,i.device,i.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...h(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}))}})),...he(Ri({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...h(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:fn(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Ks(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&l(e)!==`watchos`?X:_s;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function qs(e){return l(e)===`watchos`?Ss:e.kind===`simulator`||e.kind===`device`?X:Cs}function Js(e){return l(e)===`watchos`?Ns:e.kind===`simulator`||e.kind===`device`?X:Ns}function Ys(e){return l(e)===`watchos`?Fs:e.kind===`simulator`||e.kind===`device`?X:Is}function Xs(e){let t=Js(e);return Ce({capture:t,customActions:t.available&&m(e)&&e.kind===`simulator`?X:Ps,withoutActiveApp:m(e)?Ls:t})}export{Gs as createApplePlatformRuntime};