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.
5 lines • 49.7 kB
JavaScript
import{Mn as e,jn as t,wn as n}from"./sdk-batch.js";import{B as r,v as i}from"./sdk-contracts.js";import{a}from"./sdk-batch-runner.js";import{St as o,q as s}from"./sdk-io.js";import"./diagnostics.js";import{J as c}from"./sdk-device.js";import{i as l,n as u}from"./recording-stop-observation.js";import{n as d,t as f}from"./android-snapshot-quality.js";import{n as p}from"./device-shell.js";import{n as m}from"./adb-failure.js";import"./retry.js";import{i as h,o as g}from"./adb.js";import{a as ee,r as te}from"./durable-resource.js";import{n as ne}from"./screen-recording-runtime.js";import{n as _,r as v,t as y}from"./application-lifecycle-runtime.js";import{n as re}from"./async-lifecycle.js";import{i as ie}from"./touch-runtime.js";import{t as b}from"./mp4-duration.js";import{r as x,t as S}from"./gesture-admission.js";import{readAndroidAppStateWithExecutor as ae}from"./app-state.js";import{ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_HINT as oe}from"./clipboard-shell-response.js";import{androidAppDeploymentFacts as se,createAndroidAppDeploymentOperations as ce,t as C}from"./runtime2.js";import{createAndroidPerfOperations as le}from"./runtime3.js";import{C as ue,D as de,F as fe,M as pe,O as me,R as he,V as ge,W as _e,_ as ve,h as ye,j as be,l as xe,o as Se,p as Ce,r as we,v as Te,x as Ee}from"./tv-remote-runtime.js";import{n as De}from"./audio-probe-runtime.js";import{n as Oe}from"./perf-runtime.js";import{a as ke,i as Ae}from"./screenshot-runtime2.js";import{t as je}from"./viewport-runtime.js";import{a as Me,n as Ne,o as Pe,s as Fe,u as Ie}from"./application-lifecycle-interaction.js";import{t as Le}from"./local-interactor-operation-set.js";import{n as Re,t as ze}from"./network-traffic.js";import{a as Be,n as Ve,t as He}from"./src10.js";import{n as Ue}from"./screen-recording-completion.js";import{a as We,i as w,o as Ge,s as Ke,t as qe}from"./stop-sequence.js";import{t as Je}from"./fold-runtime.js";import{t as Ye}from"./app-log-runtime.js";import T from"node:path";async function E(e,t,n){let r=await h(e,[`emu`,...t],{signal:n,allowFailure:!0,timeoutMs:1e4});if(r.exitCode!==0)throw m(`adb emu ${t.slice(0,2).join(` `)} exited with code ${r.exitCode}`,r,{deviceId:e.id});let i=/^KO\b:?[ \t]*(.*)$/m.exec(r.stdout);return i?{stdout:r.stdout,refusal:i[1].trim()}:{stdout:r.stdout}}const D=Object.freeze({closed:{id:`1`,state:`CLOSED`},"half-open":{id:`2`,state:`HALF_OPENED`},open:{id:`3`,state:`OPENED`}});async function Xe(e,t,n={}){let{signal:r}=n;r?.throwIfAborted();let i=Qe(e,t),a=await $e(e,r),s=D[i],c=Ze(e,i,a),l=i===`closed`&&await it(e,r);return await et(e,i,s.id,r),o({level:`info`,phase:`android_fold_pose_dispatched`,data:{deviceId:e.id,pose:i}}),await tt(e,i,c,a,r),i===`closed`&&!l&&await rt(e,r),{pose:i,hingeAngleDegrees:await at(e,r)}}function Ze(e,t,n){let r=D[t],a=n.get(r.state);if(a!==void 0)return a;let o=Object.keys(D).filter(e=>n.has(D[e].state)),s=o.map(e=>D[e].state);throw s.length===0?new i(`UNSUPPORTED_OPERATION`,`${e.name} is not a foldable emulator: it lists no CLOSED, HALF_OPENED, or OPENED device state`,{deviceId:e.id,reason:`single-panel-device`,hint:`fold poses the hinge of a foldable emulator such as the Pixel 9 Pro Fold; this emulator lists no CLOSED, HALF_OPENED, or OPENED device state, so it has no hinge to pose.`}):new i(`UNSUPPORTED_OPERATION`,`${e.name} has no ${r.state} device state to commit for the ${t} pose; it lists ${s.join(`, `)}`,{deviceId:e.id,reason:`fold-posture-unsupported`,requestedPose:t,supportedPoses:o,deviceStates:s,hint:`This profile poses only ${o.join(` and `)}; request one of those.`})}function Qe(e,t){if(t.pose===void 0)throw new i(`UNSUPPORTED_OPERATION`,`fold keyframes are not supported on Android`,{deviceId:e.id,reason:`fold-keyframes-unsupported`,hint:`The emulator console poses the hinge at fixed angles only; request closed, half-open, or open.`});return t.pose}async function $e(e,t){let{stdout:n}=await O(e,[`cmd`,`device_state`,`print-states`],t),r=new Map;for(let e of n.matchAll(/identifier=(\d+), name='([A-Z_]+)'/g))r.set(e[2],e[1]);return r}async function et(e,t,n,r){let a=await E(e,[`posture`,n],r);if(a.refusal!==void 0)throw new i(`COMMAND_FAILED`,`Unable to set the emulator posture for ${t}`,{deviceId:e.id,reason:`fold-posture-dispatch-failed`,stdout:a.stdout.trim(),hint:`The emulator console refused the posture. Check that the AVD is a foldable profile (hw.sensor.hinge=yes), then retry.`})}async function tt(e,t,n,r,a){let o;for(let t=1;t<=60;t+=1)if(a?.throwIfAborted(),t>1&&await s(250,a),o=await nt(e,a),o===n)return;let c=[...r].find(([,e])=>e===o)?.[0];throw new i(`COMMAND_FAILED`,`${e.name} did not reach the ${t} pose: the emulator still reports device state ${c??o}`,{deviceId:e.id,requestedPose:t,observedDeviceState:c??o,reason:`fold-pose-unverified`,hint:"The emulator console accepted the posture, but the guest did not commit the matching device state. Read it directly with `adb shell cmd device_state print-state` to see which state the emulator holds."})}async function nt(e,t){let{stdout:n}=await O(e,[`cmd`,`device_state`,`print-state`],t);return/\d+/.exec(n)?.[0]}async function rt(e,t){let n=0,r=!1;for(let i=1;i<=60;i+=1)if(await s(250,t),await it(e,t))n=0,r=!0,await O(e,[`wm`,`dismiss-keyguard`],t);else if(n+=1,n>=3)break;if(n<3)throw new i(`COMMAND_FAILED`,`${e.name} stays locked after the fold`,{deviceId:e.id,reason:`fold-lock-screen-persists`,hint:"The fold lit a panel Android keeps locked and `wm dismiss-keyguard` did not clear it; a keyguard with a PIN or password has to be unlocked by hand."});r&&o({level:`info`,phase:`android_fold_lock_screen_dismissed`,data:{deviceId:e.id}})}async function it(e,t){let{stdout:n}=await O(e,[`dumpsys`,`window`],t);return n.includes(`isKeyguardShowing=true`)}async function at(e,t){let{stdout:n}=await E(e,[`sensor`,`get`,`hinge-angle0`],t),r=/hinge-angle0\s*=\s*(-?\d+(?:\.\d+)?)/.exec(n);if(!r)throw new i(`COMMAND_FAILED`,`${e.name} reports no hinge angle`,{deviceId:e.id,reason:`fold-hinge-angle-unreadable`,stdout:n.trim(),hint:"The emulator console answered the posture but exposes no hinge-angle0 sensor to read back; check that the AVD is a foldable profile (hw.sensor.hinge=yes) and that the emulator build supports `sensor get hinge-angle0`."});return Number(r[1])}async function O(e,t,n){let r=await g(e,t,{signal:n,allowFailure:!0});if(r.exitCode!==0)throw m(`adb shell ${t.join(` `)} exited with code ${r.exitCode}`,r,{deviceId:e.id});return r}const ot=Object.freeze({available:!0}),st=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold poses the hinge of a foldable Android emulator through the emulator console; a physical device is folded by hand.`});function ct(e){return e.kind===`emulator`?ot:st}function lt(e){return Je({fold:ct(e)})}function ut(t){let{device:n,signal:r}=t;return e(lt(n).setFoldPose,()=>({setFoldPose:async e=>(r.throwIfAborted(),await Xe(n,e,{signal:r}))}))}async function dt(e,t,n){let r=await E(e,ft(t),n);if(r.refusal!==void 0)throw new i(`COMMAND_FAILED`,`The emulator console refused telephony ${t.action}`,{deviceId:e.id,reason:`telephony-console-refused`,stdout:r.stdout.trim(),...r.refusal?{consoleReason:r.refusal}:{},hint:`The emulator console refused the event. accept needs a call from that same number (start one with telephony call <number>), and an emulator image without a modem has no telephony to simulate.`})}function ft(e){switch(e.action){case`call`:case`accept`:case`cancel`:return[`gsm`,e.action,e.number];case`sms`:return[`sms`,`send`,e.number,pt(e.text)]}}function pt(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`
`,String.raw`\n`)}const mt=Object.freeze({available:!0}),ht=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`telephony simulates calls and SMS through the Android emulator console; a physical device has no console, so place a real call or send a real message to it instead.`});function gt(e){return e.kind===`emulator`?mt:ht}function _t(e){return Object.freeze({sendTelephonyEvent:gt(e)})}function vt(t){let{device:n,signal:r}=t;return e(_t(n).sendTelephonyEvent,()=>({sendTelephonyEvent:async e=>{r.throwIfAborted(),await dt(n,e,r)}}))}function yt(e){return We(e)?Object.freeze({available:!0}):e.kind===`emulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio probe capture is supported for Android emulators on macOS hosts.`})}function bt(e){if(!/^[a-zA-Z0-9._:-]+$/.test(e))throw new i(`INVALID_ARGS`,`Invalid Android package name for logs: ${e}`)}const k=Object.freeze({resourceKind:Ye,version:1,encode:e=>({...e}),decode:e=>e.transport!==`android-logcat-local`&&e.transport!==`android-logcat-transport-composed`||!St(e.outputPath)||!St(e.pidPath)?{status:`invalid`,message:`Invalid Android app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:e.transport,outputPath:e.outputPath,pidPath:e.pidPath})}});function xt(e){let t=k.decode(e.descriptor);if(t.status!==`decoded`)throw TypeError(t.message);return te({resourceKind:Ye,sessionId:e.sessionId,device:{id:e.device.id,family:`android`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:ee(k,t.descriptor)})}function St(e){return typeof e==`string`&&e.trim().length>0}function Ct(e){return He(e,{family:`android`,backend:`android`,label:`Android`,codec:k,startUnavailableHint:`The selected Android transport cannot start a background adb logcat stream.`,cleanupFailureMessage:`Android app-log cleanup did not settle every owned resource`,doctor:async({host:e,device:t,signal:n},r)=>await wt(e,t.id,r,n),validateStart:({input:e})=>bt(e.appBundleId),process:async({host:e,device:t,input:n})=>({resolvePid:async r=>await Ve(e,Tt(t.id,n.appBundleId),r),command:e=>({kind:`android-adb`,serial:t.id,args:[`logcat`,`-v`,`time`,`--pid`,e],options:{allowFailure:!0}})}),descriptor:({artifacts:e,transport:t})=>({transport:t.mode===`transport-composed`?`android-logcat-transport-composed`:`android-logcat-local`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>xt({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function wt(e,t,n,r){let i={};return i.adbAvailable=await Ke(async()=>Ge(await e.commands.run({executable:`adb`,args:p(`adb`,`shell`,[`echo`,`ok`],[`-s`,t]),allowFailure:!0,timeoutMs:1e3},r)),r),n&&(i.androidPidVisible=await Ke(async()=>!!await Ve(e,Tt(t,n),r),r)),{backend:`android`,checks:i,notes:n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}}function Tt(e,t){return{executable:`adb`,args:p(`adb`,`shell`,[`pidof`,t],[`-s`,e]),allowFailure:!0,timeoutMs:5e3}}async function Et(e,t,n,r){let i=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),a=Re(i.text,{...n,path:i.path,exists:i.exists,lineNumberOffset:i.skippedLines,backend:`android`}),o=[],s=await Ot(e,t,n,r);if(s&&n.appBundleId){bt(n.appBundleId);let c=await At(e,t,n.appBundleId,r);if(c){let e=Re(c.text,{...n,path:`${i.path} (adb logcat recovery)`,exists:!0,backend:`android`});e.dump.entries.length>0&&(a=ze(e,a,n.maxEntries),o.push(s.reason===`stale-active`?`Session app log stream was still bound to prior Android PID ${s.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`))}}return n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&o.length===0&&o.push(`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):o.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`),a.dump.entries.length===0&&o.push(`No HTTP(s) entries were found in recent session app logs.`),Object.freeze({source:`app-log`,backend:`android`,dump:a.dump,notes:Object.freeze(o)})}async function Dt(e,t,n){n.throwIfAborted();try{let r=await e.commands.run(t,n);return n.throwIfAborted(),r}catch{n.throwIfAborted();return}}async function Ot(e,t,n,r){if(!n.appBundleId||n.appLogSnapshot?.state===void 0)return;if(n.appLogSnapshot.state!==`active`)return{reason:`inactive`};let i=kt(await e.appLogs.readProcessMarker(n.sessionId));if(!i)return;let a=await jt(e,t.id,n.appBundleId,r);if(!(!a||a===i))return{reason:`stale-active`,trackedPid:i}}function kt(e){if(e.status===`decoded`)return/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(e.marker.command)?.[1]}async function At(e,t,n,r){let i=await jt(e,t.id,n,r),a=await Dt(e,{executable:`adb`,args:[`-s`,t.id,`logcat`,`-d`,`-v`,`time`,`-t`,`4000`],allowFailure:!0,timeoutMs:3e3},r);if(!a||a.exitCode!==0||!a.stdout.trim())return;let o=Mt(a.stdout,n,i);if(o.length===0)return;let s=new Set(o),c=a.stdout.split(`
`).filter(e=>{if(!e.trim())return!1;if(e.includes(n))return!0;let t=/\(\s*(\d+)\)\s*:/.exec(e)?.[1];return!!(t&&s.has(t))}).join(`
`);return c.trim()?{text:c,pids:o}:void 0}async function jt(e,t,n,r){let i=await Dt(e,{executable:`adb`,args:p(`adb`,`shell`,[`pidof`,n],[`-s`,t]),allowFailure:!0},r);if(!i)return;let a=i.stdout.trim().split(/\s+/)[0];return a&&/^\d+$/.test(a)?a:void 0}function Mt(e,t,n){let r=new Set(n?[n]:[]),i=t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),a=[RegExp(`\\bStart proc\\s+(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`\\b(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`${i}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,`i`),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${i}`,`i`)];for(let n of e.split(`
`))if(n.includes(t))for(let e of a){let t=e.exec(n)?.[1];t&&/^\d+$/.test(t)&&r.add(t)}return Object.freeze([...r])}function A(e,t){if(t===1)return e;let n=T.parse(e);return T.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const Nt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,Pt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function Ft(e){return Rt(e)&&zt(e)&&Bt(e)}function It(e){if(!j(e))return!1;let t=e;return Vt(t)&&Ht(t)&&Ut(t)&&Wt(t)&&(t.completion===void 0||Zt(t))}function Lt(e,t){return Qt(e,t)&&$t(e,t.outputPath,t.clientOutputPath)}function Rt(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&Pt.test(e.manifestPath)&&typeof e.outputPath==`string`}function zt(e){return tn(e.clientOutputPath)&&w(e)}function Bt(e){return en(e.transportMode)}function Vt(e){return e.version===1&&e.resourceKind===`screen-recording`&&typeof e.fenceToken==`string`&&Number.isInteger(e.fenceGeneration)&&typeof e.sessionId==`string`&&typeof e.deviceId==`string`&&Number.isFinite(e.startedAt)}function Ht(e){return typeof e.outputPath==`string`&&tn(e.clientOutputPath)&&w(e)}function Ut(e){return en(e.transportMode)&&(e.pendingRemotePath===void 0||nn(e.pendingRemotePath))}function Wt(e){return Array.isArray(e.chunks)&&e.chunks.every(Gt)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||Kt(e.completion))}function Gt(e,t){if(!j(e))return!1;let n=e;return n.index===t+1&&nn(n.remotePath)&&rn(n.remotePid)&&rn(n.remoteStartTime)}function Kt(e){if(!j(e))return!1;let t=e;return Jt(t)&&Yt(t)&&qt(t)&&(t.chunks===void 0||t.chunks.every(Xt))}function qt(e){return(e.stopObservation===void 0||u(e.stopObservation))&&(e.nativePathDisposition===void 0||l(e.nativePathDisposition))}function Jt(e){return typeof e.backend==`string`&&typeof e.outPath==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)&&Number.isFinite(e.startedAt)&&Number.isFinite(e.completedAt)&&(e.capturedDurationMs===void 0||Number.isFinite(e.capturedDurationMs))}function Yt(e){return w(e)}function Xt(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function Zt(e){let t=e.completion;return t!==void 0&&Qt(t,e)&&t.startedAt===e.startedAt&&$t(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function Qt(e,t){return e.backend===`adb screenrecord`&&e.outPath===t.outputPath&&e.clientOutPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&an(e.activeSessionApp,t.activeSessionApp)}function $t(e,t,n,r=e.chunks===void 0?1:e.chunks.length){return r===1?e.chunks===void 0:e.chunks?.length===r&&e.chunks.every((e,r)=>e.path===A(t,r+1)&&e.clientOutPath===(n===void 0?void 0:A(n,r+1)))}function j(e){return typeof e==`object`&&!!e}function en(e){return e===`local`||e===`transport-composed`}function tn(e){return e===void 0||typeof e==`string`}function nn(e){return typeof e==`string`&&Nt.test(e)}function rn(e){return typeof e==`string`&&/^\d+$/.test(e)}function an(e,t){return JSON.stringify(e)===JSON.stringify(t)}const M=Object.freeze({resourceKind:ne,version:1,encode:e=>({...e}),decode:e=>Ft(e)?{status:`decoded`,descriptor:Object.freeze({backend:`adb-screenrecord`,manifestPath:e.manifestPath,outputPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutputPath:e.clientOutputPath},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,transportMode:e.transportMode,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps}})}:{status:`invalid`,message:`Invalid Android screen-recording descriptor`}});function on(e){return{outputPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutputPath:e.clientOutputPath},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}}}function N(e,t,n,r,i,a=`local`){return Object.freeze({version:1,resourceKind:`screen-recording`,fenceToken:t.fence.token,fenceGeneration:t.fence.generation,sessionId:t.sessionId,deviceId:e.id,startedAt:n,...on(t),chunks:r,...i===void 0?{}:{pendingRemotePath:i},transportMode:a})}function sn(e,t){return Object.freeze({...e,completion:t})}function P(e){try{let t=e&&JSON.parse(e);return It(t)?t:void 0}catch{return}}function cn(e,t,n){return e.deviceId===t.id&&e.deviceId===n.device.id&&e.fenceToken===n.fence.token&&e.fenceGeneration===n.fence.generation&&e.sessionId===n.sessionId}function ln(e,t){return e.outputPath===t.outputPath&&e.clientOutputPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&JSON.stringify(e.activeSessionApp)===JSON.stringify(t.activeSessionApp)&&e.exportQuality===t.exportQuality&&e.fps===t.fps&&e.transportMode===t.transportMode&&(e.completion===void 0||Lt(e.completion,t))}function F(e){switch(e){case`missing`:case`ownership-lost`:case`foreign-writer`:return!0;case`owned-alive`:case`uncertain`:return!1}}function un(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const dn=1e4,fn=1e3;var I=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}},L=class extends Error{constructor(){super(`Android screenrecord rotation refused: the recording stop was already claimed`)}};function R(e,t=Date.now()){return[...new Set(e?[e,`/sdcard`,`/data/local/tmp`]:[`/sdcard`,`/data/local/tmp`])].map(e=>`${e}/agent-device-recording-${t}.mp4`)}async function pn(e,t,n,r){let i;try{if(i=(await e.start({remotePath:t,quality:n.exportQuality??`medium`},r)).process,!/^\d+$/.test(i.pid)||!/^\d+$/.test(i.startTime)||i.remotePath!==t)throw Error(`Android screenrecord returned an invalid process identity`);if(!await vn(e,t,i,r))throw Error(`Android screenrecord did not begin producing frames`);return{index:1,remotePath:t,remotePid:i.pid,remoteStartTime:i.startTime}}catch(t){throw i&&mn(i)&&!await yn(e,i)?new I(t):r?.aborted?r.reason:t}}function mn(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function z(e,t){let n=t.at(-1),r=!1,i;for(let a of[...t].reverse())try{let t=await H(e,a);a===n&&(r=t)}catch(e){i??=e}if(i)throw i;return r}async function hn(e,t){for(let n of t){let t;for(let r=0;r<3;r+=1){let i=await e.size(n.remotePath);if(typeof i==`number`&&i>0&&i===t)break;if(t=typeof i==`number`&&i>0?i:void 0,r===2)throw Error(`Android recording artifact is not stable: ${n.remotePath}`);await new Promise(e=>setTimeout(e,250))}}}async function gn(e,t,n){for(let[r,i]of t.entries())await bn(e,i.remotePath,A(n,r+1))}async function B(e,t){let n;for(let r of t)try{if(!await e.remove(r.remotePath))throw Error(`failed to remove Android recording artifact: ${r.remotePath}`)}catch(e){n??=e}if(n)throw n}async function _n(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function V(e,t){try{await z(e,t)}finally{await B(e,t)}}async function vn(e,t,n,r){for(let i=0;i<3;i+=1){r?.throwIfAborted();let a=await e.size(t,r);if(typeof a==`number`&&a>0)return!0;if(await e.inspect(n,r)!==`owned-alive`)return!1;i<2&&await new Promise(e=>setTimeout(e,250))}return!0}async function yn(e,t){try{let n=await e.stop(t,{force:!0});return(n===`stopped`||n===`already-missing`)&&await e.remove(t.remotePath)}catch{return!1}}async function H(e,t){if(!t)return!1;let n={pid:t.remotePid,remotePath:t.remotePath,startTime:t.remoteStartTime},r=await e.stop(n);if(r===`already-missing`)return!0;if(r===`ownership-lost`)throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.remotePid}`);if(await xn(e,n))return!1;let i=await e.stop(n,{force:!0});if(i===`stopped`||i===`already-missing`)return!1;throw Error(`failed to stop Android screenrecord pid ${t.remotePid}`)}async function bn(e,t,n){for(let r=0;r<3;r+=1){let i=await e.pullPlayable({remotePath:t,outputPath:n});if(i.exitCode===0&&i.playable)return;r+1<3&&await Sn(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function xn(e,t){for(let n=0;n<=dn;n+=fn){let r=await e.inspect(t);if(r===`missing`)return!0;if(F(r))throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.pid}`);n<dn&&await Sn(fn)}return!1}function Sn(e){return new Promise(t=>setTimeout(t,e))}async function U(e,t,n,r){await e.writeManifest({manifestPath:t,contents:JSON.stringify(n)},r)}async function W(e,t){if(!await e.removeManifest(t))throw Error(`failed to remove Android recording manifest: ${t}`)}async function Cn(e,t){return await Promise.all(t.map(async t=>({chunk:t,state:await e.inspect({pid:t.remotePid,remotePath:t.remotePath,startTime:t.remoteStartTime})})))}async function wn(e,t){let n=(await Tn(e)).flatMap(n=>En(n,t,e.mode));for(let t of n)await On(e,t.evidence,t.manifestPath)}async function Tn(e){return await Promise.all(R(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function En(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw jn(e.manifestPath,e.read.message);let r=P(e.read.contents);if(r===void 0)throw Mn(e.manifestPath);if(r.transportMode!==n)throw Nn(e.manifestPath,r,n);if(!Dn(r,t))throw Pn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function Dn(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function On(e,t,n){if(await kn(e,t),await B(e,t.chunks),await An(e,t),await W(e,n),(await e.readManifest(n)).status!==`missing`)throw Ln(n)}async function kn(e,t){for(let{chunk:n,state:r}of await Cn(e,t.chunks))if(!un(r))throw r===`uncertain`?Rn(n.remotePath):Fn(n.remotePath,r===`owned-alive`?`named-recorder`:`other-recorder`);let n=t.pendingRemotePath;if(n===void 0)return;let r=await e.probeRunningWriters(n);if(r.writers.length>0)throw Fn(n,`other-recorder`);if(!r.conclusive)throw Rn(n)}async function An(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw In(n)}function jn(e,t){return new i(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unavailable: ${e}`,{reason:`native_recovery_evidence_unavailable`,manifestPath:e,hint:`Confirm the device is online and its storage readable, then run record start again.`},Error(t))}function Mn(e){return new i(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unreadable: ${e}`,{reason:`native_recovery_evidence_unreadable`,manifestPath:e,hint:G(e)})}function Nn(e,t,n){return new i(`COMMAND_FAILED`,`Android screenrecord native recovery evidence was written by the ${t.transportMode} transport, not this ${n} one: ${e}`,{reason:`native_recovery_evidence_transport_mismatch`,manifestPath:e,evidenceTransportMode:t.transportMode,hint:G(e)})}function Pn(e,t,n){return new i(`DEVICE_IN_USE`,`Android screenrecord native recovery evidence already exists: ${e} (open recording of session "${t.sessionId}" on ${n.id})`,{reason:`native_recovery_evidence_open`,manifestPath:e,sessionId:t.sessionId,retriable:!1,hint:`Run record stop --session ${t.sessionId} to retire it, or close that session. If it is already closed, ${G(e)}`})}function Fn(e,t){let n=t===`named-recorder`;return new i(`DEVICE_IN_USE`,`Android screenrecord recovery evidence is retained: ${n?`its recorder`:`another recorder`} is writing ${e}`,{reason:`native_recording_artifact_claimed`,remotePath:e,writer:t,...n?{retriable:!1}:{},hint:n?`Run record stop for the session that owns that recording before starting another.`:`Android ends any recorder after 180 seconds. Run record start again once that recorder has stopped.`})}function In(e){return new i(`COMMAND_FAILED`,`Android screenrecord recovery evidence could not remove ${e}`,{reason:`native_recording_artifact_removal_failed`,remotePath:e,hint:`Confirm the device is online and run record start again.`})}function Ln(e){return new i(`COMMAND_FAILED`,`Android screenrecord recovery evidence removal could not be confirmed: ${e}`,{reason:`native_recovery_evidence_retirement_unconfirmed`,manifestPath:e,hint:`Run record start again; the marker is retired from the beginning.`})}function Rn(e){return new i(`COMMAND_FAILED`,`Android screenrecord recovery evidence cannot be safely retired: ${e}`,{reason:`native_recording_recorder_unproven`,remotePath:e,hint:`Confirm the device is online and run record start again.`})}function G(e){return`no recording session can retire this marker; remove it on the device with \`adb shell rm -f ${e}\`.`}async function zn(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await wn(t,n),await o();let s;for(let e of R(void 0)){let o=t.manifestPathFor(e);await U(t,o,N(n,r,i,[],e,t.mode),a);let c,l;try{l=Date.now(),c=await pn(t,e,r,a)}catch(e){if(a.aborted)throw await Bn(t,o,e),a.reason;await Un(t,o,e),s=e;continue}try{await U(t,o,N(n,r,i,[c],void 0,t.mode),a)}catch(e){throw await Vn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function Bn(e,t,n){n instanceof I||await W(e,t).catch(()=>{})}async function Vn(e,t,n){try{await V(e,[n])}catch{return}await W(e,t).catch(()=>{})}async function Hn(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s,launchAdmission:c}=e,l;for(let e of R(s)){if(c.aborted)throw new L;await U(t,o,N(n,r,i,a,e,t.mode));try{if(c.aborted)throw new L;return await pn(t,e,r)}catch(e){if(e instanceof I)throw e;try{await U(t,o,N(n,r,i,a,void 0,t.mode))}catch{throw new I(e)}l=e}}throw l??Error(`failed to start next Android recording chunk`)}async function Un(e,t,n){if(n instanceof I)throw n;try{await W(e,t)}catch{throw new I(n)}}function Wn(e,t){return Object.freeze({backend:`adb screenrecord`,outPath:e.outputPath,...e.clientOutputPath?{clientOutPath:e.clientOutputPath}:{},startedAt:t,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp?{activeSessionApp:e.activeSessionApp}:{},...e.exportQuality?{exportQuality:e.exportQuality}:{},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[]})}function Gn(e){let t=Kn(e.chunkPaths);if(t===void 0)return{};let n=e.stoppedAtMs-e.startedAtMs;return n-t<2e3?{capturedDurationMs:t}:{capturedDurationMs:t,idleTailWarning:`Android screenrecord encodes a frame only when the screen changes, so this video ends at the last frame it encoded: it covers ${qn(t)}s of the ${qn(n)}s recording window.`}}function Kn(e){let t=0;for(let n of e){let e=b(n);if(e===void 0)return;t+=e}return t}function qn(e){return(e/1e3).toFixed(1)}async function Jn(e){let{host:t,transport:n,evidence:r,recording:i,startedAtMs:a,progress:o}=e,s=e.reachedLimit===!0;return await $n(e,await qe({snapshot:i,progress:o,steps:{stop:async()=>(s=await z(n,r.chunks)&&e.activeRecorderRetired!==!0||s,await hn(n,r.chunks),{observation:{recorder:`confirmed`},...s?{warning:`Android adb screenrecord stopped before record stop, likely after reaching the 180s platform limit. The MP4 may be truncated; final interactions after the limit are not in the video.`}:{}}),collect:e=>gn(n,r.chunks,e),finalize:({collectedPath:e,exportPath:n,stoppedAtMs:o})=>Yn({host:t,evidence:r,recording:i,startedAtMs:a,stoppedAtMs:o,collectedPath:e,exportPath:n}),discard:e=>Zn(t,e,r.chunks.length)}}))}async function Yn(e){let{host:t,evidence:n,recording:r,collectedPath:i,exportPath:a}=e,o=er({collectedPath:i,exportPath:a,exportClientPath:r.clientOutPath,count:n.chunks.length}),s=o.length>1,c;try{await Xn(t,o),c=await t.screenRecording.finalize.complete({outputPath:a,showTouches:!s&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,...r.fps===void 0?{}:{fps:r.fps},targetLabel:`Android recording`})}catch(e){for(let{served:e}of o)await t.screenRecording.outputs.remove(e.path);throw e}let l=Gn({chunkPaths:o.map(({collected:e})=>e.path),startedAtMs:e.startedAtMs,stoppedAtMs:e.stoppedAtMs});return Qn({finalization:c,captured:l,recording:r,chunked:s,files:o})}async function Xn(e,t){for(let{collected:n,served:r}of t)await e.screenRecording.outputs.copy({from:n.path,to:r.path})}async function Zn(e,t,n){for(let r=1;r<=n;r+=1)await e.screenRecording.outputs.remove(A(t,r))}function Qn(e){let{finalization:t,captured:n,recording:r,chunked:i,files:a}=e,o=[t.warning,...i?[`Android adb screenrecord is capped at 180s, so this recording was split into multiple MP4 chunks.`]:[],n.idleTailWarning].filter(e=>e!==void 0&&e.length>0);return{...t.telemetryPath===void 0?{}:{telemetryPath:t.telemetryPath},...o.length===0?{}:{warning:o.join(` `)},...i&&r.showTouches&&r.gestureEvents.length>0?{overlayWarning:`touch overlay burn-in is skipped for chunked Android recordings; returning raw chunks plus gesture telemetry`}:{},...n.capturedDurationMs===void 0?{}:{capturedDurationMs:n.capturedDurationMs},...i?{chunks:a.map(e=>e.served)}:{},nativePathDisposition:`retirable`}}async function $n(e,t){let{transport:n,evidence:r,manifestPath:i}=e;return await U(n,i,sn(r,t.result)),await B(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await _n(n,r.chunks)}}}function er(e){return Object.freeze(Array.from({length:e.count},(t,n)=>({collected:Object.freeze({index:n+1,path:A(e.collectedPath,n+1)}),served:Object.freeze({index:n+1,path:A(e.exportPath,n+1),...e.exportClientPath===void 0?{}:{clientOutPath:A(e.exportClientPath,n+1)}})})))}async function tr(e,t,n){try{let r=t.pendingRemotePath,i=await nr(e,t.chunks);if(await z(e,[...i.stoppable,...await ir(e,t)]),await rr(e,i.retired),await B(e,t.chunks),r!==void 0&&!await e.remove(r))throw Error(`failed to remove Android recording artifact: ${r}`);return await W(e,n),{status:`cleaned`}}catch(e){return sr(e)}}async function nr(e,t){let n=[],r=[];for(let i of t){let[t]=await Cn(e,[i]).catch(()=>[]),a=t?.state;a===`ownership-lost`||a===`foreign-writer`?r.push(i):n.push(i)}return{stoppable:n,retired:r}}async function rr(e,t){let n;for(let r of t)try{await ar(e,r)}catch(e){n??=e instanceof Error?e:Error(String(e))}if(n)throw n}async function ir(e,t){let n=t.pendingRemotePath;if(n===void 0)return[];let r=await e.probeRunningWriters(n);if(!r.conclusive)throw or(n);return r.writers.map((e,r)=>({index:t.chunks.length+1+r,remotePath:n,remotePid:e.pid,remoteStartTime:e.startTime}))}async function ar(e,t){let n=await e.probeRunningWriters(t.remotePath);if(!n.conclusive)throw or(t.remotePath);let r=n.writers.at(0);if(r)throw Error(`Android artifact is still written by pid ${r.pid}: ${t.remotePath}`)}function or(e){return Error(`cannot list every recorder writing Android artifact: ${e}`)}function sr(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function cr(e){let{transport:t,device:n,envelope:r,descriptor:i}=e;if(i.transportMode!==t.mode)return{status:`transport-unavailable`};let a=await t.readManifest(i.manifestPath);if(a.status===`unavailable`)return{status:`transport-unavailable`};let o=a.status===`read`?P(a.contents):void 0;return o&&cn(o,n,r)&&ln(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function lr(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=P(t.contents);return n&&ur(n,e)?n:void 0}function ur(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function dr(e){let{host:t,transport:n,device:r,input:i}=e,a=M.decode(i.envelope.descriptor.body);if(a.status!==`decoded`)return K(`descriptor-invalid`);let o=await cr({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await pr({host:t,transport:n,device:r,input:i,descriptor:a.descriptor,evidence:o.evidence}):K(o.status===`transport-unavailable`?`transport-not-reattachable`:`ownership-fence-lost`)}async function fr(e){let t=M.decode(e.input.envelope.descriptor.body);if(t.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`};let n=await cr({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await tr(e.transport,n.evidence,t.descriptor.manifestPath):n.status===`transport-unavailable`?{status:`cleanup-pending`,reason:`owner-unavailable`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function pr(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0){let e=await mr(n,o);return e.status===`terminal`?{status:`completed`,result:{...o.completion,nativePathDisposition:e.nativePathDisposition}}:K(`ownership-fence-lost`,`Android recording completed evidence still names a live or unverifiable recorder.`)}if(o.pendingRemotePath!==void 0)return K(`transport-not-reattachable`,`Android recording launch was interrupted before its process identity was committed.`);let s=o.chunks.at(-1);if(!s)return{status:`missing`};let c=await n.inspect({pid:s.remotePid,remotePath:s.remotePath,startTime:s.remoteStartTime});if(c!==`owned-alive`&&await n.exists(s.remotePath)===!1)return K(`transport-not-reattachable`,`Android recording process ended before its artifact could be recovered.`);let l=hr(i.envelope.sessionId,i.envelope.fence,a),u=!1;return{status:`active`,handle:Ue(Wn(l,o.startedAt),{finish:async(e,r)=>{let i=await Jn({host:t,transport:n,evidence:o,manifestPath:a.manifestPath,recording:e,startedAtMs:o.startedAt,reachedLimit:F(c),progress:r});return u=!0,i},forceCleanup:async()=>u?{status:`cleaned`}:await fr({transport:n,device:r,input:i})})}}async function mr(e,t){try{for(let n of t.chunks)if(!F(await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime})))return{status:`retained`};return{status:`terminal`,nativePathDisposition:await _n(e,t.chunks)}}catch{return{status:`retained`}}}function hr(e,t,n){return{sessionId:e,outputPath:n.outputPath,...n.clientOutputPath===void 0?{}:{clientOutputPath:n.clientOutputPath},scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:!1,recordOnlySession:n.recordOnlySession,...n.activeSessionApp===void 0?{}:{activeSessionApp:n.activeSessionApp},...n.exportQuality===void 0?{}:{exportQuality:n.exportQuality},...n.fps===void 0?{}:{fps:n.fps},fence:t}}function K(e,t){return{status:`unreattachable`,reason:e,...t===void 0?{}:{message:t}}}async function gr(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.android.resolve(n);return Object.freeze({screenRecordingStart:async e=>await _r({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await dr({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await fr({transport:a,device:n,input:e})})}async function _r(e){let{host:t,transport:n,device:r,owner:i,input:a,signal:o}=e;o.throwIfAborted();let s=Date.now(),l=await zn({transport:n,device:r,input:a,startedAt:s,signal:o,prepareOutput:async()=>await t.screenRecording.outputs.prepare(a.outputPath)}),u=l.manifestPath,d=[l.chunk],f,p,m,h=`recording`,g=!1,_=new AbortController,v=()=>{f&&clearTimeout(f),_.abort(),h===`recording`&&(h=`stopping`)},y=()=>h===`recording`,ie=()=>{h=`finished`},b=()=>{y()&&(f=setTimeout(()=>{p=ce().catch(e=>{m=e})},17e4),f.unref?.())},x=(e,t)=>N(r,a,s,e,t,n.mode),S=async e=>await Hn({transport:n,device:r,input:a,startedAt:s,chunks:d,manifestPath:u,preferredDir:T.posix.dirname(e.remotePath),launchAdmission:_.signal}),ae=async e=>{try{return{chunk:await S(e),previousStopped:!1}}catch(t){if(t instanceof L)throw t;if(_.signal.aborted)throw new L;await H(n,e)||(g=!0);try{return{chunk:await S(e),previousStopped:!0}}catch(e){throw e instanceof Error?e:t}}},oe=async e=>{await V(n,[e]),await U(n,u,x(d)).catch(()=>{})},se=async(e,t,r)=>{if(await V(n,[e]).then(()=>!1,()=>!0)||r){await U(n,u,x(d,e.remotePath)).catch(()=>{});return}try{await U(n,u,x(d))}catch{await H(n,t).catch(()=>{}),await U(n,u,x(d,e.remotePath)).catch(()=>{})}},ce=async()=>{let e=d.at(-1);if(!e)throw Error(`Android recording has no active chunk`);let t,r;try{({chunk:t,previousStopped:r}=await ae(e))}catch(e){if(e instanceof L)return;throw e}if(!y()){await oe(t);return}let i=[...d,{...t,index:d.length+1}];try{await U(n,u,x(i))}catch(n){throw await se(t,e,r),n}d=i,g=!1,r||await H(n,e),b()};b();let C=Ue(Wn(a,s),{finish:async(e,r)=>{if(v(),await p,m)throw m;let i=await Jn({host:t,transport:n,evidence:x(d),manifestPath:u,recording:e,startedAtMs:l.startedAtMs,progress:r,activeRecorderRetired:g});return ie(),i},forceCleanup:async()=>{if(v(),h===`finished`)return{status:`cleaned`};try{await p}catch(e){m=e}let e=await lr({transport:n,deviceId:r.id,sessionId:a.sessionId,fence:a.fence,manifestPath:u});return e?await tr(n,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new re(C),envelope:te({resourceKind:ne,sessionId:a.sessionId,device:c(r),owner:i,fence:a.fence,lifecycle:`open`,descriptor:ee(M,{backend:`adb-screenrecord`,manifestPath:u,...on(a),transportMode:n.mode})})})}async function vr(e,t,n){try{let r=await e.snapshot({appBundleId:t,signal:n,transient:{settleBy:Date.now()+6e3}});return{observation:`androidSnapshot`in r&&r.androidSnapshot?.systemSurfaceOnly===!0?`unobservable`:`observable`}}catch(e){return n.throwIfAborted(),f(e)?{observation:`unobservable`}:{observation:`probe-failed`,failure:yr(e)}}}function yr(e){let t=r(e),n=d(t)??t.details?.reason,{code:i}=t;return typeof n==`string`?{source:`capture`,code:i,reason:n}:{source:`capture`,code:i}}function br(e){let{host:t,device:n,signal:r}=e,a=Ne({device:n,signal:r,resolveInteractor:t.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async e=>await t.androidApplications.resolveOpenTarget(n,e),prepareApplicationOpen:async e=>{await C(t,n,{headless:!1,deadlineAtMs:e.execution.startupDeadlineAtMs},r)},openApplication:async e=>await xr(t,a,e),applyRuntimeHints:async e=>await t.androidApplications.applyRuntimeHints(n,e),clearRuntimeHints:async e=>await t.androidApplications.clearRuntimeHints(n,e),closeApplication:async e=>{if(e.ensureReady&&await C(t,n,{headless:!1},r),e.mode===`kill`){let[t]=e.positionals;if(!t)throw new i(`INVALID_ARGS`,`Kill requires an app target`);let{killAndroidApp:r}=await import(`./app-lifecycle.js`).then(e=>e.n);await r(n,t);return}await Pe({device:n,interactor:await a.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async e=>{await t.androidApplications.restoreTestIme(n,{stateDir:e.stateDir,shutdownTarget:e.shutdownTarget===!0&&n.kind===`emulator`,signal:r});let i=e.shutdownTarget&&n.kind===`emulator`?await t.deviceShutdown.android.shutdownTarget(n,r):void 0;return i===void 0?{}:{shutdown:i}},prepareAppleRunner:Cr,configureProviderPortReverse:Cr})}async function xr(e,t,n){let r={},a=n.relaunch&&!!n.target,o=a?n.appBundleId:void 0;if(o){let e=Date.now();await Pe({device:t.device,interactor:await t.resolveInteractor(n.execution,o),positionals:[o]}).catch(async e=>{let{passedAndroidRelaunchStopFences:t}=await import(`./app-lifecycle.js`).then(e=>e.n);if(!t(e))throw e}),r.relaunchCloseDurationMs=q(e)}if(v(n.runtimeHints)){if(!n.applyRuntimeHints)throw new i(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let e=Date.now();await n.applyRuntimeHints({appId:n.appBundleId,values:n.runtimeHints}),r.runtimeHintsDurationMs=q(e)}let s=Date.now(),c=await Fe({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals,appBundleId:n.appBundleId,execution:n.execution,terminateRunningApp:a&&!o});r.openDispatchDurationMs=q(s),n.enableTestIme&&await e.androidApplications.activateTestIme(t.device,{stateDir:n.stateDir});let l=Me(n);if(l){let e=Date.now();await Fe({device:t.device,interactor:await t.resolveInteractor({...n.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},n.appBundleId),positionals:[l],appBundleId:n.appBundleId,execution:{...n.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),r.launchUrlDurationMs=q(e)}else r.launchUrlDurationMs=0;let u=await e.androidApplications.inferOpenedAppBundleId(t.device,n.target,n.appBundleId,c?.launchedAppBundleId);u&&await e.androidApplications.resetFramePerfStats(t.device,u);let d=Date.now();return Object.assign(r,await Sr(t,n,u)),r.postOpenSettleDurationMs=q(d),{appBundleId:u,timing:r}}async function Sr(e,t,n){if(!t.target||a(t.target))return{};if(!n)return{postOpenObservation:`app-unidentified`};let r=await vr(await e.resolveInteractor(t.execution,n),n,e.signal);return r.observation===`probe-failed`?{postOpenObservation:`probe-failed`,postOpenObservationFailure:r.failure}:{postOpenObservation:r.observation}}function q(e){return Math.max(0,Date.now()-e)}async function Cr(){throw new i(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Android.`)}const J=n(`android`),Y=Object.freeze({available:!0}),wr=t(`unsupported-device-kind`),Tr=t(`unsupported-platform-leaf`,"Run `agent-device settings --help` for the settings each target serves."),Er=t(`unsupported-device-kind`,`focus is supported on Android emulators and physical devices.`),Dr=t(`unsupported-device-kind`,`keyboard actions are supported on Android emulators and physical devices.`),Or=t(`unsupported-platform-leaf`),kr=t(`unsupported-platform-leaf`,`Android has no key event for this system button.`),Ar=t(`unsupported-device-kind`,`Headless boot is supported only for Android emulators.`),jr=t(`unsupported-device-kind`,`Android appstate is supported only for Android emulators and devices.`),Mr=t(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),Nr=t(`unsupported-device-kind`,`open is supported only for Android emulators and devices.`),Pr=t(`unsupported-device-kind`,`close is supported only for Android emulators and devices.`),Fr=t(`unsupported-device-kind`,`Runtime hints are supported only for Android emulators and devices.`),Ir=t(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),Lr=t(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),Rr=t(`unsupported-device-kind`,`screenshot is supported only for Android emulators and devices.`),X=t(`unsupported-device-kind`,`snapshot is supported only for Android emulators and devices.`),zr=t(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),Br=t(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web).`),Vr=t(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Android targets use the host capture.`);function Hr(e){let t=Ur(e),n=Wr(e),r=Gr(e);return y({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:r,clearRuntimeHints:r,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Mr,configureProviderPortReverse:Ir})}function Ur(e){return e.kind===`emulator`||e.kind===`device`?Y:Nr}function Wr(e){return e.kind===`emulator`||e.kind===`device`?Y:Pr}function Gr(e){return e.kind===`emulator`||e.kind===`device`?Y:Fr}const Z=t(`unsupported-device-kind`,`Gestures are supported on Android emulators and physical devices.`),Kr=t(`unsupported-platform-leaf`,S),qr=t(`unsupported-platform-leaf`,x);function Jr(e,t){return e.kind===`simulator`?Z:e.target===`tv`?t:Y}function Q(e){return e.kind===`simulator`?Z:Y}function $(e){return e.kind===`simulator`?Er:Y}const Yr=t(`owner-capability-missing`,oe),Xr=t(`owner-capability-missing`,`Could not determine whether this Android build supports a shell clipboard: the adb probe did not complete. Retry once the device is reachable.`);async function Zr(e,t){let n=e.androidTools?.probeClipboardShellSupport;return n?await n.call(e.androidTools,t):`probe-failed`}const Qr=t(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets.`);function $r(e){return e.kind!==`simulator`&&e.target===`tv`?Y:Qr}function ei(t){let n=Ct(t),r=new Map,i=async e=>{if(e.kind===`simulator`)return Yr;let n=r.get(e.id)??await Zr(t,e);return n!==`probe-failed`&&r.set(e.id,n),n===`supported`?Y:n===`unsupported`?Yr:Xr},a=async e=>{let t=await n.inspectFacts(e),r=se(e),a=await i(e);return Object.freeze({device:t.device,operations:{...t.operations,...r,appState:e.kind===`simulator`?jr:Y,networkDump:Y,screenRecordingStart:Y,screenRecordingReattach:Y,screenRecordingCleanup:Y,...be({capture:e.kind===`simulator`?X:Y,customActions:zr,withoutActiveApp:e.kind===`simulator`?X:Y}),...ke({capture:e.kind===`simulator`?Rr:Y}),...pe({findText:X,querySelector:X}),...je({setViewport:Br}),...ge({focus:$(e)}),...he({unsupported:Z,plan:Q(e),directionalFling:Q(e),multiTouch:Jr(e,Kr),targetAuthoredDrag:Jr(e,qr),viewport:Q(e)}),...fe({scroll:Q(e)}),...de({type:$(e)}),...ie({unsupported:Er,tap:$(e),longPress:$(e),hover:Or,fill:$(e)}),..._e({readTextAtPoint:e.kind===`simulator`?wr:Y}),...ue({back:$(e)}),...ve({unsupported:kr,home:$(e),appSwitcher:$(e),...ye(e)}),...lt(e),..._t(e),...Te({triggerAppEvent:$(e)}),...Ie({target:$(e),unsupported:Tr,write:{wifi:Y,bluetooth:Y,airplane:Y,"mobile-data":Y,location:Y,animations:Y,appearance:Y,"text-size":Y,fingerprint:Y,"clear-app-state":Y,permission:Y},read:{"text-size":Y}}),...Ee({read:$(e),wait:$(e),accept:$(e),dismiss:$(e)}),...Se({orientation:$(e),unlock:$(e)}),...we({tvRemote:$r(e)}),...xe({unsupported:Dr,status:$(e),dismiss:$(e),enter:$(e)}),...Ce({unsupported:a.available?Yr:a,read:a,write:a}),...De({capture:yt(e),query:Vr}),...Oe({frames:$(e),memorySample:$(e),memorySnapshot:$(e),nativeCapture:$(e),profileReport:$(e)}),ensureReady:Y,bootTarget:Y,bootTargetHeadless:e.kind===`emulator`?Y:Ar,listApps:Y,...Hr(e),shutdownTarget:e.kind===`emulator`?Y:Lr}})};return Object.freeze({owner:J,ownsDevice:e=>e.platform===`android`,inspectFacts:a,bind:async r=>{let i=await n.bind(r),o=await a(r.device),s=await gr({host:t,device:r.device,owner:J,signal:r.scope.signal});return Object.freeze({device:i.device,owner:J,facts:o,operations:Object.freeze({...i.operations,...ce({host:t,device:r.device,signal:r.scope.signal}),...o.operations.appState.available?{appState:async()=>{r.scope.signal.throwIfAborted();let{runAndroidAdb:e}=await import(`./adb.js`).then(e=>e.t);return await ae(async(t,n)=>await e(r.device,t,{...n,signal:r.scope.signal}),r.scope.signal)}}:{},networkDump:async e=>await Et(t,r.device,e,r.scope.signal),...s,...e(o.operations.audioProbeStart,()=>Be({host:t.audioProbe.hostCapture,device:r.device,owner:J})),...e(o.operations.perfFrames,()=>le({resolveHost:()=>t.perf.android,device:r.device,owner:J})),...ti(t,r,o),...ut({device:r.device,signal:r.scope.signal}),...vt({device:r.device,signal:r.scope.signal}),ensureReady:async e=>await C(t,r.device,{...e,headless:!1},r.scope.signal),bootTarget:async e=>await C(t,r.device,{...e,headless:!1},r.scope.signal),...o.operations.bootTargetHeadless.available?{bootTargetHeadless:async e=>await C(t,r.device,{...e,headless:!0},r.scope.signal)}:{},listApps:async e=>{r.scope.signal.throwIfAborted();let{listAndroidApps:t}=await import(`./app-lifecycle.js`).then(e=>e.n);return(await t(e.device,e.filter)).map(e=>({id:e.package,name:e.name}))},..._(br({host:t,device:r.device,signal:r.scope.signal}),o.operations),...o.operations.shutdownTarget.available?{shutdownTarget:async()=>await t.deviceShutdown.android.shutdownTarget(r.device,r.scope.signal)}:{}}),[Symbol.asyncDispose]:async()=>await i[Symbol.asyncDispose]()})},shutdown:async()=>await n.shutdown()})}function ti(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return{...n.operations.captureSnapshot.available?me(r):{},...Le({...r,facts:n.operations,captureCapabilities:Ae(`an Android device captures through adb`),pause:async n=>await e.clock.sleep(n,t.scope.signal)})}}export{ei as createAndroidPlatformRuntime};