UNPKG

agent-device

Version:

Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.

2 lines • 44.7 kB
import{jn as e}from"./sdk-batch.js";import{B as t,C as n,F as r,T as i,ut as a,v as o}from"./sdk-contracts.js";import{a as s,o as c,v as l}from"./sdk-batch-runner.js";import{Ot as u,St as d,et as f}from"./sdk-io.js";import"./diagnostics.js";import{S as p,T as m,V as h,j as g,w as _,x as v,y}from"./sdk-device.js";import{i as b,r as ee}from"./session.js";import{l as te}from"./tv-remote.js";import"./command.js";import{i as ne,n as re,r as ie}from"./ios-snapshot-planning.js";import{n as ae}from"./request.js";import{r as oe}from"./application-lifecycle-runtime.js";import{a as se}from"./runner-lifecycle.js";import{i as ce}from"./touch-runtime.js";import{t as x}from"./ios-system-surface.js";import{r as le}from"./gesture-admission.js";import{t as ue}from"./device-readiness-runtime.js";import{A as de,C as fe,D as pe,F as me,M as he,O as ge,R as _e,V as ve,W as ye,_ as be,j as xe,l as Se,o as Ce,p as we,r as Te,v as Ee,x as De}from"./tv-remote-runtime.js";import{n as Oe,o as ke,s as S,u as C}from"./application-lifecycle-interaction.js";import{t as w}from"./interactor-operation-catalog.js";import{o as T,r as Ae}from"./config.js";import{o as je}from"./tool-provider.js";import{o as Me}from"./devicectl.js";import{r as Ne}from"./physical-device-control.js";import{d as Pe,o as Fe,s as E}from"./simctl.js";import{t as Ie}from"./runner-client.js";import{t as Le}from"./simctl-execution.js";import{n as Re}from"./app-backend.js";import{t as ze}from"./simulator-state.js";import{n as Be,t as Ve}from"./detached-attempt.js";import{n as He,t as Ue}from"./source-channel.js";import{randomUUID as We}from"node:crypto";async function D(e,t,n,r={}){return n.throwIfAborted(),m(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?await Ge(e,t)?(e.deviceReadiness.appleAutomation.keepHot(t),{...t,booted:!0}):(await Xe(e,t,n)!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await Ke(e,t,n,r.deadlineAtMs),await Ze(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function Ge(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function Ke(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await qe(e,t,n,r),await Je(e,t,n,r)}catch(a){throw i&&n.aborted&&Qe(e,t),n.throwIfAborted(),Date.now()>=r?O(t,a):a}}async function qe(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:E(t,[`boot`,t.id]),allowFailure:!0,timeoutMs:Ye(r,t)},n),a=`${i.stdout}\n${i.stderr}`.toLowerCase(),o=a.includes(`already booted`)||a.includes(`current state: booted`);return o||f(i,`simctl boot failed`),!o}async function Je(e,t,n,r){ae({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let i=await e.appleTools.run({tool:`simctl`,args:E(t,[`bootstatus`,t.id,`-b`]),allowFailure:!0,timeoutMs:Ye(r,t)},n);if(f(i,`simctl bootstatus failed`),n.throwIfAborted(),Date.now()>=r)throw O(t)}function Ye(e,t){let n=e-Date.now();if(n<=0)throw O(t);return n}function O(e,t){return new o(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:ue,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 Xe(e,t,n){return await ze(e.appleTools,t,n,15e3)}async function Ze(e,t){await e.commands.run({executable:`open`,args:[`-g`,`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function Qe(e,t){e.appleTools.run({tool:`simctl`,args:E(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const $e=Object.freeze({available:!0}),et=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.`}),tt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),nt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),rt=Object.freeze({available:!1,reason:`unsupported-device-kind`});function it(e){let t=ft(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:pt(e),uninstallApp:t})}function at(e){let{host:t,device:n,signal:r}=e,i=e.install,a=it(n);return Object.freeze({...a.deployApp.available?{deployApp:async e=>await ot(t,n,e,r,i),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await ct(t,n,e,r,i),uninstallApp:async e=>await st(t,n,e,r)}:{},...a.sendPushNotification.available?{sendPushNotification:async e=>(await dt(t,n,e,r),{})}:{}})}async function ot(e,t,n,r,i){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let a=await e.appleDeployment.resolveAppBundleId(t,n.app),o=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await ut(e,t,a,r),i?await i(o,r):await lt(e,t,o.installablePath,r),{bundleId:a,launchTarget:a}}finally{await o.cleanup()}});let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await ct(e,t,{artifact:a},r,i)}finally{await a.cleanup()}}async function st(e,t,n,r){return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{await D(e,t,r);let i;try{i=await e.appleDeployment.resolveAppBundleId(t,n.app,{installedOnly:!0})}catch(e){if(e instanceof o&&e.code===`APP_NOT_INSTALLED`&&n.app.trim().includes(`.`))return{wasInstalled:!1};throw e}return await ut(e,t,i,r),{wasInstalled:!0,bundleId:i}})}async function ct(e,t,n,r,i){let a={};i?a=await i(n.artifact,r):await lt(e,t,n.artifact.installablePath,r);let o=a.bundleId??n.artifact.bundleId,s=a.appName??n.artifact.appName,c=a.launchTarget??o;return{...a,...o?{bundleId:o}:{},...s?{appName:s}:{},...c?{launchTarget:c}:{}}}async function lt(e,t,n,r){await D(e,t,r),await k(e,t.kind===`simulator`?{tool:`simctl`,args:E(t,[`install`,t.id,n]),timeoutMs:T}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:T},r,`Apple app install failed`)}async function ut(e,t,n,r){await D(e,t,r),await k(e,t.kind===`simulator`?{tool:`simctl`,args:E(t,[`uninstall`,t.id,n]),timeoutMs:Ae}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n],timeoutMs:Ae},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>Ne(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function dt(e,t,n,r){if(t.kind!==`simulator`)throw new o(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await D(e,t,r);let i=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await i.writeText(`${JSON.stringify(n.payload)}\n`);let a=await je().simulatorFiles.stageFile(i.path,r);try{await k(e,{tool:`simctl`,args:E(t,[`push`,t.id,n.appId,a.path])},r,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}finally{await i[Symbol.asyncDispose]()}}async function k(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:f(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:Me(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function ft(e){return mt(e)?e.kind!==`simulator`&&e.kind!==`device`?rt:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?et:$e:nt}function pt(e){return mt(e)?e.kind===`simulator`?$e:tt:nt}function mt(e){return _(e)}const ht=3e3,gt=`simulator-target-discovery-pending`,_t=`simulator-target-unavailable`;function vt(){let e=new Map,t=new Map,n=Ve({waitMs:1500}),r=async(r,i,a)=>{a.throwIfAborted();let o=`${r.id}:${i}`;return e.delete(o),await n.value(o,{start:async()=>{let n=await St(r,i,t);return e.set(o,n),n},wait:(e,t)=>Be({waitMs:e,signal:a,stop:t,cancelled:()=>yt(a)}),pending:()=>j(gt,r,i)})};return Object.freeze({resolveTarget:async(t,n,i)=>{i.throwIfAborted();let a=e.get(`${t.id}:${n}`);if(a){let e=await He(a.pid,{signal:i,timeoutMs:ht});if(i.throwIfAborted(),e===a.processStartTime)return a}return await r(t,n,i)},refreshTarget:r})}function yt(e){return n({readinessPhase:`target-discovery`},e.reason)}function bt(e){return e instanceof o&&e.details?.reason===gt}function xt(e){return e instanceof o&&e.details?.reason===_t}async function St(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([Le(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:A(r)}),Ct(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 j(`simulator-target-probe-failed`,e,t);let c=wt(o.stdout,t);if(!c)throw j(_t,e,t);let l=await He(c.pid,{timeoutMs:Math.min(ht,A(r))});if(!l)throw j(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:Pe(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Ct(e,t,n){let r=t.get(e.id);if(r)return await r;let i=Le(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:A(n)}).then(t=>{if(t.exitCode!==0)throw j(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(Fe(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw j(`simulator-runtime-unavailable`,e,``);return n});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function wt(e,t){for(let n of e.split(` `)){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 A(e){return Math.max(1,e-Date.now())}function j(e,t,n){return new o(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:t.id,appBundleId:n})}function Tt(e){return e?.observation===`unobservable`&&e.proof===`no-running-process`}const Et=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function M(e){return e.platform===`apple`&&p(e)}function Dt(e){let t=ne(ie({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!M(n))return{observation:`not-eligible`};let a;for(;;){let o=await Ot(e.resolveTarget,n,r,i);if(`verdict`in o)return o.verdict;let{target:s}=o;if(e.isBridgeDisabled(s))return d({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:s.generation}}),N({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,f=Et.get(u);if(f===void 0)return N({source:`bridge`,kind:l,code:u});let p=e.clock.now();if(a=Math.min(a??1/0,p+f),p>=a)return{observation:`unobservable`,proof:`launch-transition`};await e.clock.sleep(Math.min(150,a-p),i)}}})}function N(e){return{observation:`probe-failed`,failure:e}}async function Ot(e,n,r,i){for(;;)try{return{target:await e(n,r,i)}}catch(e){if(i.throwIfAborted(),bt(e))continue;if(xt(e))return{verdict:{observation:`unobservable`,proof:`no-running-process`}};let{code:n,details:r}=t(e),a=r?.reason;return{verdict:N(typeof a==`string`?{source:`target`,code:n,reason:a}:{source:`target`,code:n})}}}const kt=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 At(e){return e===void 0?`possible`:e.some(e=>kt[e]===`runner`)?`required`:`none`}function jt(e,t,n){let r=n&&M(e),i=r?At(t.execution.plannedOperations):void 0,a=_(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function Mt(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function Nt(e,t,n,r,i,a){let s=Date.now(),c=async()=>await zt(t,n,r,i.observation),l=await c(),u,d,f=i.answerConfirmation,p=f&&l?.observation!==`observable`?await Pt(f,i.redispatchLaunchUrl,c,l):void 0;if(p&&(a.runnerDemand=`required`,u=p.report,d=p.probeFailure,l=p.observed,p.unanswered))throw new o(`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(r&&l?.observation!==`observable`&&await e.clock.sleep(300,t.signal),l&&(a.postOpenObservation=l.observation,l.observation===`probe-failed`&&(a.postOpenObservationFailure=l.failure)),a.postOpenSettleDurationMs=Math.max(0,Date.now()-s),u)return u;if(d)return{launchConfirmationProbeFailure:d}}async function Pt(e,t,n,r){let i={observed:r,acceptAttempted:!1,confirmationStillPresent:!1};for(let r=0;r<2;r+=1){i=await Ft(e,n,i);let a=r===1;if(i.confirmationStillPresent||a||!P(i)||!t)break;await t()}return{observed:i.observed,report:i.report,probeFailure:i.probeFailure,unanswered:P(i)||i.confirmationStillPresent}}async function Ft(e,t,n){let r=await e(),i=r.outcome===`unanswered`&&r.reason===`alert-still-present`,a=n.acceptAttempted||Rt(r),o=Lt(n,r);return a?{observed:await t(),...o,acceptAttempted:a,confirmationStillPresent:i}:{observed:n.observed,...o,acceptAttempted:a,confirmationStillPresent:i}}function It(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 Lt(e,t){let n=It(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 P(e){return e.acceptAttempted&&Tt(e.observed)}function Rt(e){return e.outcome===`accepted`||e.outcome===`unanswered`&&e.reason===`alert-still-present`||e.outcome===`unreadable`&&e.step===`alert-accept`}async function zt(e,t,n,r){if(!(!n||!M(e.device))&&!(!r||!t.appBundleId))return await r.awaitObservable(e.device,t.appBundleId,e.signal)}let Bt;const Vt=()=>Bt??=import(`./launch-confirmation.js`);let Ht;const Ut=()=>Ht??=import(`./expo-dev-client-launch.js`);function Wt(e){return F({...e,host:{...e.host,ensureReady:(t,n,r)=>D(e.host,t,n,r),shutdownTarget:(...t)=>e.host.deviceShutdown.apple.shutdownTarget(...t),resolveDevClientLaunchUrl:async(e,t)=>await(await Ut()).resolveExpoDevClientLaunchUrl(e,t),runnerFreeObservation:M(e.device)}})}function F(e){let t=t=>Oe({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 e.host.ensureReady(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 Gt(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 e.host.ensureReady(n,e.signal)),await rn(e.host,r,t)},finalizeApplicationClose:async t=>await an(e.host,n,e.signal,t),prepareAppleRunner:async t=>{let r=await on(e.host,n,e.signal,t);return i(r.readied),r.prepared},configureProviderPortReverse:fn})}async function Gt(e,t,n,r){let i={},a=L(t.device),o=sn(e,t,n,i),s=jt(t.device,n,e.runnerFreeObservation);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),Mt(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=nn(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Kt(e,t,n,a,l,i);let u=await qt(e,t,n,a,i),d=ln(t.device,u?{...n,runtimeLaunchUrl:u}:n,a);await Jt(o,c,n.prewarmRunnerBeforeOpen);let f=o.wasAwaited();await Yt(t,n,d,a,i),await $t(o,c,s.awaitPrewarmAfterOpen),await en(e,t,n,a,f,l);let p=await Nt(e,t,n,a,{observation:r,answerConfirmation:Zt(t,n,d),redispatchLaunchUrl:Qt(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 Kt(e,t,n,r,i,a){if(!tn(n,r)||!n.target)return;let o=Date.now();y(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await ke({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=R(o)}async function qt(e,t,n,r,i){if(!oe(n.runtimeHints))return;let a=Date.now(),s=r?await e.resolveDevClientLaunchUrl(t.device,n):void 0;if(!s){if(!n.applyRuntimeHints)throw new o(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await n.applyRuntimeHints({appId:n.appBundleId,values:n.runtimeHints})}return i.runtimeHintsDurationMs=R(a),s}async function Jt(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Yt(e,t,n,r,i){let a=Date.now();await S({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=R(a),await Xt(e,t,n.followUpUrl,i)}async function Xt(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i=Date.now();await I(e,t,n),r.launchUrlDurationMs=R(i)}async function I(e,t,n){let r={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0};await S({device:e.device,interactor:await e.resolveInteractor(r,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:r})}function Zt(e,t,{confirmation:n}){if(n)return async()=>{let{answerSimulatorLaunchConfirmation:r}=await Vt();return await r(e.device,n,e.resolveInteractor(t.execution,n.appBundleId),e.signal,t.execution.requestDeadlineAtMs)}}function Qt(e,t,{confirmation:n}){if(n)return async()=>{await I(e,t,n.url)}}async function $t(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function en(e,t,n,r,i,a){!_(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 tn(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function nn(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&tn(t,n)}async function rn(e,t,n){y(t.device.platform)&&!L(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await ke({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),L(t.device)&&await e.clock.sleep(300,t.signal)}async function an(e,t,n,r){r.daemonShutdown||await e.appleApplications.releaseRunnerOnClose(t.id,{retain:r.retainRunner}),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{});let i=r.shutdownTarget&&L(t)?await e.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function on(e,t,n,r){let i=Date.now()+r.timeoutMs,a=performance.now();return await u(`prepare_apple_runner`,async()=>{let o=await e.ensureReady(t,n,{deadlineAtMs:i}),s=Math.max(1,i-Date.now());return d({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 sn(e,t,n,r){let i,a=!1,o=cn(t.device,n)?{healthCheck:!1}:void 0;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,o?e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a,o):e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=R(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function cn(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function ln(e,t,n){let r=t.runtimeLaunchUrl?.trim(),i=t.positionals.length===1?t.positionals[0]?.trim():void 0;if(!r||!i||s(i))return{positionals:t.positionals};let a=un(e,t.appBundleId,r),o=a?{confirmation:a}:{};return n&&!dn(t)?{positionals:[i,r],...o}:{positionals:t.positionals,followUpUrl:r,...o}}function un(e,t,n){if(e.appleOs===`ios`&&e.kind===`simulator`&&!(t===void 0||c(n)))return{url:n,appBundleId:t}}function dn(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function L(e){return _(e)&&e.kind===`simulator`}function R(e){return Math.max(0,Date.now()-e)}async function fn(){throw new o(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const z=Object.freeze({available:!0}),pn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),B=gn(`Gestures are supported only for Apple simulators and devices.`),mn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:le}),hn=gn(`scroll is supported only for Apple simulators and devices.`);function gn(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function _n(e){return{..._e({unsupported:vn(e),plan:yn(e),directionalFling:yn(e),multiTouch:bn(e),targetAuthoredDrag:xn(e),viewport:Sn(e)}),...me({scroll:Cn(e)})}}function vn(e){return e.appleOs===`visionos`?pn:B}function yn(e){return e.appleOs===`visionos`?pn:V(e)?z:B}function bn(e){if(!V(e))return B;let t=h(e);if(t!==`ios`&&t!==`ipados`){let e=Re[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return z}function xn(e){return V(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?z:mn:B}function Sn(e){return V(e)?z:B}function Cn(e){return V(e)?z:hn}function V(e){return e.kind===`simulator`||e.kind===`device`}const H=Object.freeze({available:!0}),wn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),Tn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`visionOS has no back command. Press the visible back control by its ref.`});function En(e){return e.kind!==`simulator`&&e.kind!==`device`?wn:h(e)===`visionos`?Tn:H}const Dn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),On=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),kn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function An(e,t){return e.kind!==`simulator`&&e.kind!==`device`?t:h(e)===`macos`?On:H}function U(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=h(e);return t!==`tvos`&&t!==`macos`}const jn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),Mn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Nn(e){return e.kind!==`simulator`&&e.kind!==`device`?jn:U(e)?H:Mn}const Pn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function Fn(e){return(e.kind===`simulator`||e.kind===`device`)&&g(e)?H:Pn}const W=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function In(e){return U(e)?H:W}function Ln(e){return U(e)&&v(e)?H:W}const Rn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),zn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices, and on Apple Watch simulators.`}),Bn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone, iPad, and Apple Watch Ultra hardware; tvOS, macOS and visionOS have no such control.`});function Vn(e){return e.kind!==`simulator`&&e.kind!==`device`?zn:v(e)||e.appleOs===`watchos`?H:Bn}const Hn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`hardware-button volume presses the iPhone/iPad volume key; this Apple leaf has none.`}),Un=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 Wn(e){return v(e)?e.kind===`device`?H:Un:Hn}function Gn(e){return Object.freeze({...fe({back:En(e)}),...be({unsupported:Rn,home:An(e,Dn),appSwitcher:An(e,kn),actionButton:Vn(e),volumeUp:Wn(e),volumeDown:Wn(e)}),...Ce({orientation:Nn(e)}),...Te({tvRemote:Fn(e),buttonSupport:{supported:te(`apple`),unsupported:{available:!1,reason:`unsupported-platform-leaf`,hint:`This TV remote button is not supported on tvOS.`}}}),...Se({unsupported:W,status:Ln(e),dismiss:In(e),enter:In(e)})})}function Kn(e){let{host:t,device:n,signal:r,admitted:i}=e,a=Object.keys(Gn(n));return w({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Object.fromEntries(a.map(e=>[e,i[e]]))})}const G=Object.freeze({available:!0}),qn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),Jn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),Yn=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.`}),Xn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Run `agent-device settings --help` for the settings each target serves."}),Zn=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>.`}),Qn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Select a booted iPhone or iPad simulator: this setting runs only there.`}),$n=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.`});function er(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=h(e);return e.kind===`simulator`||r===`macos`?G:n}const tr=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 nr(e){return e.hostApp?tr:er(e,qn,$n)}const rr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),ir=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),ar=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function or(e){if(e.kind!==`simulator`&&e.kind!==`device`)return ir;let t=h(e);return e.kind===`simulator`||t===`ios`||t===`macos`?G:ar}function sr(e){return e.kind!==`simulator`&&e.kind!==`device`?rr:G}function cr(e){let t=nr(e);return t.available?$n:t}function lr(e){let t=e.hostApp?tr:er(e,Jn,Yn);if(m(e))return C({target:t,unsupported:Zn,write:{appearance:G,permission:G}});let n=p(e)?G:Qn;return C({target:t,unsupported:Xn,write:{wifi:G,airplane:G,location:G,appearance:G,"clear-app-state":G,"reset-keychain":G,permission:G,"text-size":n,faceid:n,touchid:n},read:{"text-size":n}})}function ur(e){let t=nr(e),n=or(e);return Object.freeze({...we({unsupported:cr(e),read:t,write:t}),...De({read:n,wait:n,accept:n,dismiss:n}),...Ee({triggerAppEvent:sr(e)}),...lr(e)})}function dr(e){let{host:t,device:n,signal:r}=e;return w({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:ur(n)})}const K=Object.freeze({available:!0}),fr=e(`unsupported-platform-leaf`);function pr(t){return e(`unsupported-device-kind`,t)}const mr=e(`unsupported-device-kind`,`focus is supported on Apple simulators and physical devices.`),hr=e(`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).`),gr=e(`unsupported-device-kind`),_r=pr(`snapshot is supported only for Apple simulators and devices.`),vr=e(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),yr=e(`owner-capability-missing`,`Open the app under test before capturing its snapshot.`);function br(e){return _(e)&&(e.kind===`simulator`||e.kind===`device`)?K:hr}function q(e){return e.kind===`simulator`||e.kind===`device`?K:mr}function xr(e){return e.kind===`simulator`||e.kind===`device`?K:gr}function Sr(e){return e.kind===`simulator`||e.kind===`device`?K:_r}function Cr(e){let t=Sr(e);return xe({capture:t,customActions:t.available&&_(e)&&e.kind===`simulator`?K:vr,withoutActiveApp:_(e)?yr:t})}function wr(e){return{appState:br(e),prepareAppleRunner:Er(e),...Cr(e),...he({findText:Sr(e),querySelector:_(e)?q(e):fr}),...ve({focus:q(e)}),..._n(e),...pe({type:q(e)}),...ce({unsupported:fr,tap:q(e),longPress:q(e),fill:q(e),..._(e)?{tapElementSelector:q(e)}:{}}),...ye({readTextAtPoint:xr(e)}),...Gn(e),...ur(e)}}const Tr=pr(`prepare is supported only for Apple simulators and devices.`);function Er(e){return e.kind===`simulator`||e.kind===`device`?K:Tr}function Dr(e,t){return Object.freeze({appState:async n=>{if(t.signal.throwIfAborted(),!n?.appBundleId||!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 i(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function Or(e,t,n){let r=ge({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=m(t.device)?ee(i.options?.surface,t.appBackend):void 0;if(a)return await e.snapshot.captureSurface(t.device,{...i.options,surface:a},de(t.signal,i));if(!n)return await r.captureSnapshot(i);let o=de(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 kr(e,t){return Object.freeze({findText:async n=>{let r=await Ar(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 Ar(e,t,n){let r=n.options?.appBundleId;if(r===void 0||m(t.device)&&b(n.options?.surface,t.appBackend)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await jr(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function jr(e,t,n){return!M(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Mr(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,t.probe);if(t.probe===`hittability`){let e=Nr(a);return Object.freeze({found:a.found===!0,...e?{hittability:e}:{}})}let o=Pr(a);return Object.freeze({found:a.found===!0,...o?{node:o}:{}})}})}function Nr(e){let{matchCount:t,hittable:n,rect:r}=e;if(typeof t!=`number`)return;let i=l(r);return Object.freeze({matchCount:t,...typeof n==`boolean`?{hittable:n}:{},...i?{rect:i}:{}})}function Pr(e){let t=e.nodes;if(!Array.isArray(t))return;let n=t[0];if(!n||typeof n!=`object`)return;let r=l(n.rect);if(r)return Object.freeze({rect:r,hittable:n.hittable===!0})}const Fr=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`],[`bridge-read-in-flight`,`bridge-read-busy`],[`snapshot-tree-changed`,`tree-changed`]]),Ir=new Set([`bridge-reader-wedged`]);function Lr(e){if(Ir.has(e.code))return{scope:`runner-session`,code:e.code};if(e.kind===`preparing`)return{scope:`capture`,code:e.code,consequence:`bridge-preparation`};let t=Rr(e);if(t)return{scope:`capture`,code:e.code,consequence:`system-surface-host`,surfaceHost:t};let n=Fr.get(e.code);return n?{scope:`capture`,code:e.code,consequence:n}:{scope:`generation`,code:e.code}}function Rr(e){if(e.code===`system-surface-host-unverified`)return`unverified`;if(e.code!==`system-surface-host-present`)return;let t=e.details?.surfaceHostExecutable;return x.find(e=>e.processExecutable===t)??`unverified`}const zr=`system-surface-presented`,Br=`system-surface-host-lingering`;function Vr(e,t,n){let{source:r}=t,i=e=>({sessionId:e,disabledGenerations:new Set,latestGeneration:new Map,sessionDisabled:!1}),a=i(),o=(e,t)=>(ii(t,e.latestGeneration,e.disabledGenerations),e.disabledGenerations.has(ai(t))),s=(e,n,r)=>{let o=t.circuit;if(o.scope!==`runner-session`)return e;let s=n.sessionId;return s===void 0?e:a===e?s===e.sessionId?e:(d({level:`debug`,phase:`ios_snapshot_route_runner_session_changed`,data:{deviceId:r.id,previousSessionId:e.sessionId,sessionId:s}}),a=i(s),o.sessionChanged(),a):s===a.sessionId?a:e};return Object.freeze({isBridgeDisabled:e=>o(a,e),shutdown:async()=>await r.close(),capture:async(i,c,l,d)=>{let f=Xr(i,c,t);if(f!==`bridge`)return await Y(i,c,d,{kind:f});let p=a,m=await Kr(i,c,l,n),h=s(p,m,i),{foreground:g}=m,_=e=>o(h,e);if(g!==`background`&&g!==`unknown`)return await Y(i,c,d,{kind:`surface`,detectedHost:g.host.bundleId});if(h.sessionDisabled)return $(`bridge-reader-wedged`,i),await Y(i,c,d,{kind:`reason`,lineage:X(i.id,c),reason:{scope:`runner-session`,code:`bridge-reader-wedged`},residue:[Z()]});let v;try{v=await Jr(t,i,c,l,_)}catch(e){Yr(l,e);let t=Ur(e,i,h);return await Y(i,c,d,{kind:`reason`,lineage:X(i.id,c),reason:t,residue:[Z()]})}if(_(v))return $(`circuit-disabled`,i,v.generation),await Y(i,c,d,{kind:`reason`,lineage:v,reason:`circuit-disabled`});let y=Q(c),b=await r.acquire({target:v,hint:ne(y),signal:l,...g===`unknown`?{surfaceHostExecutables:Gr}:{}});if(b.stage===`failed`){Hr(b.failure,l);let e=Wr(h,Lr(b.failure));if(`surfaceHost`in e)return await Zr(i,c,d,v,e);let n=await ri(b.failure,v,i,c.options.appBundleId,l,t);return await J(i,c,d,v,n,b.failure,e,h.disabledGenerations)}try{return await u(`ios.snapshot-source.present`,async()=>await e(b,c.options),{producer:`simulator-ax-bridge`})}catch(e){let t={kind:`malformed-tree`,code:`presentation-invariant`};return await J(i,c,d,v,{lineage:v,residue:[]},t,{scope:`generation`,code:t.code},h.disabledGenerations,e)}}})}function Hr(e,t){if(e.kind===`cancelled`)throw t.throwIfAborted(),new o(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:e.code,...e.details})}function Ur(e,t,n){let r=e instanceof Ue?Lr({kind:e.failureKind,code:e.failureCode}):void 0;return $(r?.scope===`runner-session`?r.code:`target-resolution-failed`,t,void 0,e),r?.scope===`runner-session`?Wr(n,r):`target-resolution-failed`}function Wr(e,t){return t.scope===`runner-session`?e.sessionId===void 0?{scope:`capture`,code:t.code,consequence:`bridge-read-busy`}:(e.sessionDisabled=!0,t):t}const Gr=x.map(e=>e.processExecutable);async function Kr(e,t,n,r){let i=t.execution?.requestId,a=await r(e,{signal:n,...i?{requestId:i}:{}});return a.foreground===`background`&&d({level:`debug`,phase:`ios_snapshot_route_surface_host_background`,data:{deviceId:e.id}}),a}async function qr(e,t,n,r){let i=n.options.appBundleId;for(;;)try{return await e.resolveTarget(t,i,r)}catch(r){let i={requestId:n.execution?.requestId};if(!await e.awaitsDiscovery?.(r,t,i))throw r}}async function Jr(e,t,n,r,i){let a=await qr(e,t,n,r);return e.resolutionVerifiesIdentity||!i(a)?a:await e.refreshTarget(t,n.options.appBundleId,r)}function Yr(e,t){if(e.aborted)throw r(t)?t:e.reason}function Xr(e,t,n){return t.options?.observeOnly&&!n.observeOnlySupported?`direct`:n.servesDevice(e)&&t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0?`bridge`:`off-route`}async function Zr(e,t,n,r,i){return i.surfaceHost===`unverified`?await Y(e,t,n,{kind:`reason`,lineage:r,reason:`system-surface-host-unverified`}):await Y(e,t,n,{kind:`surface`,detectedHost:i.surfaceHost.bundleId})}async function J(e,t,n,r,i,a,o,s,c){return o.scope===`generation`&&s.add(ai(r)),$(a.code,e,r.generation,c,a.details),await Y(e,t,n,{kind:`reason`,lineage:i.lineage,reason:o,residue:i.residue})}async function Y(e,t,n,r){let i=await n(t);if(r.kind===`direct`)return i;if(r.kind===`off-route`)return i.systemSurface?{...i,comparisonIdentity:ei($r(e.id,i.systemSurface.bundleId),Q(t),[])}:i;if(r.kind===`surface`){let n=i.systemSurface?zr:Br;return i.systemSurface||$(n,e,void 0,void 0,{detectedHost:r.detectedHost}),Qr(e.id,i,X(e.id,t),Q(t),n)}return Qr(e.id,i,r.lineage,Q(t),r.reason,r.residue)}function Qr(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:ei(o?$r(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],ti(i,n,o!==void 0)]}}function X(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function $r(e,t){return{targetId:`${e}:${t}`}}function ei(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:re(t),residue:Object.freeze([...n])})}function ti(e,t,n){if(e===zr)return`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`;if(e===Br)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`?ni(r,e.consequence):typeof e!=`string`&&e.scope===`runner-session`?`Simulator AX snapshot unavailable (${r}); used XCTest for this runner session.`:`Simulator AX snapshot unavailable (${r}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}function ni(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`bridge-read-busy`:return`${n} while an earlier bridge read was still running.`;case`foreground-ownership`:return`${n}, while another surface owned the foreground.`;case`tree-changed`:return`${n}, while the screen changed during the bridge read.`;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 ri(e,t,n,r,i,a){if(e.kind!==`stale-target`)return{lineage:t,residue:[]};try{return{lineage:await a.refreshTarget(n,r,i),residue:[]}}catch(e){return i.throwIfAborted(),$(`fallback-target-resolution-failed`,n,void 0,e),{lineage:{targetId:t.targetId},residue:[Z()]}}}function Z(){return{kind:`unknown-generation`,captureId:We()}}function Q(e){return ie({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 ii(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 ai(e){return`${e.targetId}:${e.generation}`}function $(e,t,n,r,i){d({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 oi=new Set([`notRunning`,`runningBackground`,`runningBackgroundSuspended`]),si=async e=>{let t=se(e.id);return t?.liveness===`ready`?{sessionId:t.sessionId}:void 0};function ci(e=si){return async(t,n)=>{let r=await e(t,n);if(!r)return{foreground:`unknown`};let i=x.map(e=>li(t,e.bundleId,r.sessionId,n));for(let e of i)e.catch(()=>{});for(let[e,t]of x.entries()){let n=await i[e];if(n===`runningForeground`)return{foreground:{kind:`foreground`,host:t},sessionId:r.sessionId};if(n===void 0||!oi.has(n))return{foreground:`unknown`,sessionId:r.sessionId}}return{foreground:`background`,sessionId:r.sessionId}}}async function li(e,t,n,r){try{let i=(await Ie(e,{command:`appState`,appBundleId:t},{signal:AbortSignal.any([r.signal,AbortSignal.timeout(1e3)]),expectedRunnerSessionId:n,...r.requestId?{requestId:r.requestId}:{}})).applicationState;return a(i)?i:void 0}catch{r.signal.throwIfAborted();return}}export{it as _,Or as a,wr as c,Wt as d,F as f,bt as g,vt as h,kr as i,dr as l,M as m,Vr as n,Dr as o,Dt as p,Mr as r,Er as s,ci as t,Kn as u,at as v,D as y};