agent-device 0.21.32 → 0.21.33

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 (41) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.32.apk → agent-device-android-ime-helper-0.21.33.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.33.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.32.manifest.json → agent-device-android-ime-helper-0.21.33.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.32.apk → agent-device-android-snapshot-helper-0.21.33.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.33.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.32.manifest.json → agent-device-android-snapshot-helper-0.21.33.manifest.json} +7 -7
  7. package/apple/fold-helper/Fold.m +32 -11
  8. package/apple/snapshot-bridge/ForegroundApplicationGeometry.h +4 -16
  9. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +1 -2
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +36 -58
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +66 -111
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +1 -2
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +2 -2
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +5 -29
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +4 -17
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +66 -117
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollDragExecution.swift +4 -4
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +21 -75
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +7 -61
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +1 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.h +24 -53
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m +13 -39
  23. package/dist/src/app-backend.js +1 -1
  24. package/dist/src/app-launch.js +1 -1
  25. package/dist/src/command-metadata.js +1 -1
  26. package/dist/src/config.js +1 -1
  27. package/dist/src/device-readiness-runtime.js +1 -1
  28. package/dist/src/display-inventory.js +1 -1
  29. package/dist/src/fold-helper.js +2 -2
  30. package/dist/src/fold-runtime.js +1 -0
  31. package/dist/src/interactor.js +5 -5
  32. package/dist/src/internal/bin.js +1 -1
  33. package/dist/src/mechanics.js +12 -12
  34. package/dist/src/physical-device-control.js +1 -1
  35. package/dist/src/runtime.js +3 -3
  36. package/dist/src/runtime3.js +5 -5
  37. package/dist/src/simulator.js +1 -1
  38. package/package.json +7 -2
  39. package/server.json +2 -2
  40. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.32.apk.sha256 +0 -1
  41. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.32.apk.sha256 +0 -1
@@ -1,5 +1,5 @@
1
- import{E as e,H as t,Q as n,R as r,V as i,tt as a}from"./sdk-contracts.js";import{C as o,M as s,l as c}from"./tv-remote.js";import{a as l,b as u,i as d,v as f}from"./sdk-batch-runner.js";import{K as p,St as m,Y as h,_t as g}from"./sdk-io.js";import"./diagnostics.js";import{C as _,T as v,U as ee,b as te,j as ne,p as re,w as y,z as b}from"./sdk-device.js";import{Cn as ie,Sn as x,bn as ae,hn as oe,xn as S}from"./sdk-batch.js";import{i as se,r as ce}from"./session.js";import"./command.js";import{i as le,n as ue,r as de}from"./ios-snapshot-planning.js";import{i as fe,n as pe}from"./durable-resource.js";import{n as me}from"./screen-recording-runtime.js";import{t as he}from"./request.js";import{n as ge,r as _e,t as ve}from"./application-lifecycle-runtime.js";import{n as ye,t as be}from"./async-lifecycle.js";import{i as xe,t as Se}from"./touch-runtime.js";import{t as Ce}from"./ios-system-surface.js";import{r as we}from"./gesture-admission.js";import{B as Te,C as Ee,E as De,I as Oe,K as ke,M as Ae,N as je,O as Me,P as Ne,R as Pe,T as Fe,U as Ie,V as Le,W as Re,X as ze,Y as Be,Z as Ve,_ as He,j as Ue,k as We,l as Ge,o as Ke,p as qe,q as Je,r as Ye,v as Xe,x as Ze}from"./tv-remote-runtime.js";import{n as Qe,o as $e,s as et,u as tt}from"./application-lifecycle-interaction.js";import{t as nt}from"./interactor-operation-catalog.js";import{a as rt,i as it,n as at,o as ot,r as st,s as ct,t as lt}from"./network-traffic.js";import{a as ut,i as dt,r as ft}from"./src4.js";import{n as pt,t as mt}from"./screen-recording-completion.js";import{a as ht,c as gt,i as _t,l as vt,n as yt,o as bt,r as xt,s as St,t as Ct}from"./device-readiness-runtime.js";import{a as wt,i as Tt,n as Et,r as Dt,t as Ot}from"./perf-runtime-operation-builder.js";import{t as kt}from"./app-log-runtime.js";import{n as At}from"./artifact-paths.js";import{a as jt,o as Mt,s as Nt}from"./config.js";import{a as Pt}from"./tool-provider.js";import{o as Ft}from"./devicectl.js";import{i as It}from"./physical-device-control.js";import{a as Lt,c as Rt,n as zt,o as Bt,s as C,u as Vt}from"./simctl.js";import{c as Ht,u as Ut}from"./runner-client.js";import{r as Wt}from"./simulator.js";import{r as Gt}from"./display-inventory.js";import{n as Kt}from"./fold-helper.js";import{n as qt,t as Jt}from"./app-backend.js";import{t as Yt}from"./simulator-state.js";import{randomUUID as Xt}from"node:crypto";import Zt from"node:path";function Qt(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 ie(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function $t(e){return e.hostApp?Object.freeze({available:!1,reason:`unsupported-device-scope`,hint:`This session holds one app of the Mac. Use a --surface desktop session for audio probe.`}):bt(e)?Object.freeze({available:!0}):v(e)||y(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 en(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Ot({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 Tt(t().sampleFrames(n,e)):Et(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await Tt(t().sampleMemory(n,e)):Et(`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 wt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw Dt();let c=i??Zt.join(a,`memory-memgraph-${tn()}.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 tn(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const w=Object.freeze({available:!0}),T=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),E=an(`Gestures are supported only for Apple simulators and devices.`),nn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:we}),rn=an(`scroll is supported only for Apple simulators and devices.`);function an(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function on(e){return{...ke({unsupported:sn(e),plan:cn(e),directionalFling:cn(e),multiTouch:ln(e),targetAuthoredDrag:un(e),viewport:dn(e)}),...Ie({scroll:fn(e)})}}function sn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?T:E}function cn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?T:D(e)?w:E}function ln(e){if(e.appleOs===`watchos`)return T;if(!D(e))return E;let t=b(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 w}function un(e){return D(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?w:nn:E}function dn(e){return e.appleOs===`watchos`?T:D(e)?w:E}function fn(e){return D(e)?w:rn}function D(e){return e.kind===`simulator`||e.kind===`device`}const O=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function k(e){return v(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const pn=Object.freeze({resourceKind:kt,version:1,encode:e=>({...e}),decode:e=>!hn(e.transport)||!gn(e.backend)||!bn(e.outputPath)||!vn(e.pidPath)||!_n(e.transport,e.backend)?mn():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function mn(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function hn(e){return e===`apple-log-stream`||e===`coredevice-console`}function gn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function _n(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function vn(e){return e===void 0||bn(e)}function yn(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return pe({resourceKind:kt,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:fe(pn,e.descriptor)})}function bn(e){return typeof e==`string`&&e.trim().length>0}const xn={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.`},Sn={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 Cn(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 wn(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(v(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await vt(async()=>gt(await e.appleTools.run({tool:`simctl`,args:Rt(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(O);else{i.devicectlAvailable=await vt(async()=>gt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await Cn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?xn:Sn;a.push(`${e.message} ${e.hint}`)}}return{backend:k(t),checks:i,notes:a}}function Tn(e,t){let n=On(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=On(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 En(e,t){return zt(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,Tn(t.appBundleId,t.executableName)])}function Dn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function On(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}const kn=1e4;async function An(e,t,n,r,i){jn(t),it(e,n);let a=k(t),o=await Nn(e,t,n.appBundleId,i),s=new be,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=Fn(l),d=await Mn(e,t,o,u.sink,n.pidPath,i);s.defer(async()=>{c||await d[Symbol.asyncDispose]()}),t.kind===`simulator`&&await In(e,u.written,d.wait,i);let f=Ln(e,d,l,a,n.outputPath),p={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},m=ct(f,yn({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:p}));return c=!0,m}finally{await s[Symbol.asyncDispose]()}}function jn(e){if(e.appleOs===`watchos`)throw new r(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(y(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new r(`UNSUPPORTED_OPERATION`,O,{hint:O})}async function Mn(e,t,n,i,a,o){if(y(t)&&t.kind===`device`){let t=await Cn(e,o);if(!t.supported){let e=t.reason===`unsupported`?xn:Sn;throw new r(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:n},output:i,...a?{markerPath:a}:{}})}async function Nn(e,t,n,r){return v(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,Tn(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:Dn(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:En(t,{appBundleId:n,executableName:await Pn(e,t,n,r)}),allowFailure:!0}}async function Pn(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:C(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`,`-`,Zt.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function Fn(e){let t=A,n=new Promise(e=>{t=e});return{sink:{write:async n=>{t(),await e.write(n)},[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()},written:n}}async function In(e,t,n,i){i?.throwIfAborted();let a=A,o=new Promise((e,t)=>{a=()=>t(i?.reason),i?.addEventListener(`abort`,a,{once:!0})}),s=new AbortController,c=e.clock.sleep(kn,s.signal).then(()=>`timed-out`);c.catch(A);try{let e=Promise.race([t,n.then(A,A)]).then(()=>`launched`);if(await Promise.race([e,c,o])===`timed-out`)throw new r(`COMMAND_FAILED`,`Simulator log stream did not start within ${kn}ms`,{reason:`simulator-log-stream-launch-timeout`,timeoutMs:kn,hint:`Check that the simulator finished booting, then retry logs start.`})}finally{s.abort(),i?.removeEventListener(`abort`,a)}}function A(){}function Ln(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 rt({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Rn([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 Rn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const j=oe(`apple`),zn=Object.freeze({available:!0});function Bn(e){return Object.freeze({owner:j,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>Hn(e),bind:async t=>{if(t.intent.kind===`exact-owner`&&!ae(t.intent.owner,j))throw new r(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return Vn(e,t.device,t.scope.signal)},shutdown:async()=>void 0})}function Vn(e,t,n){if(t.platform!==`apple`)throw new r(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${t.platform}`);let i=ot({codec:pn,reattach:async(n,r)=>n.backend!==k(t)||!st(e,r.sessionId,n)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await dt(e,n.pidPath),cleanup:async(n,r)=>n.backend===k(t)&&st(e,r.sessionId,n)?await ft(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:k(t)}),appLogDoctor:async({appBundleId:r})=>await wn(e,t,r,n),appLogStart:async r=>await An(e,t,r,j,n),...i});return Object.freeze({device:t,owner:j,facts:Hn(t),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function Hn(e){if(e.appleOs===`watchos`)return Un(e);let t=y(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:O}:zn;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:zn,appLogCleanup:zn}})}function Un(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 Wn(e,t,n,r){let i=k(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=at(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(Kn(t,n,o.dump)){let i=await qn(e,t,n,a.path,r);i&&(o=Gn(s,o,i,n.maxEntries))}return Xn(s,t,n),Yn(s,o.dump),o.dump.entries.length===0&&s.push(Zn(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function Gn(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).`),lt(n.scan,t,r))}function Kn(e,t,n){return y(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function qn(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=C(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,Jn(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:at(`${c.join(`
3
- `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function Jn(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 Yn(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 Xn(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(y(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 Zn(e){return y(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.`:y(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 Qn(e){let{host:t,snapshot:n,targetLabel:r,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`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r})}catch(e){throw i(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return mt(n,{...c,...l.length>0?{warning:l.join(` `)}:{},...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function $n(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 er(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function er(e){try{return await e()}catch(e){throw i(e,`COMMAND_FAILED`)}}const tr=[`outPath`,`startedAt`,`clientOutPath`,..._t],nr=Object.freeze({resourceKind:me,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=>mr(e)});function rr(e){let{device:t,owner:n,input:r,descriptor:i}=e;return pe({resourceKind:me,sessionId:r.sessionId,device:ee(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:fe(nr,i)})}function ir(e){let t={};for(let n of tr)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function ar(e,t,n,r){let i=nr.decode(n);return i.status!==`decoded`||!wr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await or(e,i.descriptor.processes,r):await cr(e,t,i.descriptor)}async function or(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(sr(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(sr(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function sr(e){return{kind:`session`,sessionId:e}}async function cr(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 lr(e){let{host:t,device:n,envelope:r}=e,i=nr.decode(r.descriptor.body);return i.status===`decoded`?wr(n,i.descriptor)?i.descriptor.backend===`simctl`?await ur(e,i.descriptor):await fr(t,n,i.descriptor):M(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):M(`descriptor-invalid`,i.message)}async function ur(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 M(`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=dr(xt(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await pr(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await or(e.host,t.processes,e.envelope.sessionId)}}function dr(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function fr(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:M(`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 pr(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function M(e,t){return{status:`unreattachable`,reason:e,message:t}}function mr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?P():e.backend===`simctl`?hr(e,e.outputPath):e.backend===`runner`?vr(e,e.outputPath):P()}function hr(e,t){let n=Tr(e.processes),r=gr(e.recording);return!n||r===`invalid`?P():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function gr(e){if(e!==void 0)return f(e)&&_r(e)?Object.freeze(e):`invalid`}function _r(e){return N(e.outPath)&&br(e.startedAt)&&yr(e.clientOutPath)&&ht(e)}function vr(e,t){return!N(e.appBundleId)||!N(e.runnerSessionId)||!xr(e.runnerAuthority)||!Sr(e.remotePath)?P():{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 N(e){return typeof e==`string`&&e.length>0}function yr(e){return e===void 0||N(e)}function br(e){return typeof e==`number`&&Number.isFinite(e)}function xr(e){return e===`local-lease`||e===`scoped-provider`}function Sr(e){return e===void 0||Cr(e)}function Cr(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function wr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:y(e)?t.remotePath!==void 0&&Cr(t.remotePath):t.remotePath===void 0:!1}function Tr(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 P(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Er(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 Dr=`iOS recording`,Or=`simctl recordVideo`;function kr(e){return e.appleOs===`watchos`?S(`unsupported-platform-leaf`,`watchOS recording is not supported.`):y(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?S(`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 Ar(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await jr({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await lr({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:Nr({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await ar(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function jr(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Mr(e):await Fr(e)}async function Mr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Er(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=At(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 Br(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 Br(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Lr(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=Ur(i,Or,{},o);return Hr({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:ir(p)},snapshot:p,finish:(e,n)=>yt({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await Pr(t,s,e)}catch(e){throw Rr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await $n({host:t,snapshot:e,targetLabel:Dr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Rr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await Vr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function Nr(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:Or,gestureEvents:[]});return pt(a,{finish:(e,i)=>yt({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 Pr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await $n({host:t,snapshot:e,targetLabel:Dr,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 Pr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Fr(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??=Ir(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!zr(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 Hr({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:Ur(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await Qn({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 Ir(e){try{return await e()}catch(e){throw i(e,`COMMAND_FAILED`)}}function Lr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Rr(e,t,n){let a=i(e,`COMMAND_FAILED`);return t===void 0||n===void 0||a.details?.reason!==`recording-output-unplayable`?e:new r(a.code,`${a.message}; ${t}`,p(n,{...a.details??{},...n.signal===void 0?{}:{signal:n.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 zr(e,t){return e.appleOs===`macos`||!y(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function Br(e){return await e.terminate(),await e.wait}async function Vr(e){try{return await Br(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function Hr(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=pt(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new ye(c),envelope:rr({device:t,owner:n,input:r,descriptor:i})})}function Ur(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}async function F(e,t,n,r={}){return n.throwIfAborted(),v(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await Wr(e,t)?`Booted`:await Yr(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await Gr(e,t,n,r.deadlineAtMs),await Xr(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function Wr(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function Gr(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await Kr(e,t,n,r),await qr(e,t,n,r)}catch(a){throw i&&n.aborted&&Zr(e,t),n.throwIfAborted(),Date.now()>=r?I(t,a):a}}async function Kr(e,t,n,i){let a=await e.appleTools.run({tool:`simctl`,args:C(t,[`boot`,t.id]),allowFailure:!0,timeoutMs:Jr(i,t)},n),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new r(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function qr(e,t,n,i){he({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await e.appleTools.run({tool:`simctl`,args:C(t,[`bootstatus`,t.id,`-b`]),allowFailure:!0,timeoutMs:Jr(i,t)},n);if(a.exitCode!==0)throw new r(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(n.throwIfAborted(),Date.now()>=i)throw I(t)}function Jr(e,t){let n=e-Date.now();if(n<=0)throw I(t);return n}function I(e,t){return new r(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:Ct,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 Yr(e,t,n){return await Yt(e.appleTools,t,n,15e3)}async function Xr(e,t){await e.commands.run({executable:`open`,args:[`-g`,`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function Zr(e,t){e.appleTools.run({tool:`simctl`,args:C(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const Qr=Object.freeze({resolveOpenTarget:`simulator`,prepareApplicationOpen:`simulator`,openApplication:`simulator`,applyRuntimeHints:`simulator`,clearRuntimeHints:`simulator`,closeApplication:`simulator`,finalizeApplicationClose:`simulator`,prepareAppleRunner:`runner`,configureProviderPortReverse:`simulator`,ensureReady:`simulator`,bootTarget:`simulator`,bootTargetHeadless:`simulator`,shutdownTarget:`simulator`,listApps:`simulator`,deployApp:`simulator`,materializeAppSource:`simulator`,deployMaterializedApp:`simulator`,sendPushNotification:`simulator`,uninstallApp:`simulator`,appState:`simulator`,appLogStart:`simulator`,appLogInspect:`simulator`,appLogDoctor:`simulator`,appLogReattach:`simulator`,appLogCleanup:`simulator`,networkDump:`simulator`,audioProbeStart:`simulator`,audioProbeQuery:`simulator`,audioProbeReattach:`simulator`,audioProbeCleanup:`simulator`,readClipboard:`simulator`,writeClipboard:`runner`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`simulator`,sendTelephonyEvent:`simulator`,unlockOrientation:`simulator`,power:`simulator`,volumeDown:`simulator`,volumeUp:`simulator`,mute:`simulator`,sleep:`simulator`,wake:`simulator`,mediaPlayPause:`simulator`,mediaNext:`simulator`,mediaPrevious:`simulator`,mediaRewind:`simulator`,mediaFastForward:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`runner`,querySelector:`runner`,readTextAtPoint:`runner`,tapPoint:`runner`,tapRef:`runner`,tapElementSelector:`runner`,fillPoint:`runner`,fillRef:`runner`,longPressPoint:`runner`,hoverPoint:`runner`,hoverRef:`runner`,focusPoint:`runner`,typeText:`runner`,scrollDirection:`runner`,performGesturePlan:`runner`,performMultiTouchGesturePlan:`runner`,performTargetAuthoredDrag:`runner`,performDirectionalFlingPlan:`runner`,gestureViewport:`runner`,setViewport:`runner`,back:`runner`,home:`runner`,setOrientation:`runner`,appSwitcher:`runner`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function $r(e){return e===void 0?`possible`:e.some(e=>Qr[e]===`runner`)?`required`:`none`}function ei(e){let{waitMs:t,signal:n,stop:r,cancelled:i}=e;return new Promise((e,a)=>{let o=()=>l(()=>a(i())),s=()=>l(e),c=setTimeout(()=>l(e),t);function l(e){clearTimeout(c),n?.removeEventListener(`abort`,o),r?.removeEventListener(`abort`,s),e()}n?.addEventListener(`abort`,o,{once:!0}),r?.addEventListener(`abort`,s,{once:!0}),n?.aborted?o():r?.aborted&&s()})}function ti(e){let t=e.now??Date.now,n=e.waitGrant??`every-caller`,r=new Map,i=(n,i)=>{let a={status:`pending`,value:void 0,error:void 0,settledAtMs:t(),waitSpent:!1,controller:new AbortController,settled:void 0},o=()=>{};a.settled=new Promise(e=>{o=e}),r.set(n,a);let s=(i,s)=>{a.status=i,i===`ready`?a.value=s:a.error=s,a.settledAtMs=t(),(i===`ready`||e.retryAfterMs===void 0)&&r.get(n)===a&&r.delete(n),o()};try{i(a.controller.signal).then(e=>s(`ready`,e),e=>s(`failed`,e))}catch(e){s(`failed`,e)}return a},a=(n,a)=>{let o=r.get(n);if(!o)return i(n,a);if(o.status!==`failed`)return o;let s=t()-o.settledAtMs;return e.retryAfterMs===void 0||s>=e.retryAfterMs?i(n,a):o};return{value:async(t,r)=>{let i=a(t,r.start);if(i.status===`pending`&&(n===`every-caller`||!i.waitSpent)){i.waitSpent=!0;let t=new AbortController,n=r.wait(e.waitMs,t.signal);n.catch(()=>{});try{await Promise.race([i.settled,n])}finally{t.abort()}}if(i.status===`ready`)return i.value;throw i.status===`failed`?i.error:r.pending()},close:()=>{let e=[...r.values()];r.clear();for(let t of e)t.controller.abort()}}}async function ni(e,t){let n=await Pt(`ps`,[`-p`,String(e),`-o`,`lstart=`],{allowFailure:!0,signal:t.signal,timeoutMs:t.timeoutMs});return n.exitCode===0&&n.stdout.trim()||null}const ri=3e3,ii=`simulator-target-discovery-pending`,ai=`simulator-target-unavailable`;function oi(){let e=new Map,t=new Map,n=ti({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 ni(c.pid,{signal:a,timeoutMs:ri});if(a.throwIfAborted(),e===c.processStartTime)return c}return e.delete(s),await n.value(s,{start:async()=>{let n=await ui(r,i,t);return e.set(s,n),n},wait:(e,t)=>ei({waitMs:e,signal:a,stop:t,cancelled:()=>si(a)}),pending:()=>L(ii,r,i)})}}function si(e){return t({readinessPhase:`target-discovery`},e.reason)}function ci(e){return e instanceof r&&e.details?.reason===ii}function li(e){return e instanceof r&&e.details?.reason===ai}async function ui(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([Bt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:pi(r)}),di(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 L(`simulator-target-probe-failed`,e,t);let c=fi(o.stdout,t);if(!c)throw L(ai,e,t);let l=await ni(c.pid,{timeoutMs:Math.min(ri,pi(r))});if(!l)throw L(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:Vt(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function di(e,t,n){let r=t.get(e.id);if(r)return await r;let i=Bt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:pi(n)}).then(t=>{if(t.exitCode!==0)throw L(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(Lt(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw L(`simulator-runtime-unavailable`,e,``);return n});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function fi(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 pi(e){return Math.max(1,e-Date.now())}function L(e,t,n){return new r(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:t.id,appBundleId:n})}function mi(e){return e?.observation===`unobservable`&&e.proof===`no-running-process`}const hi=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function R(e){return e.platform===`apple`&&_(e)}function gi(e){let t=le(de({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!R(n))return{observation:`not-eligible`};let a;for(;;){let o=await vi(e.resolveTarget,n,r,i);if(`verdict`in o)return o.verdict;let{target:s}=o;if(e.isBridgeDisabled(s))return g({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:s.generation}}),_i({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=hi.get(u);if(d===void 0)return _i({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 _i(e){return{observation:`probe-failed`,failure:e}}async function vi(e,t,n,r){for(;;)try{return{target:await e(t,n,r)}}catch(e){if(r.throwIfAborted(),ci(e))continue;if(li(e))return{verdict:{observation:`unobservable`,proof:`no-running-process`}};let{code:t,details:n}=a(e),i=n?.reason;return{verdict:_i(typeof i==`string`?{source:`target`,code:t,reason:i}:{source:`target`,code:t})}}}function yi(e,t,n){let r=n&&R(e),i=r?$r(t.execution.plannedOperations):void 0,a=y(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function bi(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function xi(e,t,n,i,a,o){let s=Date.now(),c=async()=>await Oi(t,n,i,a.observation),l=await c(),u,d,f=a.answerConfirmation,p=f&&l?.observation!==`observable`?await Si(f,a.redispatchLaunchUrl,c,l):void 0;if(p&&(o.runnerDemand=`required`,u=p.report,d=p.probeFailure,l=p.observed,p.unanswered))throw new r(`COMMAND_FAILED`,`The Simulator has not completed the launch URL for ${n.appBundleId}.`,{reason:`launch_confirmation_unanswered`,appBundleId:n.appBundleId,hint:`iOS may still be holding an "Open in" prompt, or the answer died with the runner session that raised it. Inspect the current alert before deciding on another action.`});if(i&&l?.observation!==`observable`&&await e.clock.sleep(300,t.signal),l&&(o.postOpenObservation=l.observation,l.observation===`probe-failed`&&(o.postOpenObservationFailure=l.failure)),o.postOpenSettleDurationMs=Math.max(0,Date.now()-s),u)return u;if(d)return{launchConfirmationProbeFailure:d}}async function Si(e,t,n,r){let i={observed:r,acceptAttempted:!1,confirmationStillPresent:!1};for(let r=0;r<2;r+=1){i=await Ci(e,n,i);let a=r===1;if(i.confirmationStillPresent||a||!Ei(i)||!t)break;await t()}return{observed:i.observed,report:i.report,probeFailure:i.probeFailure,unanswered:Ei(i)||i.confirmationStillPresent}}async function Ci(e,t,n){let r=await e(),i=r.outcome===`unanswered`&&r.reason===`alert-still-present`,a=n.acceptAttempted||Di(r),o=Ti(n,r);return a?{observed:await t(),...o,acceptAttempted:a,confirmationStillPresent:i}:{observed:n.observed,...o,acceptAttempted:a,confirmationStillPresent:i}}function wi(e){switch(e.outcome){case`accepted`:return{seen:{launchConfirmation:`accepted`}};case`absent`:return{};case`unreadable`:return e.step===`url-owner`?{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:`url-owner-unresolved`}}:{probeFailure:e.step};case`unanswered`:return e.reason===`alert-still-present`?{}:{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:e.reason}}}}function Ti(e,t){let n=wi(t);return`seen`in n?{report:n.seen,probeFailure:void 0}:`probeFailure`in n?{report:void 0,probeFailure:n.probeFailure}:{report:e.report,probeFailure:void 0}}function Ei(e){return e.acceptAttempted&&mi(e.observed)}function Di(e){return e.outcome===`accepted`||e.outcome===`unanswered`&&e.reason===`alert-still-present`||e.outcome===`unreadable`&&e.step===`alert-accept`}async function Oi(e,t,n,r){if(!(!n||!R(e.device))&&!(!r||!t.appBundleId))return await r.awaitObservable(e.device,t.appBundleId,e.signal)}let ki;const Ai=()=>ki??=import(`./launch-confirmation.js`);let ji;const Mi=()=>ji??=import(`./expo-dev-client-launch.js`);function Ni(e){let t=t=>Qe({device:t,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve}),n=e.device,r=t(n),i=e=>{n=e,r=t(e)};return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(n,t),prepareApplicationOpen:async t=>{let r=await F(e.host,n,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(n,t.execution,e.signal).catch(()=>{})}:void 0});i(r)},openApplication:async t=>await Pi(e.host,r,t,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(n,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(n,t),closeApplication:async t=>{t.ensureReady&&i(await F(e.host,n,e.signal)),await qi(e.host,r,t)},finalizeApplicationClose:async t=>await Ji(e.host,n,e.signal,t),prepareAppleRunner:async t=>{let r=await Yi(e.host,n,e.signal,t);return i(r.readied),r.prepared},configureProviderPortReverse:ta})}async function Pi(e,t,n,r){let i={},a=z(t.device),o=Xi(e,t,n,i),s=yi(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),bi(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=Ki(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Fi(e,t,n,a,l,i);let u=await Ii(t,n,a,i),d=Qi(t.device,u?{...n,runtimeLaunchUrl:u}:n,a);await Li(o,c,n.prewarmRunnerBeforeOpen);let f=o.wasAwaited();await Ri(t,n,d,a,i),await Ui(o,c,s.awaitPrewarmAfterOpen),await Wi(e,t,n,a,f,l);let p=await xi(e,t,n,a,{observation:r,answerConfirmation:Vi(t,n,d),redispatchLaunchUrl:Hi(t,n,d)},i);return{appBundleId:n.appBundleId,timing:i,...p??{}}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Fi(e,t,n,r,i,a){if(!Gi(n,r)||!n.target)return;let o=Date.now();te(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await $e({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=B(o)}async function Ii(e,t,n,i){if(!_e(t.runtimeHints))return;let a=Date.now(),o=n?await(await Mi()).resolveExpoDevClientLaunchUrl(e.device,t):void 0;if(!o){if(!t.applyRuntimeHints)throw new r(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints})}return i.runtimeHintsDurationMs=B(a),o}async function Li(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Ri(e,t,n,r,i){let a=Date.now();await et({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=B(a),await zi(e,t,n.followUpUrl,i)}async function zi(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i=Date.now();await Bi(e,t,n),r.launchUrlDurationMs=B(i)}async function Bi(e,t,n){let r={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0};await et({device:e.device,interactor:await e.resolveInteractor(r,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:r})}function Vi(e,t,{confirmation:n}){if(n)return async()=>{let{answerSimulatorLaunchConfirmation:r}=await Ai();return await r(e.device,n,e.resolveInteractor(t.execution,n.appBundleId),e.signal)}}function Hi(e,t,{confirmation:n}){if(n)return async()=>{await Bi(e,t,n.url)}}async function Ui(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function Wi(e,t,n,r,i,a){!y(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 Gi(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function Ki(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&Gi(t,n)}async function qi(e,t,n){te(t.device.platform)&&!z(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await $e({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),z(t.device)&&await e.clock.sleep(300,t.signal)}async function Ji(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&&z(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function Yi(e,t,n,r){let i=Date.now()+r.timeoutMs,a=performance.now();return await m(`prepare_apple_runner`,async()=>{let o=await F(e,t,n,{deadlineAtMs:i}),s=Math.max(1,i-Date.now());return g({phase:`prepare_apple_runner`,durationMs:performance.now()-a,data:{event:`runner_start`,timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}}),{readied:o,prepared:await e.appleApplications.prepareRunner(o,{...r,timeoutMs:s},n)}},()=>({timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}),`readiness_start`)}function Xi(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=B(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 Qi(e,t,n){let r=t.runtimeLaunchUrl?.trim(),i=t.positionals.length===1?t.positionals[0]?.trim():void 0;if(!r||!i||d(i))return{positionals:t.positionals};let a=$i(e,t.appBundleId,r),o=a?{confirmation:a}:{};return n&&!ea(t)?{positionals:[i,r],...o}:{positionals:t.positionals,followUpUrl:r,...o}}function $i(e,t,n){if(e.appleOs===`ios`&&e.kind===`simulator`&&!(t===void 0||l(n)))return{url:n,appBundleId:t}}function ea(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function z(e){return y(e)&&e.kind===`simulator`}function B(e){return Math.max(0,Date.now()-e)}async function ta(){throw new r(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const na=Object.freeze({available:!0}),ra=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.`}),ia=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),aa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),oa=Object.freeze({available:!1,reason:`unsupported-device-kind`});function sa(e){let t=ga(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:_a(e),uninstallApp:t})}function ca(e){let{host:t,device:n,signal:r}=e,i=sa(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await la(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await da(t,n,e,r),uninstallApp:async e=>await ua(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await ma(t,n,e,r),{})}:{}})}async function la(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await pa(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await fa(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 da(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function ua(e,t,n,i){return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{await F(e,t,i);let a;try{a=await e.appleDeployment.resolveAppBundleId(t,n.app,{installedOnly:!0})}catch(e){if(e instanceof r&&e.code===`APP_NOT_INSTALLED`&&n.app.trim().includes(`.`))return{wasInstalled:!1};throw e}return await pa(e,t,a,i),{wasInstalled:!0,bundleId:a}})}async function da(e,t,n,r){return await fa(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 fa(e,t,n,r){await F(e,t,r),await ha(e,t.kind===`simulator`?{tool:`simctl`,args:C(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:jt},r,`Apple app install failed`)}async function pa(e,t,n,r){await F(e,t,r),await ha(e,t.kind===`simulator`?{tool:`simctl`,args:C(t,[`uninstall`,t.id,n])}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n]},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>It(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function ma(e,t,n,i){if(t.kind!==`simulator`)throw new r(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await F(e,t,i);let a=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(n.payload)}\n`),await ha(e,{tool:`simctl`,args:C(t,[`push`,t.id,n.appId,a.path])},i,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}async function ha(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:h(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:Ft(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function ga(e){return va(e)?e.kind!==`simulator`&&e.kind!==`device`?oa:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?ra:na:aa}function _a(e){return va(e)?e.kind===`simulator`?na:ia:aa}function va(e){return y(e)&&e.appleOs!==`watchos`}const V=Object.freeze({available:!0}),ya=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),ba=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function xa(e){return e.kind!==`simulator`&&e.kind!==`device`?ya:b(e)===`watchos`?ba:V}const Sa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),Ca=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),wa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function Ta(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=b(e);return n===`macos`||n===`watchos`?Ca:V}function H(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=b(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const Ea=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),Da=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Oa(e){return e.kind!==`simulator`&&e.kind!==`device`?Ea:H(e)?V:Da}const ka=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function Aa(e){return(e.kind===`simulator`||e.kind===`device`)&&ne(e)?V:ka}const U=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ja=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 Ma(e){return H(e)?ja:U}function Na(e){return H(e)?V:U}function Pa(e){return H(e)?V:U}const Fa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Ia=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),La=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 Ra(e){return e.kind!==`simulator`&&e.kind!==`device`?Ia:re(e)?V:La}const za=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`hardware-button volume presses the iPhone/iPad volume key; this Apple leaf has none.`}),Ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button volume is supported on physical iPhone and iPad; iOS Simulators refuse because XCUIDevice exposes no volume press there.`});function Va(e){return re(e)?e.kind===`device`?V:Ba:za}function Ha(e){return Object.freeze({...Ee({back:xa(e)}),...He({unsupported:Fa,home:Ta(e,Sa),appSwitcher:Ta(e,wa),actionButton:Ra(e),volumeUp:Va(e),volumeDown:Va(e)}),...Ke({orientation:Oa(e)}),...Ye({tvRemote:Aa(e),buttonSupport:{supported:c(`apple`),unsupported:{available:!1,reason:`unsupported-platform-leaf`,hint:`This TV remote button is not supported on tvOS.`}}}),...Ge({unsupported:U,status:Ma(e),dismiss:Na(e),enter:Pa(e)})})}function Ua(e){let{host:t,device:n,signal:r,admitted:i}=e,a=Object.keys(Ha(n));return nt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Object.fromEntries(a.map(e=>[e,i[e]]))})}const W=Object.freeze({available:!0}),Wa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),Ga=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.`}),qa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Run `agent-device settings --help` for the settings each target serves."}),Ja=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The macOS host supports settings appearance and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>.`}),Ya=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Select a booted iPhone or iPad simulator: this setting runs only there.`}),Xa=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.`}),Za=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Qa(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=b(e);return r===`watchos`?Za:e.kind===`simulator`||r===`macos`?W:n}const $a=Object.freeze({available:!1,reason:`unsupported-device-scope`,hint:`This session holds one app of the Mac. Use a --surface desktop session for the clipboard and host settings.`});function eo(e){return e.hostApp?$a:Qa(e,Wa,Xa)}const to=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),no=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),ro=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function io(e){if(e.kind!==`simulator`&&e.kind!==`device`)return no;let t=b(e);return t===`watchos`?Za:e.kind===`simulator`||t===`ios`||t===`macos`?W:ro}function ao(e){return e.kind!==`simulator`&&e.kind!==`device`?to:b(e)===`watchos`?Za:W}function oo(e){let t=eo(e);return t.available?Xa:t}function so(e){let t=e.hostApp?$a:Qa(e,Ga,Ka);if(v(e))return tt({target:t,unsupported:Ja,write:{appearance:W,permission:W}});let n=_(e)?W:Ya;return tt({target:t,unsupported:qa,write:{wifi:W,airplane:W,location:W,appearance:W,"clear-app-state":W,"reset-keychain":W,permission:W,"text-size":n,faceid:n,touchid:n},read:{"text-size":n}})}function co(e){let t=eo(e),n=io(e);return Object.freeze({...qe({unsupported:oo(e),read:t,write:t}),...Ze({read:n,wait:n,accept:n,dismiss:n}),...Xe({triggerAppEvent:ao(e)}),...so(e)})}function lo(e){let{host:t,device:n,signal:r}=e;return nt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:co(n)})}async function uo(e,t,n={}){n.signal?.throwIfAborted(),Wt(e,`fold`);let r=t,i=r.keyframes?.at(-1)?.angle,a=r.pose??s(i),o=Kt(e);mo(e,await Gt(e,{signal:n.signal,foldHelper:o})),await o.setPose(r.keyframes??a,n.signal),g({level:`info`,phase:`apple_fold_pose_dispatched`,data:{deviceId:e.id,pose:a}});let c=await ho(e,o,a,n.signal,i),l=await wo(e,o,n.signal);return{pose:s(c),hingeAngleDegrees:c,...l?{screen:To(l)}:{}}}function fo(e){return e instanceof r&&e.details?.reason===`fold-hinge-angle-no-sample`}async function po(e,t,n,i,a,o){let s=await wo(e,t,i);return new r(`COMMAND_FAILED`,`${e.name} received the ${n} pose request, but the first hinge-angle read returned no sample to verify it`,{deviceId:e.id,requestedPose:n,...a===void 0?{}:{targetAngleDegrees:a},reason:`fold-pose-dispatched-unverified`,...s?{screen:To(s)}:{},...o instanceof r?{hingeReadFailure:o.details}:{},hint:`The pose request was sent and the device may have followed it, but the first hinge-angle read returned no sample, so fold cannot confirm it. Take a screenshot or snapshot to see which panel is lit; hingeReadFailure names why the read failed.`},o)}function mo(e,t){if(t.unresolved)throw new r(`COMMAND_FAILED`,`The simulator reported no panel table`,{deviceId:e.id,hint:`fold needs the simulator's panel table to tell a foldable from a single-panel simulator: 'devicectl device info displays' in the default device set, or the fold helper's guest panel read in a scoped set. The apple_display_inventory_unresolved diagnostic names why the read failed.`});if(!t.multiScreen)throw new r(`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 ho(e,t,n,r,i){let a,o;for(let s=1;s<=8;s+=1){r?.throwIfAborted(),o=a;try{a=await t.readHingeAngle({signal:r,windowMs:s>1?Mt:0})}catch(o){throw a!==void 0||!fo(o)?o:await po(e,t,n,r,i,o)}if(go(a,o,n,i))return a}throw yo(e,n,a,o,i)}function go(e,t,n,r){return r===void 0?s(e)===n?n!==`half-open`||t!==void 0&&bo(e,t):!1:_o(e,t,r)}function _o(e,t,n){return vo(e,n)?n===0||n===180||t!==void 0&&vo(t,n)&&Math.abs(e-t)<=.5:!1}function vo(e,t){return t===void 0||e!==void 0&&Math.abs(e-t)<=.5}function yo(e,t,n,i,a){return vo(n,a)?a!==void 0&&n!==void 0?Co(e,s(n),n,i):n!==void 0&&t===`half-open`&&s(n)===t?Co(e,t,n,i):So(e,t,n):new r(`COMMAND_FAILED`,`The hinge did not reach the final keyframe angle`,{reason:`fold-angle-unverified`,targetAngleDegrees:a,hingeAngleDegrees:n,deviceId:e.id})}function bo(e,t){return s(e)===`half-open`&&s(t)===`half-open`&&Math.abs(e-t)<=.5}function xo(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:s(n),hingeAngleDegrees:n}}function So(e,t,n){return new r(`COMMAND_FAILED`,`${e.name} did not reach the ${t} pose: the simulator still reports a hinge angle of ${n}°`,{...xo(e,t,n),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 Co(e,t,n,i){return new r(`COMMAND_FAILED`,`${e.name} was observed ${t} at ${n}° but did not settle: 8 hinge reads never held two consecutive angles within ${Nt}° of each other`,{...xo(e,t,n),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 to see whether the simulator holds the pose.`})}async function wo(e,t,n){let r=await Gt(e,{signal:n,foldHelper:t});if(!(r.unresolved||r.ambiguous))return r.activeDisplay}function To(e){return{display:e.name,coordinateSpace:o,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const Eo=Object.freeze({available:!0}),Do=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.`}),Oo=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 ko(e){if(e.kind!==`simulator`)return Do;let t=b(e);return t!==`ios`&&t!==`ipados`?Oo:Eo}function Ao(e){return St({fold:ko(e)})}function jo(e){let{device:t,signal:n}=e;return x(Ao(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await uo(t,e,{signal:n}))}))}function Mo(e,t,n){let r=We({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(i.options?.observeOnly===!0)return await r.captureSnapshot(i);let a=v(t.device)?ce(i.options?.surface,t.appBackend):void 0;if(a)return await e.snapshot.captureSurface(t.device,{...i.options,surface:a},Ue(t.signal,i));if(!n)return await r.captureSnapshot(i);let o=Ue(t.signal,i);return await n.capture(t.device,i,o,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function No(e,t){return Object.freeze({findText:async n=>{let r=await Po(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 Po(e,t,n){let r=n.options?.appBundleId;if(r===void 0||v(t.device)&&se(n.options?.surface,t.appBackend)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await Fo(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function Fo(e,t,n){return!R(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Io(e){return Object.freeze({querySelector:async t=>{let n=t.signal?AbortSignal.any([e.signal,t.signal]):e.signal;n.throwIfAborted();let r={...t.execution,signal:n},{queryAppleRunnerSelector:i}=await import(`./runner-selector-query.js`),a=await i(e.device,t.selector,t.options?.appBundleId,r),o=Lo(a);return Object.freeze({found:a.found===!0,...o?{node:o}:{}})}})}function Lo(e){let t=e.nodes;if(!Array.isArray(t))return;let n=t[0];if(!n||typeof n!=`object`)return;let r=u(n.rect);if(r)return Object.freeze({rect:r,hittable:n.hittable===!0})}const G=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.`});function Ro(e,t){return!v(e)||t!==`native`?{}:Object.freeze({screenRecordingStart:G,screenRecordingReattach:G,prepareAppleRunner:G,longPressPoint:G,...Ee({back:G}),...ke({unsupported:G})})}function zo(e){let t,n=!1,r=async()=>(t??=import(`./host3.js`).then(e=>e.t).then(({createSnapshotSourceHost:t})=>import(`./adapter.js`).then(({createSimulatorSnapshotSource:n})=>n({host:t(e)}))),await t);return{acquire:async e=>n?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await r()).acquire(e),close:async()=>{n=!0,t&&await(await t).close()}}}const Bo=new Set([`notRunning`,`runningBackground`,`runningBackgroundSuspended`]);function Vo(){return async(e,t)=>{let n=Ut(e.id);if(!n||n.liveness!==`ready`)return`unknown`;for(let r of Ce){let i=await Ho(e,r.bundleId,n.sessionId,t);if(i===`runningForeground`)return{kind:`foreground`,host:r};if(i===void 0||!Bo.has(i))return`unknown`}return`background`}}async function Ho(t,n,r,i){try{let a=(await Ht(t,{command:`appState`,appBundleId:n},{signal:AbortSignal.any([i.signal,AbortSignal.timeout(1e3)]),expectedRunnerSessionId:r,...i.requestId?{requestId:i.requestId}:{}})).applicationState;return e(a)?a:void 0}catch{i.signal.throwIfAborted();return}}function Uo(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 Wo(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function Wo(e,t){let n=await Promise.all(Ce.map(async e=>({host:e,pids:await Go(e.processExecutable,t)}))),r=!1;for(let{host:i,pids:a}of n){if(a===`unknown`){r=!0;continue}for(let n of a){let a=await Ko(n,e.id,t);if(a===`unknown`)r=!0;else if(a)return{kind:`present`,host:i}}}return r?`unknown`:`absent`}async function Go(e,t){let n=await qo(`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 Ko(e,t,n){let r=await qo(`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 qo(e,t,n){try{let r=await Pt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Jo=new Map([[`window-coordinate-space-unresolved`,`coordinate-space-unresolved`],[`app-window-not-full-screen`,`window-not-full-screen`],[`foreground-owner-unverified`,`foreground-ownership`],[`foreground-owner-changed`,`foreground-ownership`]]);function Yo(e){if(e.kind===`preparing`)return{scope:`capture`,code:e.code,consequence:`bridge-preparation`};let t=Jo.get(e.code);return t?{scope:`capture`,code:e.code,consequence:t}:{scope:`generation`,code:e.code}}const Xo=`system-surface-presented`,Zo=`system-surface-host-lingering`;function Qo(e,t={}){let n=t.source??zo(e.hostEnvironment),i=t.resolveTarget??oi(),a=t.systemSurfacePresent??Uo(),o=t.systemSurfaceForeground??Vo(),s=new Set,c=new Map,l=e=>(ms(e,c,s),s.has(hs(e))),u=gi({source:n,resolveTarget:i,clock:e.clock,isBridgeDisabled:l});return Object.freeze({awaitObservable:u.awaitObservable,shutdown:async()=>await n.close(),capture:async(t,c,u,d)=>{if(!ns(t,c))return await as(t,c,d);let f=await $o(t,c,u,o);if(f!==`background`&&f!==`unknown`)return await is(t,c,d,f.host.bundleId);let p=f===`background`?`absent`:await a(t,u);if(p===`unknown`)return await K(t.id,c,d,ss(t.id,c),q(c),`system-surface-probe-unavailable`,[ps()]);if(p!==`absent`)return await is(t,c,d,p.host.bundleId);let h;try{h=await es(e,i,t,c,u)}catch(e){return ts(u,e),J(`target-resolution-failed`,t,void 0,e),await K(t.id,c,d,ss(t.id,c),q(c),`target-resolution-failed`,[ps()])}if(l(h))return J(`circuit-disabled`,t,h.generation),await K(t.id,c,d,h,q(c),`circuit-disabled`);let g=q(c),_=await n.acquire({target:h,hint:le(g),signal:u});if(_.stage===`failed`){if(_.failure.kind===`cancelled`)throw u.throwIfAborted(),new r(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:_.failure.code,..._.failure.details});let e=await fs(_.failure,h,t,c.options.appBundleId,u,i);return await rs(c,d,h,e,g,_.failure,s)}try{return await m(`ios.snapshot-source.present`,async()=>await e.snapshot.presentIosAcquisition(_,c.options),{producer:`simulator-ax-bridge`})}catch(e){return await rs(c,d,h,{lineage:h,residue:[]},g,{kind:`malformed-tree`,code:`presentation-invariant`},s,e)}}})}async function $o(e,t,n,r){let i=t.execution?.requestId,a=await r(e,{signal:n,...i?{requestId:i}:{}});return a===`background`&&g({level:`debug`,phase:`ios_snapshot_route_surface_host_background`,data:{deviceId:e.id}}),a}async function es(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!ci(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function ts(e,t){if(e.aborted)throw n(t)?t:e.reason}function ns(e,t){return R(e)&&!!t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0}async function rs(e,t,n,r,i,a,o,s){let c=Yo(a);return c.scope===`generation`&&o.add(hs(n)),J(a.code,{id:n.simulator.udid},n.generation,s,a.details),await K(n.simulator.udid,e,t,r.lineage,i,c,r.residue)}async function K(e,t,n,r,i,a,o=[]){return os(e,await n(t),r,i,a,o)}async function is(e,t,n,r){let i=await n(t),a=i.systemSurface?Xo:Zo;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),os(e.id,i,ss(e.id,t),q(t),a)}async function as(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:ls(cs(e.id,i.bundleId),q(t),[])}:r}function os(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:ls(o?cs(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],us(i,n,o!==void 0)]}}function ss(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function cs(e,t){return{targetId:`${e}:${t}`}}function ls(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 us(e,t,n){if(e===Xo)return`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`;if(e===Zo)return`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`;let r=typeof e==`string`?e:e.code;return n?`Simulator AX snapshot unavailable (${r}); used XCTest, which read the system surface presented over the app.`:typeof e!=`string`&&e.scope===`capture`?ds(r,e.consequence):`Simulator AX snapshot unavailable (${r}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}function ds(e,t){let n=`Simulator AX snapshot unavailable (${e}); used XCTest for this capture`;switch(t){case`bridge-preparation`:return`${n} while the bridge is still being prepared.`;case`foreground-ownership`:return`${n}, while another surface owned the foreground.`;case`window-not-full-screen`:return`${n}, while the app window did not fill the screen; the runner republishes a windowed capture in screen space.`;case`coordinate-space-unresolved`:return`${n}, which reports captured geometry in the app's own orientation space.`}}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:[ps()]}}}function ps(){return{kind:`unknown-generation`,captureId:Xt()}}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 ms(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 hs(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){g({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=oe(`apple`),X=Object.freeze({available:!0}),Z=S(`unsupported-platform-leaf`),gs=S(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`),_s=S(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`),vs=S(`unsupported-device-backend`,`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`),ys=S(`unsupported-device-kind`,`focus is supported on Apple simulators and physical devices.`),bs=S(`unsupported-platform-leaf`,`telephony simulates calls and SMS through the Android emulator console; Apple simulators and devices expose no host control that injects a call or text message.`),xs=S(`unsupported-platform-leaf`,`Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`);function Ss(e){return!y(e)||e.appleOs===`watchos`?xs:e.kind===`simulator`||e.kind===`device`?X:xs}const Cs=S(`unsupported-provider-mode`,`Headless boot is supported only for local Android emulators.`),ws=S(`unsupported-platform-leaf`,`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`),Ts=S(`unsupported-device-kind`),Es=S(`unsupported-platform-leaf`,`watchOS open is not supported because XCUITest cannot drive watchOS UI.`),Ds=S(`unsupported-platform-leaf`,`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`),Os=S(`unsupported-platform-leaf`,`watchOS close is not supported because XCUITest cannot drive watchOS UI.`),ks=S(`unsupported-device-kind`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),As=Q(`open is supported only for Apple simulators and devices.`),js=Q(`prepare is supported only for Apple simulators and devices.`),Ms=Q(`close is supported only for Apple simulators and devices.`),Ns=S(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),Ps=S(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),Fs=Q(`snapshot is supported only for Apple simulators and devices.`),Is=S(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),Ls=S(`unsupported-platform-leaf`,`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`),Rs=Q(`screenshot is supported only for Apple simulators and devices.`),zs=S(`owner-capability-missing`,`Open the app under test before capturing its snapshot.`);function Q(e){return S(`unsupported-device-kind`,e)}function Bs(e){return!y(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:Ps}function Vs(e){let t=Hs(e),n=Us(e),r=Ws(e),i=Gs(e);return ve({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:Ns})}function Hs(e){return b(e)===`watchos`?Es:e.kind===`simulator`||e.kind===`device`?X:As}function Us(e){return b(e)===`watchos`?Ds:e.kind===`simulator`||e.kind===`device`?X:js}function Ws(e){return b(e)===`watchos`?Os:e.kind===`simulator`||e.kind===`device`?X:Ms}function Gs(e){return b(e)!==`watchos`&&y(e)&&e.kind===`simulator`?X:ks}function Ks(e){return e.appleOs===`watchos`?S(`unsupported-platform-leaf`,`watchOS app inventory is not supported.`):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?S(`unsupported-device-backend`,`App inventory is available only on CoreDevice-backed physical iOS devices.`):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:ys}function qs(e){let t=Bn(e),n=Qo(e),r,i=t=>v(t)?r??=Jt(e.hostEnvironment.env):`xctest`,a=async n=>{let r=await t.inspectFacts(n),a=sa(n),o=kr(n),s=o.available?await e.screenRecording.apple.availability(n):void 0,c=o.available&&s?.available===!1?S(`unsupported-provider-mode`,s.hint):o,l=n.appleOs===`watchos`?Z:X,u=v(n)||n.appleOs===`watchos`?Z:X,d=Ks(n);return Object.freeze({device:r.device,operations:{...r.operations,...a,appState:Ss(n),networkDump:X,screenRecordingStart:c,screenRecordingReattach:c,screenRecordingCleanup:c,...Qs(n),...Oe({capture:Zs(n)}),...je({findText:Xs(n),querySelector:y(n)?$(n):Z}),...Fe({setViewport:gs}),...Be({focus:$(n)}),...on(n),...Me({type:$(n)}),...xe({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...y(n)?{tapElementSelector:$(n)}:{}}),...Ve({readTextAtPoint:Ys(n)}),...Ha(n),...Ao(n),sendTelephonyEvent:bs,...co(n),...Te({capture:$t(n),query:_s}),...Pe(Js(n)),ensureReady:l,bootTarget:u,bootTargetHeadless:Cs,listApps:d,...Vs(n),shutdownTarget:Bs(n),...Ro(n,i(n))}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:a,bind:async r=>{let o=await t.bind(r),s=await a(r.device),c=s.operations.screenRecordingStart,l=x(s.operations.appState,()=>Qt(e,{device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),u=x(s.operations.querySelector,()=>Io({device:r.device,signal:r.scope.signal})),d={...l,...u,...o.operations,...ca({host:e,device:r.device,signal:r.scope.signal}),networkDump:async t=>await Wn(e,r.device,t,r.scope.signal),...x(c,()=>Ar({host:e,device:r.device,owner:Y,signal:r.scope.signal})),...x(s.operations.audioProbeStart,()=>ut({host:e.audioProbe.hostCapture,device:r.device,owner:Y})),...x(s.operations.perfFrames,()=>en({resolveHost:()=>e.perf.apple,device:r.device,owner:Y})),...x(s.operations.captureSnapshot,()=>Mo(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)},n)),...x(s.operations.captureScreenshot,()=>Ne({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...x(s.operations.focusPoint,()=>Je({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...Re({device:r.device,signal:r.scope.signal,facts:s.operations,resolveInteractor:e.localInteractors.resolve}),...x(s.operations.scrollDirection,()=>Le({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...x(s.operations.typeText,()=>De({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...x(s.operations.tapPoint,()=>Se({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:s.operations,pause:async t=>await e.clock.sleep(t,r.scope.signal)})),...x(s.operations.readTextAtPoint,()=>ze({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...x(s.operations.findText,()=>No(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)})),...Ua({host:e,device:r.device,signal:r.scope.signal,admitted:s.operations}),...lo({host:e,device:r.device,signal:r.scope.signal}),...jo({device:r.device,signal:r.scope.signal}),...x(s.operations.ensureReady,()=>({ensureReady:async()=>await F(e,r.device,r.scope.signal)})),...x(s.operations.bootTarget,()=>({bootTarget:async t=>await F(e,r.device,r.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...x(s.operations.listApps,()=>({listApps:async e=>{r.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...ge(Ni({host:e,device:r.device,signal:r.scope.signal,observation:n}),s.operations),...x(s.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(r.device,r.scope.signal)}))};return Object.freeze({device:o.device,owner:Y,facts:s,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Js(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&b(e)!==`watchos`?X:vs;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Ys(e){return b(e)===`watchos`?ws:e.kind===`simulator`||e.kind===`device`?X:Ts}function Xs(e){return b(e)===`watchos`?Fs:e.kind===`simulator`||e.kind===`device`?X:Fs}function Zs(e){return b(e)===`watchos`?Ls:e.kind===`simulator`||e.kind===`device`?X:Rs}function Qs(e){let t=Xs(e);return Ae({capture:t,customActions:t.available&&y(e)&&e.kind===`simulator`?X:Is,withoutActiveApp:y(e)?zs:t})}export{qs as createApplePlatformRuntime,ti as n,ei as r,ni as t};
1
+ import{E as e,H as t,Q as n,R as r,V as i,tt as a}from"./sdk-contracts.js";import{l as o}from"./tv-remote.js";import{a as s,b as c,i as l,v as u}from"./sdk-batch-runner.js";import{K as d,St as f,Y as p,_t as m}from"./sdk-io.js";import"./diagnostics.js";import{C as h,T as g,U as _,b as ee,j as te,p as ne,w as v,z as y}from"./sdk-device.js";import{Cn as re,Sn as b,bn as ie,hn as ae,xn as x}from"./sdk-batch.js";import{i as oe,r as se}from"./session.js";import"./command.js";import{i as ce,n as le,r as ue}from"./ios-snapshot-planning.js";import{i as de,n as fe}from"./durable-resource.js";import{n as pe}from"./screen-recording-runtime.js";import{t as me}from"./request.js";import{n as he,r as ge,t as _e}from"./application-lifecycle-runtime.js";import{n as ve,t as ye}from"./async-lifecycle.js";import{i as be,t as xe}from"./touch-runtime.js";import{t as Se}from"./ios-system-surface.js";import{r as Ce}from"./gesture-admission.js";import{B as we,C as Te,E as Ee,I as De,K as Oe,M as ke,N as Ae,O as je,P as Me,R as Ne,T as Pe,U as Fe,V as Ie,W as Le,X as Re,Y as ze,Z as Be,_ as Ve,j as He,k as Ue,l as We,o as Ge,p as Ke,q as qe,r as Je,v as Ye,x as Xe}from"./tv-remote-runtime.js";import{n as Ze,o as Qe,s as $e,u as et}from"./application-lifecycle-interaction.js";import{t as tt}from"./interactor-operation-catalog.js";import{a as nt,i as rt,n as it,o as at,r as ot,s as st,t as ct}from"./network-traffic.js";import{a as lt,i as ut,r as dt}from"./src4.js";import{n as ft,t as pt}from"./screen-recording-completion.js";import{a as mt,c as ht,i as gt,n as _t,o as vt,r as yt,s as bt,t as xt}from"./device-readiness-runtime.js";import{a as St,i as Ct,n as wt,r as Tt,t as Et}from"./perf-runtime-operation-builder.js";import{t as Dt}from"./app-log-runtime.js";import{n as Ot}from"./artifact-paths.js";import{a as kt}from"./config.js";import{a as At}from"./tool-provider.js";import{o as jt}from"./devicectl.js";import{i as Mt}from"./physical-device-control.js";import{a as Nt,c as Pt,n as Ft,o as It,s as S,u as Lt}from"./simctl.js";import{c as Rt,u as zt}from"./runner-client.js";import{i as Bt,n as Vt,r as Ht,t as Ut}from"./app-backend.js";import{t as Wt}from"./simulator-state.js";import{randomUUID as Gt}from"node:crypto";import Kt from"node:path";function qt(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 re(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function Jt(e){return e.hostApp?Object.freeze({available:!1,reason:`unsupported-device-scope`,hint:`This session holds one app of the Mac. Use a --surface desktop session for audio probe.`}):vt(e)?Object.freeze({available:!0}):g(e)||v(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 Yt(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Et({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 Ct(t().sampleFrames(n,e)):wt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await Ct(t().sampleMemory(n,e)):wt(`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 St(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw Tt();let c=i??Kt.join(a,`memory-memgraph-${Xt()}.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 Xt(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const C=Object.freeze({available:!0}),w=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),T=$t(`Gestures are supported only for Apple simulators and devices.`),Zt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Ce}),Qt=$t(`scroll is supported only for Apple simulators and devices.`);function $t(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function en(e){return{...Oe({unsupported:tn(e),plan:nn(e),directionalFling:nn(e),multiTouch:rn(e),targetAuthoredDrag:an(e),viewport:on(e)}),...Fe({scroll:sn(e)})}}function tn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?w:T}function nn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?w:E(e)?C:T}function rn(e){if(e.appleOs===`watchos`)return w;if(!E(e))return T;let t=y(e);if(t!==`ios`&&t!==`ipados`){let e=Bt[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return C}function an(e){return E(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?C:Zt:T}function on(e){return e.appleOs===`watchos`?w:E(e)?C:T}function sn(e){return E(e)?C:Qt}function E(e){return e.kind===`simulator`||e.kind===`device`}const D=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function O(e){return g(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const cn=Object.freeze({resourceKind:Dt,version:1,encode:e=>({...e}),decode:e=>!un(e.transport)||!dn(e.backend)||!hn(e.outputPath)||!pn(e.pidPath)||!fn(e.transport,e.backend)?ln():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function ln(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function un(e){return e===`apple-log-stream`||e===`coredevice-console`}function dn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function fn(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function pn(e){return e===void 0||hn(e)}function mn(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return fe({resourceKind:Dt,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:de(cn,e.descriptor)})}function hn(e){return typeof e==`string`&&e.trim().length>0}const gn={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.`},_n={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 vn(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 yn(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(g(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await ht(async()=>bt(await e.appleTools.run({tool:`simctl`,args:Pt(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(D);else{i.devicectlAvailable=await ht(async()=>bt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await vn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?gn:_n;a.push(`${e.message} ${e.hint}`)}}return{backend:O(t),checks:i,notes:a}}function bn(e,t){let n=Cn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=Cn(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 xn(e,t){return Ft(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,bn(t.appBundleId,t.executableName)])}function Sn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function Cn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}const wn=1e4;async function Tn(e,t,n,r,i){En(t),rt(e,n);let a=O(t),o=await On(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=An(l),d=await Dn(e,t,o,u.sink,n.pidPath,i);s.defer(async()=>{c||await d[Symbol.asyncDispose]()}),t.kind===`simulator`&&await jn(e,u.written,d.wait,i);let f=Mn(e,d,l,a,n.outputPath),p={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},m=st(f,mn({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:p}));return c=!0,m}finally{await s[Symbol.asyncDispose]()}}function En(e){if(e.appleOs===`watchos`)throw new r(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(v(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new r(`UNSUPPORTED_OPERATION`,D,{hint:D})}async function Dn(e,t,n,i,a,o){if(v(t)&&t.kind===`device`){let t=await vn(e,o);if(!t.supported){let e=t.reason===`unsupported`?gn:_n;throw new r(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:n},output:i,...a?{markerPath:a}:{}})}async function On(e,t,n,r){return g(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,bn(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:Sn(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:xn(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:S(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`,`-`,Kt.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function An(e){let t=k,n=new Promise(e=>{t=e});return{sink:{write:async n=>{t(),await e.write(n)},[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()},written:n}}async function jn(e,t,n,i){i?.throwIfAborted();let a=k,o=new Promise((e,t)=>{a=()=>t(i?.reason),i?.addEventListener(`abort`,a,{once:!0})}),s=new AbortController,c=e.clock.sleep(wn,s.signal).then(()=>`timed-out`);c.catch(k);try{let e=Promise.race([t,n.then(k,k)]).then(()=>`launched`);if(await Promise.race([e,c,o])===`timed-out`)throw new r(`COMMAND_FAILED`,`Simulator log stream did not start within ${wn}ms`,{reason:`simulator-log-stream-launch-timeout`,timeoutMs:wn,hint:`Check that the simulator finished booting, then retry logs start.`})}finally{s.abort(),i?.removeEventListener(`abort`,a)}}function k(){}function Mn(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 nt({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Nn([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 Nn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const A=ae(`apple`),Pn=Object.freeze({available:!0});function Fn(e){return Object.freeze({owner:A,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>Ln(e),bind:async t=>{if(t.intent.kind===`exact-owner`&&!ie(t.intent.owner,A))throw new r(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return In(e,t.device,t.scope.signal)},shutdown:async()=>void 0})}function In(e,t,n){if(t.platform!==`apple`)throw new r(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${t.platform}`);let i=at({codec:cn,reattach:async(n,r)=>n.backend!==O(t)||!ot(e,r.sessionId,n)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await ut(e,n.pidPath),cleanup:async(n,r)=>n.backend===O(t)&&ot(e,r.sessionId,n)?await dt(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:O(t)}),appLogDoctor:async({appBundleId:r})=>await yn(e,t,r,n),appLogStart:async r=>await Tn(e,t,r,A,n),...i});return Object.freeze({device:t,owner:A,facts:Ln(t),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function Ln(e){if(e.appleOs===`watchos`)return Rn(e);let t=v(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:D}:Pn;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:Pn,appLogCleanup:Pn}})}function Rn(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 zn(e,t,n,r){let i=O(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=it(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(Vn(t,n,o.dump)){let i=await Hn(e,t,n,a.path,r);i&&(o=Bn(s,o,i,n.maxEntries))}return Gn(s,t,n),Wn(s,o.dump),o.dump.entries.length===0&&s.push(Kn(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function Bn(e,t,n,r){let i=n.scan.dump.entries.length;return i===0&&(n.scan.dump.unnamedRequests??0)===0?(n.lineCount>0&&e.push(`Recovered ${n.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`),t):(i>0&&e.push(`Recovered ${i} iOS simulator HTTP entr${i===1?`y`:`ies`} from simctl log show (${n.lineCount} app log lines scanned).`),ct(n.scan,t,r))}function Vn(e,t,n){return v(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function Hn(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=S(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,Un(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:it(`${c.join(`
3
+ `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function Un(e){let t=e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function Wn(e,t){let n=t.entries.filter(e=>e.pathUnavailable).length,r=t.unnamedRequests??0,i=n+r;if(i===0)return;let a=[`${i} request${i===1?``:`s`} reused a keep-alive connection, so CFNetwork logged no request URL.`];n>0&&a.push(`${n} listed against the origin the connection was opened for, without a path.`),r>0&&a.push(`${r} opened before this scan window and are missing from the entries entirely; scan more lines, or run logs clear --restart before the repro.`),a.push(`Absence of an endpoint in this dump does not prove it was not called.`),e.push(a.join(` `))}function Gn(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(v(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 Kn(e){return v(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.`:v(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 qn(e){let{host:t,snapshot:n,targetLabel:r,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`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r})}catch(e){throw i(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return pt(n,{...c,...l.length>0?{warning:l.join(` `)}:{},...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function Jn(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 Yn(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function Yn(e){try{return await e()}catch(e){throw i(e,`COMMAND_FAILED`)}}const Xn=[`outPath`,`startedAt`,`clientOutPath`,...gt],Zn=Object.freeze({resourceKind:pe,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=>lr(e)});function Qn(e){let{device:t,owner:n,input:r,descriptor:i}=e;return fe({resourceKind:pe,sessionId:r.sessionId,device:_(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:de(Zn,i)})}function $n(e){let t={};for(let n of Xn)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function er(e,t,n,r){let i=Zn.decode(n);return i.status!==`decoded`||!yr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await tr(e,i.descriptor.processes,r):await rr(e,t,i.descriptor)}async function tr(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(nr(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(nr(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function nr(e){return{kind:`session`,sessionId:e}}async function rr(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 ir(e){let{host:t,device:n,envelope:r}=e,i=Zn.decode(r.descriptor.body);return i.status===`decoded`?yr(n,i.descriptor)?i.descriptor.backend===`simctl`?await ar(e,i.descriptor):await sr(t,n,i.descriptor):j(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):j(`descriptor-invalid`,i.message)}async function ar(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 j(`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=or(yt(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await cr(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await tr(e.host,t.processes,e.envelope.sessionId)}}function or(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function sr(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:j(`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 cr(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function j(e,t){return{status:`unreattachable`,reason:e,message:t}}function lr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?N():e.backend===`simctl`?ur(e,e.outputPath):e.backend===`runner`?pr(e,e.outputPath):N()}function ur(e,t){let n=br(e.processes),r=dr(e.recording);return!n||r===`invalid`?N():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function dr(e){if(e!==void 0)return u(e)&&fr(e)?Object.freeze(e):`invalid`}function fr(e){return M(e.outPath)&&hr(e.startedAt)&&mr(e.clientOutPath)&&mt(e)}function pr(e,t){return!M(e.appBundleId)||!M(e.runnerSessionId)||!gr(e.runnerAuthority)||!_r(e.remotePath)?N():{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 M(e){return typeof e==`string`&&e.length>0}function mr(e){return e===void 0||M(e)}function hr(e){return typeof e==`number`&&Number.isFinite(e)}function gr(e){return e===`local-lease`||e===`scoped-provider`}function _r(e){return e===void 0||vr(e)}function vr(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function yr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:v(e)?t.remotePath!==void 0&&vr(t.remotePath):t.remotePath===void 0:!1}function br(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 N(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function xr(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 Sr=`iOS recording`,Cr=`simctl recordVideo`;function wr(e){return e.appleOs===`watchos`?x(`unsupported-platform-leaf`,`watchOS recording is not supported.`):v(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?x(`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 Tr(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Er({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await ir({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:Or({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await er(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Er(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Dr(e):await Ar(e)}async function Dr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await xr(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=Ot(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 P(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 P(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Mr(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=Lr(i,Cr,{},o);return Ir({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:$n(p)},snapshot:p,finish:(e,n)=>_t({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await kr(t,s,e)}catch(e){throw Nr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await Jn({host:t,snapshot:e,targetLabel:Sr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Nr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await Fr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function Or(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:Cr,gestureEvents:[]});return ft(a,{finish:(e,i)=>_t({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 kr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await Jn({host:t,snapshot:e,targetLabel:Sr,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 kr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Ar(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??=jr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!Pr(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 Ir({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:Lr(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await qn({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 jr(e){try{return await e()}catch(e){throw i(e,`COMMAND_FAILED`)}}function Mr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Nr(e,t,n){let a=i(e,`COMMAND_FAILED`);return t===void 0||n===void 0||a.details?.reason!==`recording-output-unplayable`?e:new r(a.code,`${a.message}; ${t}`,d(n,{...a.details??{},...n.signal===void 0?{}:{signal:n.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 Pr(e,t){return e.appleOs===`macos`||!v(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function P(e){return await e.terminate(),await e.wait}async function Fr(e){try{return await P(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function Ir(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=ft(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new ve(c),envelope:Qn({device:t,owner:n,input:r,descriptor:i})})}function Lr(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}async function F(e,t,n,r={}){return n.throwIfAborted(),g(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await Rr(e,t)?`Booted`:await Wr(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await zr(e,t,n,r.deadlineAtMs),await Gr(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function Rr(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function zr(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await Br(e,t,n,r),await Vr(e,t,n,r)}catch(a){throw i&&n.aborted&&Kr(e,t),n.throwIfAborted(),Date.now()>=r?Ur(t,a):a}}async function Br(e,t,n,i){let a=await e.appleTools.run({tool:`simctl`,args:S(t,[`boot`,t.id]),allowFailure:!0,timeoutMs:Hr(i,t)},n),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new r(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function Vr(e,t,n,i){me({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await e.appleTools.run({tool:`simctl`,args:S(t,[`bootstatus`,t.id,`-b`]),allowFailure:!0,timeoutMs:Hr(i,t)},n);if(a.exitCode!==0)throw new r(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(n.throwIfAborted(),Date.now()>=i)throw Ur(t)}function Hr(e,t){let n=e-Date.now();if(n<=0)throw Ur(t);return n}function Ur(e,t){return new r(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:xt,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 Wr(e,t,n){return await Wt(e.appleTools,t,n,15e3)}async function Gr(e,t){await e.commands.run({executable:`open`,args:[`-g`,`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function Kr(e,t){e.appleTools.run({tool:`simctl`,args:S(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const qr=Object.freeze({resolveOpenTarget:`simulator`,prepareApplicationOpen:`simulator`,openApplication:`simulator`,applyRuntimeHints:`simulator`,clearRuntimeHints:`simulator`,closeApplication:`simulator`,finalizeApplicationClose:`simulator`,prepareAppleRunner:`runner`,configureProviderPortReverse:`simulator`,ensureReady:`simulator`,bootTarget:`simulator`,bootTargetHeadless:`simulator`,shutdownTarget:`simulator`,listApps:`simulator`,deployApp:`simulator`,materializeAppSource:`simulator`,deployMaterializedApp:`simulator`,sendPushNotification:`simulator`,uninstallApp:`simulator`,appState:`simulator`,appLogStart:`simulator`,appLogInspect:`simulator`,appLogDoctor:`simulator`,appLogReattach:`simulator`,appLogCleanup:`simulator`,networkDump:`simulator`,audioProbeStart:`simulator`,audioProbeQuery:`simulator`,audioProbeReattach:`simulator`,audioProbeCleanup:`simulator`,readClipboard:`simulator`,writeClipboard:`runner`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`simulator`,sendTelephonyEvent:`simulator`,unlockOrientation:`simulator`,power:`simulator`,volumeDown:`simulator`,volumeUp:`simulator`,mute:`simulator`,sleep:`simulator`,wake:`simulator`,mediaPlayPause:`simulator`,mediaNext:`simulator`,mediaPrevious:`simulator`,mediaRewind:`simulator`,mediaFastForward:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`runner`,querySelector:`runner`,readTextAtPoint:`runner`,tapPoint:`runner`,tapRef:`runner`,tapElementSelector:`runner`,fillPoint:`runner`,fillRef:`runner`,longPressPoint:`runner`,hoverPoint:`runner`,hoverRef:`runner`,focusPoint:`runner`,typeText:`runner`,scrollDirection:`runner`,performGesturePlan:`runner`,performMultiTouchGesturePlan:`runner`,performTargetAuthoredDrag:`runner`,performDirectionalFlingPlan:`runner`,gestureViewport:`runner`,setViewport:`runner`,back:`runner`,home:`runner`,setOrientation:`runner`,appSwitcher:`runner`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function Jr(e){return e===void 0?`possible`:e.some(e=>qr[e]===`runner`)?`required`:`none`}function Yr(e){let{waitMs:t,signal:n,stop:r,cancelled:i}=e;return new Promise((e,a)=>{let o=()=>l(()=>a(i())),s=()=>l(e),c=setTimeout(()=>l(e),t);function l(e){clearTimeout(c),n?.removeEventListener(`abort`,o),r?.removeEventListener(`abort`,s),e()}n?.addEventListener(`abort`,o,{once:!0}),r?.addEventListener(`abort`,s,{once:!0}),n?.aborted?o():r?.aborted&&s()})}function Xr(e){let t=e.now??Date.now,n=e.waitGrant??`every-caller`,r=new Map,i=(n,i)=>{let a={status:`pending`,value:void 0,error:void 0,settledAtMs:t(),waitSpent:!1,controller:new AbortController,settled:void 0},o=()=>{};a.settled=new Promise(e=>{o=e}),r.set(n,a);let s=(i,s)=>{a.status=i,i===`ready`?a.value=s:a.error=s,a.settledAtMs=t(),(i===`ready`||e.retryAfterMs===void 0)&&r.get(n)===a&&r.delete(n),o()};try{i(a.controller.signal).then(e=>s(`ready`,e),e=>s(`failed`,e))}catch(e){s(`failed`,e)}return a},a=(n,a)=>{let o=r.get(n);if(!o)return i(n,a);if(o.status!==`failed`)return o;let s=t()-o.settledAtMs;return e.retryAfterMs===void 0||s>=e.retryAfterMs?i(n,a):o};return{value:async(t,r)=>{let i=a(t,r.start);if(i.status===`pending`&&(n===`every-caller`||!i.waitSpent)){i.waitSpent=!0;let t=new AbortController,n=r.wait(e.waitMs,t.signal);n.catch(()=>{});try{await Promise.race([i.settled,n])}finally{t.abort()}}if(i.status===`ready`)return i.value;throw i.status===`failed`?i.error:r.pending()},close:()=>{let e=[...r.values()];r.clear();for(let t of e)t.controller.abort()}}}async function Zr(e,t){let n=await At(`ps`,[`-p`,String(e),`-o`,`lstart=`],{allowFailure:!0,signal:t.signal,timeoutMs:t.timeoutMs});return n.exitCode===0&&n.stdout.trim()||null}const Qr=3e3,$r=`simulator-target-discovery-pending`,ei=`simulator-target-unavailable`;function ti(){let e=new Map,t=new Map,n=Xr({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 Zr(c.pid,{signal:a,timeoutMs:Qr});if(a.throwIfAborted(),e===c.processStartTime)return c}return e.delete(s),await n.value(s,{start:async()=>{let n=await ai(r,i,t);return e.set(s,n),n},wait:(e,t)=>Yr({waitMs:e,signal:a,stop:t,cancelled:()=>ni(a)}),pending:()=>I($r,r,i)})}}function ni(e){return t({readinessPhase:`target-discovery`},e.reason)}function ri(e){return e instanceof r&&e.details?.reason===$r}function ii(e){return e instanceof r&&e.details?.reason===ei}async function ai(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([It(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:ci(r)}),oi(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 I(`simulator-target-probe-failed`,e,t);let c=si(o.stdout,t);if(!c)throw I(ei,e,t);let l=await Zr(c.pid,{timeoutMs:Math.min(Qr,ci(r))});if(!l)throw I(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:Lt(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function oi(e,t,n){let r=t.get(e.id);if(r)return await r;let i=It(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:ci(n)}).then(t=>{if(t.exitCode!==0)throw I(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(Nt(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw I(`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 I(e,t,n){return new r(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:t.id,appBundleId:n})}function li(e){return e?.observation===`unobservable`&&e.proof===`no-running-process`}const ui=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function L(e){return e.platform===`apple`&&h(e)}function di(e){let t=ce(ue({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!L(n))return{observation:`not-eligible`};let a;for(;;){let o=await pi(e.resolveTarget,n,r,i);if(`verdict`in o)return o.verdict;let{target:s}=o;if(e.isBridgeDisabled(s))return m({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:s.generation}}),fi({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=ui.get(u);if(d===void 0)return fi({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 fi(e){return{observation:`probe-failed`,failure:e}}async function pi(e,t,n,r){for(;;)try{return{target:await e(t,n,r)}}catch(e){if(r.throwIfAborted(),ri(e))continue;if(ii(e))return{verdict:{observation:`unobservable`,proof:`no-running-process`}};let{code:t,details:n}=a(e),i=n?.reason;return{verdict:fi(typeof i==`string`?{source:`target`,code:t,reason:i}:{source:`target`,code:t})}}}function mi(e,t,n){let r=n&&L(e),i=r?Jr(t.execution.plannedOperations):void 0,a=v(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function hi(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function gi(e,t,n,i,a,o){let s=Date.now(),c=async()=>await Ci(t,n,i,a.observation),l=await c(),u,d,f=a.answerConfirmation,p=f&&l?.observation!==`observable`?await _i(f,a.redispatchLaunchUrl,c,l):void 0;if(p&&(o.runnerDemand=`required`,u=p.report,d=p.probeFailure,l=p.observed,p.unanswered))throw new r(`COMMAND_FAILED`,`The Simulator has not completed the launch URL for ${n.appBundleId}.`,{reason:`launch_confirmation_unanswered`,appBundleId:n.appBundleId,hint:`iOS may still be holding an "Open in" prompt, or the answer died with the runner session that raised it. Inspect the current alert before deciding on another action.`});if(i&&l?.observation!==`observable`&&await e.clock.sleep(300,t.signal),l&&(o.postOpenObservation=l.observation,l.observation===`probe-failed`&&(o.postOpenObservationFailure=l.failure)),o.postOpenSettleDurationMs=Math.max(0,Date.now()-s),u)return u;if(d)return{launchConfirmationProbeFailure:d}}async function _i(e,t,n,r){let i={observed:r,acceptAttempted:!1,confirmationStillPresent:!1};for(let r=0;r<2;r+=1){i=await vi(e,n,i);let a=r===1;if(i.confirmationStillPresent||a||!xi(i)||!t)break;await t()}return{observed:i.observed,report:i.report,probeFailure:i.probeFailure,unanswered:xi(i)||i.confirmationStillPresent}}async function vi(e,t,n){let r=await e(),i=r.outcome===`unanswered`&&r.reason===`alert-still-present`,a=n.acceptAttempted||Si(r),o=bi(n,r);return a?{observed:await t(),...o,acceptAttempted:a,confirmationStillPresent:i}:{observed:n.observed,...o,acceptAttempted:a,confirmationStillPresent:i}}function yi(e){switch(e.outcome){case`accepted`:return{seen:{launchConfirmation:`accepted`}};case`absent`:return{};case`unreadable`:return e.step===`url-owner`?{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:`url-owner-unresolved`}}:{probeFailure:e.step};case`unanswered`:return e.reason===`alert-still-present`?{}:{seen:{launchConfirmation:`unanswered`,launchConfirmationReason:e.reason}}}}function bi(e,t){let n=yi(t);return`seen`in n?{report:n.seen,probeFailure:void 0}:`probeFailure`in n?{report:void 0,probeFailure:n.probeFailure}:{report:e.report,probeFailure:void 0}}function xi(e){return e.acceptAttempted&&li(e.observed)}function Si(e){return e.outcome===`accepted`||e.outcome===`unanswered`&&e.reason===`alert-still-present`||e.outcome===`unreadable`&&e.step===`alert-accept`}async function Ci(e,t,n,r){if(!(!n||!L(e.device))&&!(!r||!t.appBundleId))return await r.awaitObservable(e.device,t.appBundleId,e.signal)}let wi;const Ti=()=>wi??=import(`./launch-confirmation.js`);let Ei;const Di=()=>Ei??=import(`./expo-dev-client-launch.js`);function Oi(e){let t=t=>Ze({device:t,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve}),n=e.device,r=t(n),i=e=>{n=e,r=t(e)};return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(n,t),prepareApplicationOpen:async t=>{let r=await F(e.host,n,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(n,t.execution,e.signal).catch(()=>{})}:void 0});i(r)},openApplication:async t=>await ki(e.host,r,t,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(n,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(n,t),closeApplication:async t=>{t.ensureReady&&i(await F(e.host,n,e.signal)),await Hi(e.host,r,t)},finalizeApplicationClose:async t=>await Ui(e.host,n,e.signal,t),prepareAppleRunner:async t=>{let r=await Wi(e.host,n,e.signal,t);return i(r.readied),r.prepared},configureProviderPortReverse:Xi})}async function ki(e,t,n,r){let i={},a=R(t.device),o=Gi(e,t,n,i),s=mi(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),hi(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=Vi(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Ai(e,t,n,a,l,i);let u=await ji(t,n,a,i),d=qi(t.device,u?{...n,runtimeLaunchUrl:u}:n,a);await Mi(o,c,n.prewarmRunnerBeforeOpen);let f=o.wasAwaited();await Ni(t,n,d,a,i),await Ri(o,c,s.awaitPrewarmAfterOpen),await zi(e,t,n,a,f,l);let p=await gi(e,t,n,a,{observation:r,answerConfirmation:Ii(t,n,d),redispatchLaunchUrl:Li(t,n,d)},i);return{appBundleId:n.appBundleId,timing:i,...p??{}}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Ai(e,t,n,r,i,a){if(!Bi(n,r)||!n.target)return;let o=Date.now();ee(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await Qe({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=z(o)}async function ji(e,t,n,i){if(!ge(t.runtimeHints))return;let a=Date.now(),o=n?await(await Di()).resolveExpoDevClientLaunchUrl(e.device,t):void 0;if(!o){if(!t.applyRuntimeHints)throw new r(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints})}return i.runtimeHintsDurationMs=z(a),o}async function Mi(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Ni(e,t,n,r,i){let a=Date.now();await $e({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=z(a),await Pi(e,t,n.followUpUrl,i)}async function Pi(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i=Date.now();await Fi(e,t,n),r.launchUrlDurationMs=z(i)}async function Fi(e,t,n){let r={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0};await $e({device:e.device,interactor:await e.resolveInteractor(r,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:r})}function Ii(e,t,{confirmation:n}){if(n)return async()=>{let{answerSimulatorLaunchConfirmation:r}=await Ti();return await r(e.device,n,e.resolveInteractor(t.execution,n.appBundleId),e.signal)}}function Li(e,t,{confirmation:n}){if(n)return async()=>{await Fi(e,t,n.url)}}async function Ri(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function zi(e,t,n,r,i,a){!v(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 Bi(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function Vi(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&Bi(t,n)}async function Hi(e,t,n){ee(t.device.platform)&&!R(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await Qe({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),R(t.device)&&await e.clock.sleep(300,t.signal)}async function Ui(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&&R(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function Wi(e,t,n,r){let i=Date.now()+r.timeoutMs,a=performance.now();return await f(`prepare_apple_runner`,async()=>{let o=await F(e,t,n,{deadlineAtMs:i}),s=Math.max(1,i-Date.now());return m({phase:`prepare_apple_runner`,durationMs:performance.now()-a,data:{event:`runner_start`,timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}}),{readied:o,prepared:await e.appleApplications.prepareRunner(o,{...r,timeoutMs:s},n)}},()=>({timeoutMs:r.timeoutMs,remainingMs:i-Date.now()}),`readiness_start`)}function Gi(e,t,n,r){let i,a=!1,o=Ki(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=z(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function Ki(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function qi(e,t,n){let r=t.runtimeLaunchUrl?.trim(),i=t.positionals.length===1?t.positionals[0]?.trim():void 0;if(!r||!i||l(i))return{positionals:t.positionals};let a=Ji(e,t.appBundleId,r),o=a?{confirmation:a}:{};return n&&!Yi(t)?{positionals:[i,r],...o}:{positionals:t.positionals,followUpUrl:r,...o}}function Ji(e,t,n){if(e.appleOs===`ios`&&e.kind===`simulator`&&!(t===void 0||s(n)))return{url:n,appBundleId:t}}function Yi(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function R(e){return v(e)&&e.kind===`simulator`}function z(e){return Math.max(0,Date.now()-e)}async function Xi(){throw new r(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const Zi=Object.freeze({available:!0}),Qi=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.`}),$i=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),ea=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ta=Object.freeze({available:!1,reason:`unsupported-device-kind`});function na(e){let t=ua(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:da(e),uninstallApp:t})}function ra(e){let{host:t,device:n,signal:r}=e,i=na(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await ia(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await oa(t,n,e,r),uninstallApp:async e=>await aa(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await la(t,n,e,r),{})}:{}})}async function ia(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await ca(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await sa(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 oa(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function aa(e,t,n,i){return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{await F(e,t,i);let a;try{a=await e.appleDeployment.resolveAppBundleId(t,n.app,{installedOnly:!0})}catch(e){if(e instanceof r&&e.code===`APP_NOT_INSTALLED`&&n.app.trim().includes(`.`))return{wasInstalled:!1};throw e}return await ca(e,t,a,i),{wasInstalled:!0,bundleId:a}})}async function oa(e,t,n,r){return await sa(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 sa(e,t,n,r){await F(e,t,r),await B(e,t.kind===`simulator`?{tool:`simctl`,args:S(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:kt},r,`Apple app install failed`)}async function ca(e,t,n,r){await F(e,t,r),await B(e,t.kind===`simulator`?{tool:`simctl`,args:S(t,[`uninstall`,t.id,n])}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n]},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>Mt(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function la(e,t,n,i){if(t.kind!==`simulator`)throw new r(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await F(e,t,i);let a=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(n.payload)}\n`),await B(e,{tool:`simctl`,args:S(t,[`push`,t.id,n.appId,a.path])},i,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}async function B(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:p(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:jt(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function ua(e){return fa(e)?e.kind!==`simulator`&&e.kind!==`device`?ta:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Qi:Zi:ea}function da(e){return fa(e)?e.kind===`simulator`?Zi:$i:ea}function fa(e){return v(e)&&e.appleOs!==`watchos`}const V=Object.freeze({available:!0}),pa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),ma=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ha(e){return e.kind!==`simulator`&&e.kind!==`device`?pa:y(e)===`watchos`?ma:V}const ga=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),_a=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),va=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function ya(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=y(e);return n===`macos`||n===`watchos`?_a:V}function H(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=y(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),xa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Sa(e){return e.kind!==`simulator`&&e.kind!==`device`?ba:H(e)?V:xa}const Ca=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function wa(e){return(e.kind===`simulator`||e.kind===`device`)&&te(e)?V:Ca}const U=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ta=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 Ea(e){return H(e)?Ta:U}function Da(e){return H(e)?V:U}function Oa(e){return H(e)?V:U}const ka=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Aa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),ja=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 Ma(e){return e.kind!==`simulator`&&e.kind!==`device`?Aa:ne(e)?V:ja}const Na=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`hardware-button volume presses the iPhone/iPad volume key; this Apple leaf has none.`}),Pa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button volume is supported on physical iPhone and iPad; iOS Simulators refuse because XCUIDevice exposes no volume press there.`});function Fa(e){return ne(e)?e.kind===`device`?V:Pa:Na}function Ia(e){return Object.freeze({...Te({back:ha(e)}),...Ve({unsupported:ka,home:ya(e,ga),appSwitcher:ya(e,va),actionButton:Ma(e),volumeUp:Fa(e),volumeDown:Fa(e)}),...Ge({orientation:Sa(e)}),...Je({tvRemote:wa(e),buttonSupport:{supported:o(`apple`),unsupported:{available:!1,reason:`unsupported-platform-leaf`,hint:`This TV remote button is not supported on tvOS.`}}}),...We({unsupported:U,status:Ea(e),dismiss:Da(e),enter:Oa(e)})})}function La(e){let{host:t,device:n,signal:r,admitted:i}=e,a=Object.keys(Ia(n));return tt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Object.fromEntries(a.map(e=>[e,i[e]]))})}const W=Object.freeze({available:!0}),Ra=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),za=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),Ba=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.`}),Va=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Run `agent-device settings --help` for the settings each target serves."}),Ha=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The macOS host supports settings appearance and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>.`}),Ua=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Select a booted iPhone or iPad simulator: this setting runs only there.`}),Wa=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.`}),Ga=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ka(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=y(e);return r===`watchos`?Ga:e.kind===`simulator`||r===`macos`?W:n}const qa=Object.freeze({available:!1,reason:`unsupported-device-scope`,hint:`This session holds one app of the Mac. Use a --surface desktop session for the clipboard and host settings.`});function Ja(e){return e.hostApp?qa:Ka(e,Ra,Wa)}const Ya=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),Xa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),Za=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function Qa(e){if(e.kind!==`simulator`&&e.kind!==`device`)return Xa;let t=y(e);return t===`watchos`?Ga:e.kind===`simulator`||t===`ios`||t===`macos`?W:Za}function $a(e){return e.kind!==`simulator`&&e.kind!==`device`?Ya:y(e)===`watchos`?Ga:W}function eo(e){let t=Ja(e);return t.available?Wa:t}function to(e){let t=e.hostApp?qa:Ka(e,za,Ba);if(g(e))return et({target:t,unsupported:Ha,write:{appearance:W,permission:W}});let n=h(e)?W:Ua;return et({target:t,unsupported:Va,write:{wifi:W,airplane:W,location:W,appearance:W,"clear-app-state":W,"reset-keychain":W,permission:W,"text-size":n,faceid:n,touchid:n},read:{"text-size":n}})}function no(e){let t=Ja(e),n=Qa(e);return Object.freeze({...Ke({unsupported:eo(e),read:t,write:t}),...Xe({read:n,wait:n,accept:n,dismiss:n}),...Ye({triggerAppEvent:$a(e)}),...to(e)})}function ro(e){let{host:t,device:n,signal:r}=e;return tt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:no(n)})}function io(e,t,n){let r=Ue({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(i.options?.observeOnly===!0)return await r.captureSnapshot(i);let a=g(t.device)?se(i.options?.surface,t.appBackend):void 0;if(a)return await e.snapshot.captureSurface(t.device,{...i.options,surface:a},He(t.signal,i));if(!n)return await r.captureSnapshot(i);let o=He(t.signal,i);return await n.capture(t.device,i,o,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function ao(e,t){return Object.freeze({findText:async n=>{let r=await oo(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 oo(e,t,n){let r=n.options?.appBundleId;if(r===void 0||g(t.device)&&oe(n.options?.surface,t.appBackend)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await so(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function so(e,t,n){return!L(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function co(e){return Object.freeze({querySelector:async t=>{let n=t.signal?AbortSignal.any([e.signal,t.signal]):e.signal;n.throwIfAborted();let r={...t.execution,signal:n},{queryAppleRunnerSelector:i}=await import(`./runner-selector-query.js`),a=await i(e.device,t.selector,t.options?.appBundleId,r),o=lo(a);return Object.freeze({found:a.found===!0,...o?{node:o}:{}})}})}function lo(e){let t=e.nodes;if(!Array.isArray(t))return;let n=t[0];if(!n||typeof n!=`object`)return;let r=c(n.rect);if(r)return Object.freeze({rect:r,hittable:n.hittable===!0})}const G=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.`});function uo(e,t){return!g(e)||t!==`native`?{}:Object.freeze({screenRecordingStart:G,screenRecordingReattach:G,prepareAppleRunner:G,longPressPoint:G,...Te({back:G}),...Oe({unsupported:G})})}function fo(e){let t,n=!1,r=async()=>(t??=import(`./host3.js`).then(e=>e.t).then(({createSnapshotSourceHost:t})=>import(`./adapter.js`).then(({createSimulatorSnapshotSource:n})=>n({host:t(e)}))),await t);return{acquire:async e=>n?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await r()).acquire(e),close:async()=>{n=!0,t&&await(await t).close()}}}const po=new Set([`notRunning`,`runningBackground`,`runningBackgroundSuspended`]);function mo(){return async(e,t)=>{let n=zt(e.id);if(!n||n.liveness!==`ready`)return`unknown`;for(let r of Se){let i=await ho(e,r.bundleId,n.sessionId,t);if(i===`runningForeground`)return{kind:`foreground`,host:r};if(i===void 0||!po.has(i))return`unknown`}return`background`}}async function ho(t,n,r,i){try{let a=(await Rt(t,{command:`appState`,appBundleId:n},{signal:AbortSignal.any([i.signal,AbortSignal.timeout(1e3)]),expectedRunnerSessionId:r,...i.requestId?{requestId:i.requestId}:{}})).applicationState;return e(a)?a:void 0}catch{i.signal.throwIfAborted();return}}function go(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 _o(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function _o(e,t){let n=await Promise.all(Se.map(async e=>({host:e,pids:await vo(e.processExecutable,t)}))),r=!1;for(let{host:i,pids:a}of n){if(a===`unknown`){r=!0;continue}for(let n of a){let a=await yo(n,e.id,t);if(a===`unknown`)r=!0;else if(a)return{kind:`present`,host:i}}}return r?`unknown`:`absent`}async function vo(e,t){let n=await bo(`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 bo(`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 bo(e,t,n){try{let r=await At(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const xo=new Map([[`window-coordinate-space-unresolved`,`coordinate-space-unresolved`],[`app-window-not-full-screen`,`window-not-full-screen`],[`foreground-owner-unverified`,`foreground-ownership`],[`foreground-owner-changed`,`foreground-ownership`]]);function So(e){if(e.kind===`preparing`)return{scope:`capture`,code:e.code,consequence:`bridge-preparation`};let t=xo.get(e.code);return t?{scope:`capture`,code:e.code,consequence:t}:{scope:`generation`,code:e.code}}const Co=`system-surface-presented`,wo=`system-surface-host-lingering`;function To(e,t={}){let n=t.source??fo(e.hostEnvironment),i=t.resolveTarget??ti(),a=t.systemSurfacePresent??go(),o=t.systemSurfaceForeground??mo(),s=new Set,c=new Map,l=e=>(Vo(e,c,s),s.has(Ho(e))),u=di({source:n,resolveTarget:i,clock:e.clock,isBridgeDisabled:l});return Object.freeze({awaitObservable:u.awaitObservable,shutdown:async()=>await n.close(),capture:async(t,c,u,d)=>{if(!ko(t,c))return await Mo(t,c,d);let p=await Eo(t,c,u,o);if(p!==`background`&&p!==`unknown`)return await jo(t,c,d,p.host.bundleId);let m=p===`background`?`absent`:await a(t,u);if(m===`unknown`)return await K(t.id,c,d,Po(t.id,c),q(c),`system-surface-probe-unavailable`,[Bo()]);if(m!==`absent`)return await jo(t,c,d,m.host.bundleId);let h;try{h=await Do(e,i,t,c,u)}catch(e){return Oo(u,e),J(`target-resolution-failed`,t,void 0,e),await K(t.id,c,d,Po(t.id,c),q(c),`target-resolution-failed`,[Bo()])}if(l(h))return J(`circuit-disabled`,t,h.generation),await K(t.id,c,d,h,q(c),`circuit-disabled`);let g=q(c),_=await n.acquire({target:h,hint:ce(g),signal:u});if(_.stage===`failed`){if(_.failure.kind===`cancelled`)throw u.throwIfAborted(),new r(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:_.failure.code,..._.failure.details});let e=await zo(_.failure,h,t,c.options.appBundleId,u,i);return await Ao(c,d,h,e,g,_.failure,s)}try{return await f(`ios.snapshot-source.present`,async()=>await e.snapshot.presentIosAcquisition(_,c.options),{producer:`simulator-ax-bridge`})}catch(e){return await Ao(c,d,h,{lineage:h,residue:[]},g,{kind:`malformed-tree`,code:`presentation-invariant`},s,e)}}})}async function Eo(e,t,n,r){let i=t.execution?.requestId,a=await r(e,{signal:n,...i?{requestId:i}:{}});return a===`background`&&m({level:`debug`,phase:`ios_snapshot_route_surface_host_background`,data:{deviceId:e.id}}),a}async function Do(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!ri(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function Oo(e,t){if(e.aborted)throw n(t)?t:e.reason}function ko(e,t){return L(e)&&!!t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0}async function Ao(e,t,n,r,i,a,o,s){let c=So(a);return c.scope===`generation`&&o.add(Ho(n)),J(a.code,{id:n.simulator.udid},n.generation,s,a.details),await K(n.simulator.udid,e,t,r.lineage,i,c,r.residue)}async function K(e,t,n,r,i,a,o=[]){return No(e,await n(t),r,i,a,o)}async function jo(e,t,n,r){let i=await n(t),a=i.systemSurface?Co:wo;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),No(e.id,i,Po(e.id,t),q(t),a)}async function Mo(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:Io(Fo(e.id,i.bundleId),q(t),[])}:r}function No(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:Io(o?Fo(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],Lo(i,n,o!==void 0)]}}function Po(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function Fo(e,t){return{targetId:`${e}:${t}`}}function Io(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:le(t),residue:Object.freeze([...n])})}function Lo(e,t,n){if(e===Co)return`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`;if(e===wo)return`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`;let r=typeof e==`string`?e:e.code;return n?`Simulator AX snapshot unavailable (${r}); used XCTest, which read the system surface presented over the app.`:typeof e!=`string`&&e.scope===`capture`?Ro(r,e.consequence):`Simulator AX snapshot unavailable (${r}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}function Ro(e,t){let n=`Simulator AX snapshot unavailable (${e}); used XCTest for this capture`;switch(t){case`bridge-preparation`:return`${n} while the bridge is still being prepared.`;case`foreground-ownership`:return`${n}, while another surface owned the foreground.`;case`window-not-full-screen`:return`${n}, while the app window did not fill the screen; the runner republishes a windowed capture in screen space.`;case`coordinate-space-unresolved`:return`${n}, which reports captured geometry in the app's own orientation space.`}}async function zo(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:[Bo()]}}}function Bo(){return{kind:`unknown-generation`,captureId:Gt()}}function q(e){return ue({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 Vo(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 Ho(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){m({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=ae(`apple`),X=Object.freeze({available:!0}),Z=x(`unsupported-platform-leaf`),Uo=x(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`),Wo=x(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`),Go=x(`unsupported-device-backend`,`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`),Ko=x(`unsupported-device-kind`,`focus is supported on Apple simulators and physical devices.`),qo=x(`unsupported-platform-leaf`,`telephony simulates calls and SMS through the Android emulator console; Apple simulators and devices expose no host control that injects a call or text message.`),Jo=x(`unsupported-platform-leaf`,`Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`);function Yo(e){return!v(e)||e.appleOs===`watchos`?Jo:e.kind===`simulator`||e.kind===`device`?X:Jo}const Xo=x(`unsupported-provider-mode`,`Headless boot is supported only for local Android emulators.`),Zo=x(`unsupported-platform-leaf`,`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`),Qo=x(`unsupported-device-kind`),$o=x(`unsupported-platform-leaf`,`watchOS open is not supported because XCUITest cannot drive watchOS UI.`),es=x(`unsupported-platform-leaf`,`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`),ts=x(`unsupported-platform-leaf`,`watchOS close is not supported because XCUITest cannot drive watchOS UI.`),ns=x(`unsupported-device-kind`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),rs=Q(`open is supported only for Apple simulators and devices.`),is=Q(`prepare is supported only for Apple simulators and devices.`),as=Q(`close is supported only for Apple simulators and devices.`),os=x(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),ss=x(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),cs=Q(`snapshot is supported only for Apple simulators and devices.`),ls=x(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),us=x(`unsupported-platform-leaf`,`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`),ds=Q(`screenshot is supported only for Apple simulators and devices.`),fs=x(`owner-capability-missing`,`Open the app under test before capturing its snapshot.`);function Q(e){return x(`unsupported-device-kind`,e)}function ps(e){return!v(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:ss}function ms(e){let t=hs(e),n=gs(e),r=_s(e),i=vs(e);return _e({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:os})}function hs(e){return y(e)===`watchos`?$o:e.kind===`simulator`||e.kind===`device`?X:rs}function gs(e){return y(e)===`watchos`?es:e.kind===`simulator`||e.kind===`device`?X:is}function _s(e){return y(e)===`watchos`?ts:e.kind===`simulator`||e.kind===`device`?X:as}function vs(e){return y(e)!==`watchos`&&v(e)&&e.kind===`simulator`?X:ns}function ys(e){return e.appleOs===`watchos`?x(`unsupported-platform-leaf`,`watchOS app inventory is not supported.`):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?x(`unsupported-device-backend`,`App inventory is available only on CoreDevice-backed physical iOS devices.`):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:Ko}function bs(e){let t=Fn(e),n=To(e),r,i=t=>g(t)?r??=Ut(e.hostEnvironment.env):`xctest`,a=async n=>{let r=await t.inspectFacts(n),a=na(n),o=wr(n),s=o.available?await e.screenRecording.apple.availability(n):void 0,c=o.available&&s?.available===!1?x(`unsupported-provider-mode`,s.hint):o,l=n.appleOs===`watchos`?Z:X,u=g(n)||n.appleOs===`watchos`?Z:X,d=ys(n);return Object.freeze({device:r.device,operations:{...r.operations,...a,appState:Yo(n),networkDump:X,screenRecordingStart:c,screenRecordingReattach:c,screenRecordingCleanup:c,...Ts(n),...De({capture:ws(n)}),...Ae({findText:Cs(n),querySelector:v(n)?$(n):Z}),...Pe({setViewport:Uo}),...ze({focus:$(n)}),...en(n),...je({type:$(n)}),...be({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...v(n)?{tapElementSelector:$(n)}:{}}),...Be({readTextAtPoint:Ss(n)}),...Ia(n),...Vt(n),sendTelephonyEvent:qo,...no(n),...we({capture:Jt(n),query:Wo}),...Ne(xs(n)),ensureReady:l,bootTarget:u,bootTargetHeadless:Xo,listApps:d,...ms(n),shutdownTarget:ps(n),...uo(n,i(n))}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:a,bind:async r=>{let o=await t.bind(r),s=await a(r.device),c=s.operations.screenRecordingStart,l=b(s.operations.appState,()=>qt(e,{device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),u=b(s.operations.querySelector,()=>co({device:r.device,signal:r.scope.signal})),d={...l,...u,...o.operations,...ra({host:e,device:r.device,signal:r.scope.signal}),networkDump:async t=>await zn(e,r.device,t,r.scope.signal),...b(c,()=>Tr({host:e,device:r.device,owner:Y,signal:r.scope.signal})),...b(s.operations.audioProbeStart,()=>lt({host:e.audioProbe.hostCapture,device:r.device,owner:Y})),...b(s.operations.perfFrames,()=>Yt({resolveHost:()=>e.perf.apple,device:r.device,owner:Y})),...b(s.operations.captureSnapshot,()=>io(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)},n)),...b(s.operations.captureScreenshot,()=>Me({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.focusPoint,()=>qe({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...Le({device:r.device,signal:r.scope.signal,facts:s.operations,resolveInteractor:e.localInteractors.resolve}),...b(s.operations.scrollDirection,()=>Ie({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.typeText,()=>Ee({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.tapPoint,()=>xe({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:s.operations,pause:async t=>await e.clock.sleep(t,r.scope.signal)})),...b(s.operations.readTextAtPoint,()=>Re({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...b(s.operations.findText,()=>ao(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)})),...La({host:e,device:r.device,signal:r.scope.signal,admitted:s.operations}),...ro({host:e,device:r.device,signal:r.scope.signal}),...Ht({device:r.device,signal:r.scope.signal}),...b(s.operations.ensureReady,()=>({ensureReady:async()=>await F(e,r.device,r.scope.signal)})),...b(s.operations.bootTarget,()=>({bootTarget:async t=>await F(e,r.device,r.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...b(s.operations.listApps,()=>({listApps:async e=>{r.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...he(Oi({host:e,device:r.device,signal:r.scope.signal,observation:n}),s.operations),...b(s.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(r.device,r.scope.signal)}))};return Object.freeze({device:o.device,owner:Y,facts:s,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function xs(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&y(e)!==`watchos`?X:Go;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Ss(e){return y(e)===`watchos`?Zo:e.kind===`simulator`||e.kind===`device`?X:Qo}function Cs(e){return y(e)===`watchos`?cs:e.kind===`simulator`||e.kind===`device`?X:cs}function ws(e){return y(e)===`watchos`?us:e.kind===`simulator`||e.kind===`device`?X:ds}function Ts(e){let t=Cs(e);return ke({capture:t,customActions:t.available&&v(e)&&e.kind===`simulator`?X:ls,withoutActiveApp:v(e)?fs:t})}export{bs as createApplePlatformRuntime,Xr as n,Yr as r,Zr as t};
@@ -1 +1 @@
1
- import{R as e}from"./sdk-contracts.js";import{K as t,L as n,V as r,Y as i}from"./sdk-io.js";import"./command.js";import{o as a}from"./version.js";import"./retry.js";import{n as o,t as s}from"./boot-diagnostics.js";import{_ as c,d as l,r as u}from"./config.js";import{a as d,o as f}from"./tool-provider.js";import{i as p,n as m}from"./simctl.js";const h=a({ttlMs:5e3});function g(e){return`${e.id}|${e.simulatorSetPath??``}`}function _(e){return h.get(g(e))===!0}function v(e){h.set(g(e),!0)}function y(t,n){if(t.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`${n} is only supported on iOS simulators`)}async function b(e={}){await d(`open`,[`-g`,`-a`,`Simulator`],{allowFailure:!0,signal:e.signal,timeoutMs:c})}async function x(a,c={}){if(a.kind!==`simulator`)return;if(c.signal?.throwIfAborted(),(_(a)?`Booted`:await S(a,c.signal))===`Booted`){v(a);return}let l=n.fromTimeoutMs(u),d,p,h=e=>o({error:e,stdout:p?.stdout??d?.stdout,stderr:p?.stderr??d?.stderr,context:{platform:`ios`,phase:`boot`}});try{await r(async({deadline:n})=>{if(n?.isExpired())throw new e(`COMMAND_FAILED`,`iOS simulator boot deadline exceeded`,{timeoutMs:u});let r=Math.max(1e3,n?.remainingMs()??18e4);d=await f(m(a,[`boot`,a.id]),{allowFailure:!0,signal:c.signal,timeoutMs:r});let o=`${d.stdout}\n${d.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(d.exitCode!==0&&!s)throw new e(`COMMAND_FAILED`,`simctl boot failed`,t(d));p=await f(m(a,[`bootstatus`,a.id,`-b`]),{allowFailure:!0,signal:c.signal,timeoutMs:r}),i(p,`simctl bootstatus failed`);let l=await S(a,c.signal);if(l!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{state:l})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let t=h(e);return t!==`IOS_BOOT_TIMEOUT`&&t!==`CI_RESOURCE_STARVATION_SUSPECTED`}},{deadline:l,phase:`boot`,signal:c.signal,classifyReason:h})}catch(t){let n=h(t);throw new e(`COMMAND_FAILED`,`iOS simulator failed to boot`,{platform:`ios`,deviceId:a.id,timeoutMs:u,elapsedMs:l.elapsedMs(),reason:n,hint:s(n),boot:d,bootstatus:p})}v(a),await b({signal:c.signal})}async function S(e,t){let n=m(e,[`list`,`devices`,`-j`]),r=await f(n,{allowFailure:!0,signal:t,timeoutMs:l});return r.exitCode===0?p(r.stdout,e.id):null}export{_ as i,v as n,y as r,x as t};
1
+ import{R as e}from"./sdk-contracts.js";import{K as t,L as n,V as r,Y as i}from"./sdk-io.js";import"./command.js";import{o as a}from"./version.js";import"./retry.js";import{n as o,t as s}from"./boot-diagnostics.js";import{f as c,r as l,v as u}from"./config.js";import{a as d,o as f}from"./tool-provider.js";import{i as p,n as m}from"./simctl.js";const h=a({ttlMs:5e3});function g(e){return`${e.id}|${e.simulatorSetPath??``}`}function _(e){return h.get(g(e))===!0}function v(e){h.set(g(e),!0)}function y(t,n){if(t.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`${n} is only supported on iOS simulators`)}async function b(e={}){await d(`open`,[`-g`,`-a`,`Simulator`],{allowFailure:!0,signal:e.signal,timeoutMs:u})}async function x(a,c={}){if(a.kind!==`simulator`)return;if(c.signal?.throwIfAborted(),(_(a)?`Booted`:await S(a,c.signal))===`Booted`){v(a);return}let u=n.fromTimeoutMs(l),d,p,h=e=>o({error:e,stdout:p?.stdout??d?.stdout,stderr:p?.stderr??d?.stderr,context:{platform:`ios`,phase:`boot`}});try{await r(async({deadline:n})=>{if(n?.isExpired())throw new e(`COMMAND_FAILED`,`iOS simulator boot deadline exceeded`,{timeoutMs:l});let r=Math.max(1e3,n?.remainingMs()??18e4);d=await f(m(a,[`boot`,a.id]),{allowFailure:!0,signal:c.signal,timeoutMs:r});let o=`${d.stdout}\n${d.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(d.exitCode!==0&&!s)throw new e(`COMMAND_FAILED`,`simctl boot failed`,t(d));p=await f(m(a,[`bootstatus`,a.id,`-b`]),{allowFailure:!0,signal:c.signal,timeoutMs:r}),i(p,`simctl bootstatus failed`);let u=await S(a,c.signal);if(u!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{state:u})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let t=h(e);return t!==`IOS_BOOT_TIMEOUT`&&t!==`CI_RESOURCE_STARVATION_SUSPECTED`}},{deadline:u,phase:`boot`,signal:c.signal,classifyReason:h})}catch(t){let n=h(t);throw new e(`COMMAND_FAILED`,`iOS simulator failed to boot`,{platform:`ios`,deviceId:a.id,timeoutMs:l,elapsedMs:u.elapsedMs(),reason:n,hint:s(n),boot:d,bootstatus:p})}v(a),await b({signal:c.signal})}async function S(e,t){let n=m(e,[`list`,`devices`,`-j`]),r=await f(n,{allowFailure:!0,signal:t,timeoutMs:c});return r.exitCode===0?p(r.stdout,e.id):null}export{_ as i,v as n,y as r,x as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-device",
3
- "version": "0.21.32",
3
+ "version": "0.21.33",
4
4
  "description": "Mobile app automation and verification for AI coding agents. CLI, MCP server, and typed Node.js API for iOS, Android, HarmonyOS, TV, web, macOS, and Linux.",
5
5
  "mcpName": "io.github.callstack/agent-device",
6
6
  "license": "MIT",
@@ -146,6 +146,10 @@
146
146
  "fallow:all": "fallow --summary",
147
147
  "fallow:baseline": "fallow health --report-only --save-baseline fallow-baselines/health.json --summary",
148
148
  "check:fallow": "fallow audit",
149
+ "check:native-dupes": "jscpd --config .jscpd-native.json --baseline native-dupes-baseline.json --fail-on-new-clones --fail-on-empty",
150
+ "check:native-dupes:test": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/native-dupes/check.test.ts",
151
+ "native-dupes:report": "jscpd --config .jscpd-native.json --baseline native-dupes-baseline.json --fail-on-empty",
152
+ "native-dupes:baseline": "jscpd --config .jscpd-native.json --baseline native-dupes-baseline.json --update-baseline --fail-on-empty",
149
153
  "check:affected": "node --experimental-strip-types scripts/check-affected/run.ts",
150
154
  "check:affected:test": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/check-affected/*.test.ts",
151
155
  "gate": "node --experimental-strip-types scripts/gate/run.ts",
@@ -179,7 +183,7 @@
179
183
  "check:quick": "pnpm lint && pnpm typecheck",
180
184
  "sync:mcp-metadata": "node scripts/sync-mcp-metadata.mjs",
181
185
  "check:mcp-metadata": "node scripts/sync-mcp-metadata.mjs --check",
182
- "check:tooling": "pnpm format:check && pnpm lint && pnpm typecheck && pnpm check:layering && pnpm depgraph:test && pnpm check:gate-manifest:test && pnpm check:gate-manifest && pnpm check:production-exports && pnpm check:tmpdir-leaks:test && pnpm check:xctest-selection && pnpm check:packaged-runner-swift && pnpm check:mcp-metadata && pnpm check:doc-prose && pnpm check:doc-links && pnpm build && pnpm check:bundle-owner-files && pnpm check:package",
186
+ "check:tooling": "pnpm format:check && pnpm lint && pnpm typecheck && pnpm check:layering && pnpm depgraph:test && pnpm check:gate-manifest:test && pnpm check:gate-manifest && pnpm check:production-exports && pnpm check:native-dupes:test && pnpm check:native-dupes && pnpm check:tmpdir-leaks:test && pnpm check:xctest-selection && pnpm check:packaged-runner-swift && pnpm check:mcp-metadata && pnpm check:doc-prose && pnpm check:doc-links && pnpm build && pnpm check:bundle-owner-files && pnpm check:package",
183
187
  "check:unit": "pnpm test:unit && pnpm check:tmpdir-leaks && pnpm test:smoke",
184
188
  "check": "node --experimental-strip-types scripts/check-affected/run.ts --run --full",
185
189
  "prepack": "npm_config_dry_run=false pnpm release:prepare",
@@ -348,6 +352,7 @@
348
352
  "fast-check": "^4.9.0",
349
353
  "ipaddr.js": "^2.5.0",
350
354
  "jpeg-js": "^0.4.4",
355
+ "jscpd": "5.4.2",
351
356
  "oxc-parser": "^0.146.0",
352
357
  "oxfmt": "^0.67.0",
353
358
  "oxlint": "^1.79.0",
package/server.json CHANGED
@@ -7,12 +7,12 @@
7
7
  "url": "https://github.com/callstack/agent-device",
8
8
  "source": "github"
9
9
  },
10
- "version": "0.21.32",
10
+ "version": "0.21.33",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "agent-device",
15
- "version": "0.21.32",
15
+ "version": "0.21.33",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  },
@@ -1 +0,0 @@
1
- 3f4409c09c27a9202163140f0cd1c23df781ec8d25f52c390d6948d4aa735876 agent-device-android-ime-helper-0.21.32.apk
@@ -1 +0,0 @@
1
- 39e02e88a4790b5503ba095c163451bc195e7b719435ba992732431a25e119e0 agent-device-android-snapshot-helper-0.21.32.apk