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.

1 lines • 23.8 kB
import{$ as e,J as t,X as n,Y as r,d as i,jt as a,q as o,u as s}from"./sdk-batch.js";import{B as c,C as l,H as u,s as d,v as f}from"./sdk-contracts.js";import{a as p}from"./sdk-batch-runner.js";import{St as m,wt as h}from"./sdk-io.js";import"./diagnostics.js";import{A as g,K as _,R as v,w as y}from"./sdk-device.js";import{n as b,r as x}from"./success-text.js";import"./session-store.js";import{d as S,l as C,p as w,x as ee}from"./parameterized-recorded-fill.js";import{c as te,s as ne}from"./session-artifact-paths.js";import{n as re}from"./keyed-lock.js";import{a as T,m as E,n as D,t as O}from"./device-claim-rule.js";import{_ as ie,o as k,v as ae}from"./snapshot-runtime-capture-input.js";import{d as A,i as j,n as M,t as N}from"./device-claims.js";import{c as P,f as oe,u as F}from"./request.js";import{o as I}from"./lease-context.js";import{r as L}from"./session-tenant-scope.js";import{c as se,d as R,f as z,i as B,l as V,n as ce,r as le,s as ue}from"./session-runtime.js";import{n as de}from"./device-isolation.js";import{o as fe}from"./device-selector-intent.js";import{n as pe}from"./context.js";import{a as me,i as H}from"./session-routing.js";import{t as he}from"./runtime-admission.js";import{n as ge}from"./open-target-device-resolution.js";import{r as _e}from"./request-device-resolution.js";import{o as ve}from"./runtime-session.js";import{n as U,r as ye}from"./session-runtime-admission.js";import{n as be,r as xe}from"./device-selection-resolver.js";import{t as Se}from"./session-device-resolution.js";import{t as Ce}from"./snapshot-runtime.js";function W(e,t){let n=de(e.androidDeviceAllowlist,t);return n?[...n].sort():void 0}function we(e){return{serial:e.flags.serial,androidSerialAllowlist:W(e.flags,e.env),...e.deadlineAtMs===void 0?{}:{deadlineAtMs:e.deadlineAtMs}}}async function G(e){let{device:t,owner:n}=e;if(n.kind===`local-family`&&t.platform===`android`&&t.booted!==!0)return await(await e.bindDevice(t,a)).operations.ensureReady({androidSerialAllowlist:W(e.flags,e.env),deadlineAtMs:e.deadlineAtMs})}const Te=new Set(`acceptAlert.actionButton.appLogCleanup.appLogDoctor.appLogInspect.appLogReattach.appLogStart.appState.appSwitcher.applyRuntimeHints.audioProbeCleanup.audioProbeQuery.audioProbeReattach.audioProbeStart.awaitAlert.back.bootTarget.bootTargetHeadless.captureScreenshot.captureSnapshot.captureSnapshotWithCustomActions.captureSnapshotWithoutActiveApp.clearRuntimeHints.closeApplication.configureProviderPortReverse.deployApp.deployMaterializedApp.dismissAlert.ensureReady.fillPoint.fillRef.finalizeApplicationClose.findText.focusPoint.gestureViewport.home.hoverPoint.hoverRef.keyboardDismiss.keyboardEnter.keyboardStatus.listApps.longPressPoint.materializeAppSource.mediaFastForward.mediaNext.mediaPlayPause.mediaPrevious.mediaRewind.mute.networkDump.openApplication.perfFrames.perfMemorySample.perfMemorySnapshot.perfNativeCaptureCleanup.perfNativeCaptureReattach.perfNativeCaptureStart.perfProfileReport.performDirectionalFlingPlan.performGesturePlan.performMultiTouchGesturePlan.performTargetAuthoredDrag.power.prepareAppleRunner.prepareApplicationOpen.querySelector.readAlert.readClipboard.readSetting.readTextAtPoint.resolveOpenTarget.screenRecordingCleanup.screenRecordingReattach.screenRecordingStart.scrollDirection.sendPushNotification.sendTelephonyEvent.setFoldPose.setOrientation.setSetting.setViewport.shutdownTarget.sleep.tapElementSelector.tapPoint.tapRef.triggerAppEvent.tvRemote.typeText.uninstallApp.unlockOrientation.volumeDown.volumeUp.wake.writeClipboard`.split(`.`));function Ee(e){return Te.has(e)}const De=new Map(s.map(e=>[e.name,e]));function Oe(e){let t=new Set;for(let n of e){let e=ke(n);if(e===void 0)return;for(let n of e)t.add(n)}return Object.freeze([...t].sort())}function ke(e){let t=De.get(e.command)?.platformExecution;if(t===void 0)return;if(t.kind!==`device-runtime`)return[];let n=(`uses`in t?t.selectUses?.(e)??t.uses:[t.use]).flatMap(e=>e.required);return n.every(Ee)?n:void 0}function Ae(e,t){let n=i(e);return!n||!t?!1:n.some(e=>e.length>0&&e.every(e=>je(t,e)))}function je(e,t){return Object.hasOwn(e.operations,t)?e.operations[t]?.available===!0:!1}function Me(e){if(e!==void 0&&e.remainingSteps.length!==0)return Oe(e.remainingSteps)}function K(e,t,n){return{requestDeadlineAtMs:Ne(e),requestId:e.meta?.requestId,logPath:t,traceLogPath:n,verbose:e.flags?.verbose,activity:e.flags?.activity,launchConsole:e.flags?.launchConsole,launchArgs:e.flags?.launchArgs,clearAppState:e.flags?.clearAppState,iosXctestrunFile:e.flags?.iosXctestrunFile,iosXctestDerivedDataPath:e.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:e.flags?.iosXctestEnvDir,runnerLeaseContext:I(e),plannedOperations:Me(e.internal?.executionPlan)}}function Ne(e){let t=e.meta?.requestId;return P(t)??F(t)}function q(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Date.now()+e:void 0}function J(e){return d(`INVALID_ARGS`,e)}function Y(e,t,n,r,i){try{return e.resolveRequestedOpenSurface({device:t,surfaceFlag:n,openTarget:r,existingSurface:i})}catch(e){return d(e instanceof f?e.code:`INVALID_ARGS`,String(e.message),e instanceof f?e.details:void 0)}}async function Pe(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i,platformServices:a}=e;if(!t)return null;let o=await a.validateOpenRelaunchTarget({target:n,platform:i.platform,surface:r});return o?J(o):null}async function Fe(e){let{shouldRelaunch:t,openTarget:n,platform:r,platformServices:i}=e;if(!t)return null;let a=await i.validateOpenRelaunchTarget({target:n,platform:r});return a?J(a):null}function Ie(e){let t=R(e);if(!t.ok)return{type:`response`,response:t};let{runtime:n,previousRuntime:r,replacedStoredRuntime:i}=t.data;return{type:`plan`,plan:{runtime:n,previousRuntime:r,replacedStoredRuntime:i,applyRuntimeHints:le(n),clearRemovedRuntimeHints:V({replacedStoredRuntime:i,previousRuntime:r,runtime:n,session:e.existingSession})}}}async function Le(e){let{req:t,logPath:n,surface:r,openTarget:i,existingSession:a,runtime:o,runtimeHintPlan:s,clearRuntimeHints:c,foreground:l}=e;await o.operations.prepareApplicationOpen({target:i,currentAppBundleId:a?.appBundleId,hasExistingSession:a!==void 0,surface:r,prewarmRunnerOnColdBoot:r===`app`&&!!i&&!p(i??``),execution:{startupDeadlineAtMs:e.startupDeadlineAtMs,requestId:t.meta?.requestId,logPath:n,traceLogPath:a?.trace?.outPath,verbose:t.flags?.verbose,iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir,runnerLeaseContext:I(t)}});let{appBundleId:u,appName:d}=await Re({runtime:o,surface:r,openTarget:i,existingAppBundleId:a?.appBundleId,foreground:l});if(s.clearRemovedRuntimeHints){if(!c)throw new f(`COMMAND_FAILED`,`Runtime hint clear operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await B({replacedStoredRuntime:s.replacedStoredRuntime,previousRuntime:s.previousRuntime,runtime:s.runtime,session:a,clearRuntimeHints:c})}return{type:`details`,details:{appBundleId:u,appName:d,runtime:s.runtime}}}async function Re(e){let{runtime:t,surface:n,openTarget:r,existingAppBundleId:i,foreground:a}=e,o=await t.operations.resolveOpenTarget({target:r,currentAppBundleId:i,surface:n,foreground:a});return{appBundleId:o.appBundleId,appName:o.appName}}async function X(e){let{req:t,hasExistingSession:n}=e;return t.flags?.foreground===!0?t.positionals?.[0]?{type:`resolved`,req:t}:n?{type:`response`,response:d(`INVALID_ARGS`,`open --foreground only applies to a fresh session. Close the current session first, or omit --foreground.`)}:t.flags?.udid!==void 0||t.flags?.device!==void 0?{type:`response`,response:d(`INVALID_ARGS`,`open --foreground resolves the device itself; drop --udid/--device or open explicitly: agent-device open <app> --udid <udid>.`)}:t.flags?.platform!==void 0&&t.flags.platform!==`ios`?{type:`response`,response:d(`INVALID_ARGS`,`open --foreground only supports --platform ios; drop the flag or pass --platform ios.`)}:{type:`resolved`,req:fe(t)}:{type:`not-requested`}}async function ze(e){let{req:t,ref:n,logPath:r,sessionStore:i,openResponse:a}=e;if(!a.ok||t.flags?.foreground!==!0)return a;try{let o=await Ce({createCommandSurface:e.createCommandSurface,req:{...t,command:`snapshot`,positionals:[],flags:{...t.flags,snapshotInteractiveOnly:!0,noRecord:!0}},sessionName:n.address,sessionRef:n,logPath:r,sessionStore:i,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return o.ok?{ok:!0,data:{...a.data,snapshot:o.data}}:Be(a.data,o.error)}catch(e){return Be(a.data,c(e))}}function Be(e,t){return{ok:!0,data:{...e,warnings:[...b(e),`The session is open, but the initial interactive snapshot failed (${t.code}: ${t.message}). Run: agent-device snapshot -i`],initialSnapshotError:t}}}function Ve(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,appName:o,appBundleId:s,surface:c,startup:l,timing:u,device:d,runtime:f,runtimeHintCount:p,sessionReused:m,selection:h,launchConfirmation:g}=e,_={session:t,surface:c,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,sessionReused:m,...Ue(h)};return o&&(_.appName=o),s&&(_.appBundleId=s),l&&(_.startup=l),u&&(_.timing=u),Object.assign(_,g??{}),f&&p(f)>0&&(_.runtime=f),d&&Object.assign(_,He(d)),{..._,...x(`Opened: ${o??s??t}`)}}function He(e){let t={platform:v(e),target:e.target??`mobile`,device:e.name,id:e.id,kind:e.kind};return e.model&&(t.model=e.model),e.osVersion&&(t.osVersion=e.osVersion),g(e.platform)&&(t.serial=e.id),y(e)&&(t.device_udid=e.id,t.ios_simulator_device_set=e.simulatorSetPath??null),t}function Ue(e){if(!e)return{};let{device:t,...n}=e;return{selection:n}}function Z(e,t,n){n?(e.assertAdmissionOpen(n.address),e.requireCurrent(n)):e.assertPublishable(t)}function We(e){let{req:t,sessionStore:n,sessionName:r,existingRef:i,device:a,surface:o,appBundleId:s,appName:c,deviceClaim:l}=e;if(Z(n,r,i),i){let e=n.update(i,{device:a,surface:o,appBundleId:s,appName:c});return e.lease=E({req:t,existingLease:e.lease}),l&&(e.deviceClaim=l),ve(e),n.refresh(i)}return n.publish(r,{name:H(t),sessionScope:t.internal?.resolvedSessionScope??me(t),device:a,surface:o,appBundleId:s,appName:c,createdAt:Date.now(),actions:[],lease:E({req:t}),deviceClaim:l})}function Q(e,t){e.warnings=[...b(e),t]}function Ge(e){let{session:t,existingSession:n,saveScriptRequested:r,responseData:i,hostCwd:a}=e;if(!n&&r){S(t,{},a,e.remoteDelivery);let n=e.remoteDelivery?.publicationId;n&&(i.scriptPublicationId=n);return}w(n)&&(C(t),Q(i,`Script publication was aborted because this session completed a second open. Start a fresh session with open --save-script to author another script.`))}function Ke(e,t){return t.internal?.admittedLease?.backend===`macos-app`?`Took the device over: it rebooted after its previous claim was taken, so the previous app was already gone.`:`Took the device from session "${e.session}" in workspace "${e.workspace}": that device rebooted after its claim was taken, so its app and runner were already gone.`}function qe(e){switch(e.launchConfirmation){case`accepted`:return{launchConfirmation:`accepted`};case`unanswered`:return{launchConfirmation:`unanswered`,launchConfirmationReason:e.launchConfirmationReason};default:return e.launchConfirmationProbeFailure?{launchConfirmationProbeFailure:e.launchConfirmationProbeFailure}:{}}}function Je(){return"agent-device could not read whether iOS is asking to confirm the launch URL, so the launch URL may still be held by a prompt. Check with `alert get` before retrying."}function Ye(e){return e===`url-owner-unresolved`?"iOS is still holding the launch confirmation and the installed app that owns the launch URL's scheme could not be resolved, so this launch URL has not reached the app. Answer it with `alert accept`.":"iOS shows an alert this open did not recognize (alert-unrecognized), so it left the launch URL unconfirmed. The alert can be the launch confirmation in another language, or an alert of the app's own, such as a permission prompt. Read it with `alert get`. Answer with `alert accept` only when it is the launch confirmation; answer any other alert on its own terms."}function Xe(e,t){if(e.platform!==`android`)return!1;let n=t.flags?.testIme;return n===void 0?e.kind===`emulator`:n}function Ze(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:`open-command-roundtrip`,appTarget:t,appBundleId:n}}async function $(e,t,n){if(!t)return;let r=await A(t,n);if(r.status!==`renewed`)return r.conflict?D(e,r.conflict):d(`DEVICE_IN_USE`,`${e.name} no longer holds the claim this open was made with.`,{reason:`claim-lost-during-open`,deviceKey:t.deviceKey,hint:`Close this session and open the device again to claim it.`})}async function Qe(e){let{req:t,sessionName:n,sessionStore:r,logPath:i,device:a,openTarget:o,openPositionals:s,appName:c,surface:p,appBundleId:g,runtimeHints:_,lifecycle:v,applyRuntimeHints:y,existingRef:b,deviceClaim:x,tookOverDeviceClaim:S,selection:C}=e;Z(r,n,b);let w=b?r.requireCurrent(b):void 0,re=w?.snapshot,T=t.flags?.relaunch===!0,E=g,D=Date.now(),O=await $e({req:t,sessionName:n,sessionStore:r,device:a,surface:p,sessionAppBundleId:E,appName:c,existingRef:b});if(O.type===`response`)return O;let k=O.ref;Z(r,n,k);let A=k?r.requireCurrent(k):void 0,j=Date.now(),M=()=>{b&&T&&r.resolveCurrent(b)&&r.markCloseEffectsUnconfirmed(b)},N=await v.operations.openApplication({target:o,positionals:s,outPath:t.flags?.out,runtimeLaunchUrl:_?.launchUrl,appBundleId:E,surface:p,hasExistingSession:w!==void 0,relaunch:T,prewarmRunnerBeforeOpen:t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,enableTestIme:Xe(a,t),stateDir:r.resolveDaemonStateDir(),runtimeHints:ue(_),applyRuntimeHints:y,execution:K(t,i,A?.trace?.outPath)}).catch(e=>{throw e instanceof f&&(u(e.details)===`no`||e.details?.reason===`runtime-hints-operation-missing`)||M(),e});E=N.appBundleId??E;let P={...N.timing},F=be(C),I=o?Ze(j,o,E):void 0;if(oe(t.meta?.requestId)){M();let e=l();return{type:`response`,response:d(e.code,e.message,e.details)}}Z(r,n,k),b&&ie({session:r.requireCurrent(b),command:`open`,positionals:[],flags:void 0,androidFreshnessBaseline:re});let L=r.ensureSessionDir(n),R=ne(L,t.meta?.requestId??h().requestId);P.totalDurationMs=Math.max(0,Date.now()-D),m({level:`info`,phase:`open_timing`,durationMs:P.totalDurationMs,data:P});let z=Ve({sessionName:A?.name??H(t),sessionStateDir:L,runnerLogPath:te(L),requestLogPath:R,eventLogPath:r.resolveEventLogPath(n),appName:c,appBundleId:E,surface:p,startup:I,timing:P,device:a,runtime:_,runtimeHintCount:ce,sessionReused:w!==void 0,selection:F,launchConfirmation:qe(N)});S&&Q(z,Ke(S,t)),N.launchConfirmation===`unanswered`&&Q(z,Ye(N.launchConfirmationReason)),N.launchConfirmation===void 0&&N.launchConfirmationProbeFailure&&Q(z,Je());let B=We({req:t,sessionStore:r,sessionName:n,existingRef:k,device:a,surface:p,appBundleId:E,appName:c,deviceClaim:x});r.clearCloseEffectsUnconfirmed(B);let V=r.requireCurrent(B);return ae(V,P.postOpenObservation,t.flags),t.runtime!==void 0&&se(r,n,_),Ge({session:V,existingSession:b?V:void 0,saveScriptRequested:!!t.flags?.saveScript,remoteDelivery:ee(t.meta),responseData:z,hostCwd:r.host.cwd}),r.recordAction(B,{command:`open`,positionals:s,flags:t.flags??{},runtime:t.runtime===void 0?void 0:_,result:z}),{type:`opened`,ref:B,response:{ok:!0,data:z}}}async function $e(e){let{req:t,sessionName:n,sessionStore:r,existingRef:i}=e,a=t.internal?.openLifecycle?.beforeDispatch;if(!a)return{type:`session`,ref:i};let o=We({req:t,sessionName:n,sessionStore:r,existingRef:i,device:e.device,surface:e.surface,appBundleId:e.sessionAppBundleId,appName:e.appName}),s=await a();return s&&!s.ok?{type:`response`,response:s}:(Z(r,n,o),{type:`session`,ref:r.refresh(o)})}async function et(e){let{req:t,device:n,owner:r,sessionName:i,sessionStore:a,reconcileOrphanedDeviceClaim:o,platformServices:s}=e;switch(O(r)){case`none`:return{status:`not-required`};case`ordinary`:return await M({device:n,session:i,workspace:pe(t,e.host),stateDir:a.resolveDaemonStateDir(),env:e.host.env,reconcileOrphanedDeviceClaim:o,observeDeviceBoot:s.deviceBootObservation})}}async function tt(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,device:a,surface:o,openTarget:s,lifecycle:c,runtimeHintPlan:l,applyRuntimeHints:u,clearRuntimeHints:d,reconcileOrphanedDeviceClaim:f,selection:p,platformServices:m}=e;Z(i,n,void 0);let h=T({req:t,device:a,sessionStore:i});if(h)return{type:`response`,response:h};let g=await et({host:e.host,req:t,device:a,owner:c.owner,sessionName:n,sessionStore:i,reconcileOrphanedDeviceClaim:f,platformServices:m});if(g.status===`conflict`)return{type:`response`,response:D(a,g.conflict)};let _=g.status===`acquired`?g.ownership:void 0,v=g.status===`acquired`?g.tookOver:void 0,y={mayHaveStarted:!1},b=async()=>await nt({ownership:_,effects:y,sessionName:n,sessionStore:i,env:e.host.env});try{Z(i,n,void 0);let f=await Le({req:t,startupDeadlineAtMs:e.startupDeadlineAtMs,logPath:r,surface:o,openTarget:s,runtime:c,runtimeHintPlan:l,clearRuntimeHints:d,foreground:t.flags?.foreground===!0&&s===void 0});if(f.type===`response`)return await b(),{type:`response`,response:f.response};let m=await $(a,_,e.host.env);if(m)return{type:`response`,response:m};y.mayHaveStarted=!0;let h=t.positionals??[],g=s??f.details.appBundleId,x=await Qe({req:t,sessionName:n,sessionStore:i,logPath:r,device:a,openTarget:g,openPositionals:h.length>0?h:g?[g]:[],appBundleId:f.details.appBundleId,appName:f.details.appName,runtimeHints:f.details.runtime,lifecycle:c,applyRuntimeHints:u,surface:o,deviceClaim:_,tookOverDeviceClaim:v,selection:p});return x.response.ok||await b(),x}catch(e){throw await b(),e}}async function nt(e){let{ownership:t,effects:n,sessionName:r,sessionStore:i,env:a}=e;if(!t)return;if(!n.mayHaveStarted){await j(t,a);return}if(i.get(r)?.deviceClaim?.ownerToken===t.ownerToken)return;let o=await N(t,a);m({level:`warn`,phase:`device_claim_open_effects_unconfirmed`,data:{deviceKey:t.deviceKey,outcome:o}})}const rt=new WeakMap;function it(e){let t=rt.get(e);return t||(t=new Map,rt.set(e,t)),t}function at(e){return e.hostApp?.hostDeviceId??e.id}async function ot(i){let a=e({applyRuntimeHints:i.runtimeHintPlan.applyRuntimeHints,clearRemovedRuntimeHints:i.runtimeHintPlan.clearRemovedRuntimeHints}),s=await he({...i,command:`open`,required:a.use.required});if(s.type===`response`)return s;let c=s.bind;switch(a.kind){case`open`:return{type:`runtime`,runtime:await c(i.device,o)};case`open-apply-runtime-hints`:{let e=await c(i.device,r);return{type:`runtime`,runtime:e,applyRuntimeHints:e.operations.applyRuntimeHints}}case`open-clear-runtime-hints`:{let e=await c(i.device,n);return{type:`runtime`,runtime:e,clearRuntimeHints:e.operations.clearRuntimeHints}}case`open-apply-and-clear-runtime-hints`:{let e=await c(i.device,t);return{type:`runtime`,runtime:e,applyRuntimeHints:e.operations.applyRuntimeHints,clearRuntimeHints:e.operations.clearRuntimeHints}}}}async function st(e){let t=Ie(e);if(t.type===`response`)return t;let n=await ot({device:e.device,runtimeHintPlan:t.plan,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return n.type===`response`?n:{type:`runtime`,runtimeHintPlan:t.plan,admission:n}}async function ct(e){let{req:t,session:n,platformServices:r}=e,i=await X({req:t,hasExistingSession:!0});if(i.type===`response`)return i;if(t.flags?.saveScript)return{type:`response`,response:d(`INVALID_ARGS`,`open --save-script can only arm a fresh session. Use the current session without --save-script, or close it and start a fresh session.`)};let a=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(a?n.appName:void 0),c=Y(r,n.device,t.flags?.surface,s,n.surface);if(typeof c!=`string`)return{type:`response`,response:c};if(!s&&c===`app`)return{type:`response`,response:J(a?`open --relaunch requires an app name or an active session app.`:`Session already active. Close it first or pass a new --session name.`)};let l=await Pe({shouldRelaunch:a,openTarget:s,surface:c,device:n.device,platformServices:r});return l?{type:`response`,response:l}:{type:`resolved`,requestedOpenTarget:o,openTarget:s,surface:c}}async function lt(e){let{sessionName:t,logPath:n,sessionStore:r}=e,i=r.lookup(t),a=await X({req:e.req,hasExistingSession:!!i});if(a.type===`response`)return{type:`response`,response:a.response};let o=a.type===`resolved`?a.req:e.req;Z(r,t,i);let s=q(o.flags?.timeoutMs);if(i){let a=r.requireCurrent(i);z(a)&&_(L(o));let c=await ct({req:o,session:a,platformServices:e.platformServices});if(c.type===`response`)return c;let{requestedOpenTarget:l,openTarget:u,surface:d}=c,f=r.requireCurrent(i),p=await $(f.device,f.deviceClaim,e.host.env);if(p)return{type:`response`,response:p};let m=await Se(a.device,e.platformServices,e.host.env),h=xe(m);await o.internal?.retainDeviceExecutionLock?.(m.id);let g=await st({req:o,sessionStore:r,sessionName:t,device:m,existingSession:a,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(g.type===`response`)return{type:`response`,response:g.response};let{admission:v,runtimeHintPlan:y}=g;Z(r,t,i);let b=r.requireCurrent(i);k(b);let x=await Le({req:o,startupDeadlineAtMs:s,logPath:n,surface:d,openTarget:u,existingSession:b,runtime:v.runtime,runtimeHintPlan:y,clearRuntimeHints:v.clearRuntimeHints,foreground:!1});if(x.type===`response`)return{type:`response`,response:x.response};Z(r,t,i);let S=await $(m,r.requireCurrent(i).deviceClaim,e.host.env);return S?{type:`response`,response:S}:await Qe({req:o,sessionName:t,sessionStore:r,logPath:n,device:m,openTarget:u,openPositionals:l?o.positionals??[]:u?[u]:[],appBundleId:x.details.appBundleId,appName:x.details.appName,runtimeHints:x.details.runtime,lifecycle:v.runtime,applyRuntimeHints:v.applyRuntimeHints,surface:d,existingRef:i,selection:h})}let c=o.flags?.relaunch===!0,l=o.positionals?.[0];if(c&&!l)return{type:`response`,response:J(`open --relaunch requires an app argument.`)};let u=await Fe({shouldRelaunch:c,openTarget:l,platform:o.flags?.platform===`android`?`android`:void 0,platformServices:e.platformServices});if(u)return{type:`response`,response:u};let d=await _e(o,ge(o,e.host.env));await o.internal?.retainDeviceExecutionLock?.(d.device.id);let f=Y(e.platformServices,d.device,o.flags?.surface,l);if(typeof f!=`string`)return{type:`response`,response:f};let p=await Pe({shouldRelaunch:c,openTarget:l,surface:f,device:d.device,platformServices:e.platformServices});if(p)return{type:`response`,response:p};let m=async n=>await st({req:o,sessionStore:r,sessionName:t,device:n,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}),h=await m(d.device);if(h.type===`response`)return{type:`response`,response:h.response};let g=await G({device:d.device,owner:h.admission.runtime.owner,bindDevice:U(e.bindDevice),flags:o.flags??{},env:e.host.env,deadlineAtMs:s}),v=g?{...d,device:g}:d,y=v.device;if(g&&(await o.internal?.retainDeviceExecutionLock?.(y.id),h=await m(y),h.type===`response`))return{type:`response`,response:h.response};let{admission:b,runtimeHintPlan:x}=h;return await re(it(r),at(y),async()=>await tt({host:e.host,req:o,startupDeadlineAtMs:s,sessionName:t,logPath:n,sessionStore:r,device:y,surface:f,openTarget:l,lifecycle:b.runtime,runtimeHintPlan:x,applyRuntimeHints:b.applyRuntimeHints,clearRuntimeHints:b.clearRuntimeHints,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim,platformServices:e.platformServices,selection:v}))}async function ut(e){let t=await lt(e),n=t.response;return t.type!==`opened`||e.req.flags?.foreground!==!0?n:await ze({...e,inspectFacts:ye(e.inspectFacts),bindDevice:U(e.bindDevice),openResponse:n,ref:t.ref})}export{we as a,ut as handleSessionOpenCommands,G as i,K as n,W as o,Ae as r,ct as resolveExistingOpenRequest,X as resolveForegroundOpenRequest,q as t};