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.

11 lines (8 loc) • 35.7 kB
import{B as e,S as t,v as n}from"./sdk-contracts.js";import{St as r,Z as i,q as a}from"./sdk-io.js";import"./diagnostics.js";import{a as o,r as s}from"./version.js";import"./command.js";import{d as c,g as l,n as u,t as d}from"./adb-executor.js";import{n as f,o as p,s as m}from"./device-shell.js";import{n as h,o as ee}from"./adb-failure.js";import{n as g}from"./runtime-slots.js";import"./retry.js";import{n as te,t as ne}from"./helper-artifacts.js";import _ from"node:path";import re from"node:net";const ie=Symbol(`androidDeviceExitStatusForwarding`),ae=()=>g(ie,()=>new Map);async function oe(e){let t=ae().get(e.deviceKey);if(t!==void 0)return t;let n;try{let t=await e.adb([`features`],{allowFailure:!0,timeoutMs:2e3,...e.signal?{signal:e.signal}:{}});if(t.exitCode!==0)return!1;n=t.stdout}catch{return!1}let r=ce(n).includes(`shell_v2`);return ae().set(e.deviceKey,r),r}function se(){ae().clear()}function ce(e){return e.split(` `).map(e=>e.trim()).filter(Boolean)}function le(e){let t={status:[],results:[],currentStatus:null,currentResult:null};for(let n of e.split(/\r?\n/))ue(n,t);return de(t),{status:t.status,results:t.results}}function ue(e,t){if(e.startsWith(`INSTRUMENTATION_STATUS: `)){t.currentStatus??={},me(e.slice(24),t.currentStatus);return}if(e.startsWith(`INSTRUMENTATION_STATUS_CODE: `)){fe(t);return}if(e.startsWith(`INSTRUMENTATION_RESULT: `)){t.currentResult??={},me(e.slice(24),t.currentResult);return}e.startsWith(`INSTRUMENTATION_CODE: `)&&pe(t)}function de(e){fe(e),pe(e)}function fe(e){e.currentStatus&&=(e.status.push(e.currentStatus),null)}function pe(e){e.currentResult&&=(e.results.push(e.currentResult),null)}function me(e,t){let n=e.indexOf(`=`);n<0||(t[e.slice(0,n)]=e.slice(n+1))}function v(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function he(e){if(e===void 0)return;if(e===``)return[];let t=e.split(`,`);return t.every(e=>/^\d+$/.test(e))?t.map(Number):void 0}function y(e){if(e===`true`)return!0;if(e===`false`)return!1}const ge=4096,b=2048,_e=`([A-Za-z0-9_.$/]*)`,ve=[RegExp(`^INSTRUMENTATION_FAILED: ?${_e}$`),RegExp(`^android\\.util\\.AndroidException: INSTRUMENTATION_FAILED: ${_e}$`),RegExp(`^onError: commandError=(?:true|false) message=INSTRUMENTATION_FAILED: ${_e}$`)],ye=/[A-Za-z][\w:-]*\s*=\s*["']/,be=/[<>]|&[A-Za-z][A-Za-z0-9]*;|&#|payloadBase64/i;function xe(e){return ye.test(e)||be.test(e.replaceAll(`<init>`,``).replaceAll(`<clinit>`,``))}const Se=/^INSTRUMENTATION_ABORTED:[ \t]?(.*)$/,Ce=/^INSTRUMENTATION_(?:STATUS|STATUS_CODE|RESULT|CODE|ABORTED|FAILED):/,we=/^INSTRUMENTATION_(?:STATUS|RESULT): ([^=]*)=(.*)$/,Te=/^INSTRUMENTATION_(STATUS_CODE|CODE): (-?\d+)\s*$/,Ee=new Set([`STATUS Error,STATUS id,STATUS_CODE`,`STATUS id,STATUS Error,STATUS_CODE`]),De={shortMsg:`shortMsg`,longMsg:`longMsg`,Error:`error`,stack:`stack`};function Oe(e){let t=``,n=!1,r=e=>{t+=e,!(t.length<=ge)&&(n=!0,t=t.slice(0,ge))},i=()=>{e(t.replace(/\r$/,``),n),t=``,n=!1};return{write(e){let t=e;for(let e=t.indexOf(` `);e>=0;e=t.indexOf(` `))r(t.slice(0,e)),i(),t=t.slice(e+1);r(t)},end(){t&&i()}}}function ke(){let e={},t,n=new Set,r=[],i=!1,a=(e,t,r)=>((r||xe(t))&&n.add(e),t),o=(t,n)=>{if(n)return!1;for(let n of ve){let r=n.exec(t);if(r)return e.failed??=r[1]??``,!0}return!1},s=(n,i)=>{n.trim()!==``&&r.push(Ae(n,i)),o(n,i)?t=void 0:Ce.test(n)?t=d(n,i):t&&(e[t]=Me(e[t],a(t,n,i)))},c=(t,n)=>{t===`CODE`?e.resultCode??=n:e.statusCode=n},l=(t,n)=>{e.aborted===void 0&&(e.aborted=a(`aborted`,t,n).slice(0,b))},u=(t,n,r)=>{let i=je(t);if(!(!i||e[i]!==void 0))return e[i]=a(i,n,r).slice(0,b),i},d=(e,t)=>{let n=Te.exec(e);if(n){let e=Number(n[2]);Number.isSafeInteger(e)&&c(n[1],e);return}let r=Se.exec(e);if(r){l(r[1]??``,t);return}let a=we.exec(e);if(a)return a[1]===`id`&&e.startsWith(`INSTRUMENTATION_STATUS:`)&&(i=a[2]===`ActivityManagerService`),u(a[1],a[2]??``,t)},f=Oe(s),p=Oe(o);return{writeStdout:f.write,writeStderr:p.write,result(t,r,i){i&&(f.end(),p.end());let a={...e};for(let e of n)delete a[e];let{aborted:o,failed:s,shortMsg:c,longMsg:l,error:u,stack:d,resultCode:m,statusCode:h}=a;return{exitCode:t??null,...r?{signal:r}:{},...m===void 0?{}:{resultCode:m},...h===void 0?{}:{statusCode:h},...o===void 0?{}:{aborted:o.trim()},...s===void 0?{}:{failed:s},...c===void 0?{}:{shortMsg:c.trimEnd()},...l===void 0?{}:{longMsg:l.trimEnd()},...u===void 0?{}:{error:u.trimEnd()},...d===void 0?{}:{stack:d.trimEnd()},...n.size>0?{withheldFields:[...n].sort()}:{}}},isSystemRefusal:()=>Ee.has(r.join(`,`))&&i&&e.statusCode===-1}}function Ae(e,t){if(t)return`cut`;let n=Te.exec(e);if(n)return n[1];let r=we.exec(e);return r?`${e.startsWith(`INSTRUMENTATION_STATUS:`)?`STATUS`:`RESULT`} ${r[1]}`:Ce.test(e)?`protocol`:`text`}function je(e){return Object.hasOwn(De,e)?De[e]:void 0}function Me(e,t){let n=`${e??``}\n${t}`;return n.length>b?e:n}function Ne(e){let t=Pe(e),n=t.result(e.exitCode,e.signal,!0);return n.failed!==void 0&&n.exitCode!==null&&n.exitCode!==0&&n.signal===void 0&&t.isSystemRefusal()}function Pe(e){let t=ke();return t.writeStdout(e.stdout),t.writeStderr(e.stderr),t}function x(e){return Pe(e).result(e.exitCode,e.signal,!0)}function Fe(e){let t=ke(),n=(e,t)=>{let n=new TextDecoder;e?.on(`data`,e=>{t(typeof e==`string`?e:n.decode(e,{stream:!0}))})};n(e.stdout,t.writeStdout),n(e.stderr,t.writeStderr);let r=!1;return{closed:new Promise(t=>{e.once(`close`,()=>{r=!0,t()})}),exitResult:()=>r?t.result(e.exitCode,e.signalCode,!0):void 0,current:()=>t.result(e.exitCode,e.signalCode,!1)}}function Ie(e,t,r,i){if(i instanceof n){let a=i.details??{};return new n(i.code,i.message,{...a,action:e,package:r,tool:t,hint:typeof a.hint==`string`?a.hint:Re(t,a)},i)}return new n(`COMMAND_FAILED`,`Failed to ${e} Android ${t} for ${r}`,{action:e,package:r,tool:t,hint:S(t)},i)}function S(e){return e===`simpleperf`?`Verify simpleperf is available, the app process is running, and the app/device permits native CPU profiling.`:`Verify perfetto is available, the app process is running, and the device permits trace capture.`}function Le(e){return e===`simpleperf`?`Use an emulator/system image with simpleperf available, or install the Android NDK simpleperf binary for this device.`:`Use Android 10+ or a system image that exposes the perfetto command-line binary.`}function Re(e,t){let n=(typeof t.stderr==`string`?t.stderr:``).toLowerCase();return e===`simpleperf`?ze(n):Ve(n)?`Use a device image that permits perfetto trace capture for shell, keep the app running, then retry perf trace start.`:S(e)}function ze(e){return Be(e)?`Use a debuggable/profileable Android app or a device image that permits simpleperf for the target process, then retry perf cpu profile start.`:e.includes(`not supported`)||e.includes(`failed to open perf event`)?`This device image does not expose the requested simpleperf event for the app process. Try a different emulator/system image or a profileable app.`:S(`simpleperf`)}function Be(e){return e.includes(`permission denied`)||e.includes(`not profileable`)||e.includes(`profileable`)}function Ve(e){return e.includes(`permission denied`)||e.includes(`not allowed`)}const He=`adb-shell-simpleperf`,Ue=`adb-shell-perfetto`,C=15e3,We=3e4,Ge=`/data/local/tmp`,Ke=`/data/misc/perfetto-traces`,qe=3600;async function Je(e,t){try{let n=await c(e,[`pidof`,t],{allowFailure:!0,timeoutMs:C}),r=w(n.stdout);if(n.exitCode===0&&r)return r}catch{}throw new n(`COMMAND_FAILED`,`No active Android app process found for ${t}`,{package:t,hint:`Run open <app> for this session again, wait for the app UI to appear, then retry perf.`})}async function Ye(e,t,r){let i=await c(e,[p(`command -v ${m(t)} || which ${m(t)}`)],{allowFailure:!0,timeoutMs:C});if(!(i.exitCode===0&&i.stdout.trim()))throw new n(`UNSUPPORTED_OPERATION`,`Android device does not expose ${t}`,{package:r,tool:t,hint:Le(t)})}function w(e){return e.trim().split(/\s+/).find(e=>/^\d+$/.test(e))}const T=2e3,Xe=`android_snapshot_helper_runtime_occupied`,Ze=Symbol(`androidPendingRetirements`),E=()=>g(Ze,()=>new Map);function Qe(e){return`${e.platform}:${e.id}`}async function D(e){await N({adb:e.adb,packageName:e.packageName}),await k({deviceKey:e.deviceKey,packageName:e.packageName,adb:e.adb,cause:e.cause})}async function O(e){let t=E().get(e.deviceKey);if(!t)return;await N({adb:e.adb,packageName:t.packageName,timeoutMs:5e3,...e.signal?{signal:e.signal}:{}}),e.signal?.throwIfAborted();let n=await A({adb:e.adb,packageName:t.packageName});if(n===`occupied`&&(await a(250),n=await A({adb:e.adb,packageName:t.packageName})),n===`occupied`)throw et({deviceKey:e.deviceKey,packageName:t.packageName,cause:t.cause});n!==`unknown`&&E().delete(e.deviceKey)}async function k(e){let t=e.release??await A({adb:e.adb,packageName:e.packageName});if(t===`released`)return E().delete(e.deviceKey),t;let n=e.cause instanceof Error?e.cause.message:String(e.cause);return E().set(e.deviceKey,{packageName:e.packageName,cause:n}),r({level:`warn`,phase:`android_snapshot_helper_retirement_pending`,data:{deviceKey:e.deviceKey,packageName:e.packageName,release:t}}),t}function $e(e){return e instanceof n&&e.details?.reason===Xe}function et(e){let t=e.cause instanceof Error?e.cause.message:String(e.cause);return new n(`COMMAND_FAILED`,`Android automation helper is still holding device automation ownership`,{reason:Xe,deviceKey:e.deviceKey,packageName:e.packageName,cause:t,hint:`Retry after the helper process exits, or restart the device if Android keeps reporting the helper as running.`})}async function A(e){try{let t=await c(e.adb,[`pidof`,e.packageName,p(`|| echo AGENT_DEVICE_NO_HELPER`)],{allowFailure:!0,timeoutMs:T}),n=t.stdout.trim();return w(n)?`occupied`:n===`AGENT_DEVICE_NO_HELPER`&&t.stderr.trim().length===0?`released`:`unknown`}catch{return`unknown`}}async function tt(e){let t=AbortSignal.timeout(e.timeoutMs),[,n]=await Promise.all([e.forceStopRuntime?N({adb:e.adb,packageName:e.packageName,timeoutMs:e.timeoutMs,signal:t}):void 0,ot({...e,signal:t})]);return{timedOut:t.aborted||!n}}function nt(e){let t=j(e);return{ended:t?Promise.resolve():new Promise(t=>{e.once(`close`,()=>t()),e.once(`exit`,()=>t())}),hasEnded:()=>j(e),completedCleanly:()=>!t&&e.exitCode===0&&e.signalCode==null}}function j(e){return e.exitCode!=null||e.signalCode!=null}async function M(e,t,n){let r,i,a=await Promise.race([e.then(()=>!0),new Promise(e=>{r=setTimeout(()=>e(!1),t)}),...n?[new Promise(e=>{i=()=>e(!1),n.addEventListener(`abort`,i,{once:!0}),n.aborted&&i()})]:[]]);return r&&clearTimeout(r),i&&n?.removeEventListener(`abort`,i),a}async function rt(e){if(e.processExit.hasEnded())return!0;try{e.process.kill(`SIGTERM`)}catch{}return await M(e.processExit.ended,e.timeoutMs)}function it(e){E().delete(e)}function at(){E().clear()}async function N(e){await c(e.adb,[`am`,`force-stop`,e.packageName],{allowFailure:!0,timeoutMs:e.timeoutMs??2e3,...e.signal?{signal:e.signal}:{}}).catch(()=>{})}async function ot(e){return e.process.stdin?.end(),e.process.stdout?.destroy(),e.process.stderr?.destroy(),await e.adb([`forward`,`--remove`,`tcp:${e.port}`],{allowFailure:!0,timeoutMs:e.timeoutMs,signal:e.signal}).then(()=>!0,()=>!1)}function P(e){return e.errorType===`java.util.concurrent.TimeoutException`?`accessibility-timeout`:void 0}function st(e){return e===137?`accessibility-timeout`:void 0}function F(e){return e?{androidCaptureFailureReason:e}:{}}const I=`android-snapshot-helper-v1`,L=`uiautomator-xml`,ct=5e3,lt=3e4;async function ut(e){let t=R(e),r=e.deviceKey??`android:default`;await O({deviceKey:r,adb:e.adb,signal:e.signal});let a;try{a=await e.adb(B({...t,waitForIdleTimeoutMs:e.idleWait===`none`?0:e.idleWait===`short`?Math.min(t.waitForIdleTimeoutMs,100):t.waitForIdleTimeoutMs}),{allowFailure:!0,timeoutMs:t.commandTimeoutMs,signal:e.signal})}catch(n){throw e.signal?.aborted?(await D({deviceKey:r,packageName:t.packageName,adb:e.adb,cause:n}),e.signal.throwIfAborted(),ft(n)):ft(n)}e.signal?.aborted&&(await D({deviceKey:r,packageName:t.packageName,adb:e.adb,cause:e.signal.reason}),e.signal.throwIfAborted());let o=mt(a);if(a.exitCode!==0){let e=x(a);throw new n(`COMMAND_FAILED`,`Android snapshot helper failed`,i({stdout:``,stderr:a.stderr,exitCode:a.exitCode},{helper:o.metadata,instrumentation:e}))}return o}function dt(e){return e instanceof n&&e.details?.androidSnapshotHelperStartRefused===!0}function ft(e){if(!(e instanceof n)||e.details?.stdout===void 0)return e;let{stdout:t,...r}=e.details;return new n(e.code,e.message,{...r,instrumentation:x({stdout:typeof t==`string`?t:``,stderr:typeof r.stderr==`string`?r.stderr:``,exitCode:typeof r.exitCode==`number`?r.exitCode:null})},e.cause)}function pt(e){return{adb:e.adb,adbProvider:e.adbProvider,deviceKey:e.deviceKey,helperVersion:e.artifact.manifest.version,helperVersionCode:e.artifact.manifest.versionCode,helperSha256:e.artifact.manifest.sha256,packageName:e.artifact.manifest.packageName,instrumentationRunner:e.artifact.manifest.instrumentationRunner,waitForIdleTimeoutMs:500,timeoutMs:ct,commandTimeoutMs:lt,...e.signal?{signal:e.signal}:{}}}function R(e){let t=z(e.timeoutMs,8e3),n=z(e.packageName,`com.callstack.agentdevice.snapshothelper`);return{waitForIdleTimeoutMs:z(e.waitForIdleTimeoutMs,500),waitForIdleQuietMs:z(e.waitForIdleQuietMs,100),timeoutMs:t,commandTimeoutMs:z(e.commandTimeoutMs,t+5e3),maxDepth:z(e.maxDepth,128),maxNodes:z(e.maxNodes,5e3),packageName:n,runner:z(e.instrumentationRunner,`${n}/.SnapshotInstrumentation`),...e.emitChunks===void 0?{}:{emitChunks:e.emitChunks}}}function z(e,t){return e===void 0?t:e}function B(e,t={}){return f(`adb`,`shell`,[`am`,`instrument`,`-w`,`-e`,`waitForIdleTimeoutMs`,String(e.waitForIdleTimeoutMs),`-e`,`waitForIdleQuietMs`,String(e.waitForIdleQuietMs),`-e`,`timeoutMs`,String(e.timeoutMs),`-e`,`maxDepth`,String(e.maxDepth),`-e`,`maxNodes`,String(e.maxNodes),...e.emitChunks===void 0?[]:[`-e`,`emitChunks`,String(e.emitChunks)],...t.sessionPort===void 0?[]:[`-e`,`sessionPort`,t.sessionPort],e.runner])}function mt(e){try{return ht(`${e.stdout}\n${e.stderr}`)}catch(t){if(t instanceof n&&t.details?.helper)throw new n(t.code,t.message,{...t.details,instrumentation:x(e)},t.cause);let r=x(e);throw new n(`COMMAND_FAILED`,e.exitCode===0?`Android snapshot helper output could not be parsed`:`Android snapshot helper failed before returning parseable output`,{stderr:e.stderr,exitCode:e.exitCode,instrumentation:r,...Ne(e)?{androidSnapshotHelperStartRefused:!0}:{},...F(st(e.exitCode))},t)}}function ht(e){let t=le(e),n=_t(t.results);return{xml:yt(gt(t.status),n),metadata:{...Ct(n),transport:`instrumentation`}}}function gt(e){let t=[];for(let n of e){if(n.agentDeviceProtocol!==`android-snapshot-helper-v1`||n.outputFormat!==`uiautomator-xml`)continue;let{payloadBase64:e}=n;e!==void 0&&t.push({index:V(n.chunkIndex),count:V(n.chunkCount),payloadBase64:e})}return t}function _t(e){let t=e.find(e=>e.agentDeviceProtocol===I);if(!t)throw new n(`COMMAND_FAILED`,`Android snapshot helper did not return a final result`);if(t.ok!==`true`)throw new n(`COMMAND_FAILED`,vt(t),{errorType:t.errorType,helper:t,...F(P(t))});return t}function vt(e){return e.message&&e.message!==`null`?e.message:e.errorType||`Android snapshot helper returned an error`}function yt(e,t){if(e.length===0)throw new n(`COMMAND_FAILED`,`Android snapshot helper did not return XML chunks`,{helper:t});let r=bt(e),i=Buffer.concat(St(xt(e,r),r)).toString(`utf8`);if(!i.includes(`<hierarchy`)||!i.includes(`</hierarchy>`))throw new n(`COMMAND_FAILED`,`Android snapshot helper output did not contain XML`,{xmlLength:i.length});return i}function bt(e){let t=e[0]?.count??e.length;if(t<1||e.length!==t||e.some(e=>e.count!==t))throw new n(`COMMAND_FAILED`,`Android snapshot helper returned incomplete XML chunks`,{expectedChunks:t,actualChunks:e.length});return t}function xt(e,t){let r=new Map;for(let i of e){if(i.index===void 0||i.index<0||i.index>=t)throw new n(`COMMAND_FAILED`,`Android snapshot helper returned invalid chunk index`,{chunkIndex:i.index,expectedChunks:t});if(r.has(i.index))throw new n(`COMMAND_FAILED`,`Android snapshot helper returned duplicate XML chunks`,{chunkIndex:i.index});r.set(i.index,i.payloadBase64)}return r}function St(e,t){let r=[];for(let i=0;i<t;i+=1){let a=e.get(i);if(a===void 0)throw new n(`COMMAND_FAILED`,`Android snapshot helper returned incomplete XML chunks`,{missingChunkIndex:i,expectedChunks:t});r.push(Buffer.from(a,`base64`))}return r}function Ct(e){return{helperApiVersion:e.helperApiVersion,outputFormat:L,waitForIdleTimeoutMs:V(e.waitForIdleTimeoutMs),waitForIdleQuietMs:V(e.waitForIdleQuietMs),timeoutMs:V(e.timeoutMs),maxDepth:V(e.maxDepth),maxNodes:V(e.maxNodes),rootPresent:H(e.rootPresent),cacheInvalidated:H(e.cacheInvalidated),captureMode:wt(e.captureMode),windowCount:V(e.windowCount),missingRootWindowTypes:he(e.missingRootWindowTypes),nodeCount:V(e.nodeCount),truncated:H(e.truncated),elapsedMs:V(e.elapsedMs),pixelDensity:V(e.pixelDensity),displayWidth:V(e.displayWidth),displayHeight:V(e.displayHeight)}}function wt(e){return e===`interactive-windows`||e===`active-window`?e:void 0}const V=v,H=y;function Tt(){return new Promise((e,t)=>{let n=re.createServer();n.unref(),n.on(`error`,t),n.listen(0,`127.0.0.1`,()=>{let r=n.address();if(!r||typeof r==`string`){n.close(()=>t(Error(`Failed to allocate a local TCP port`)));return}let i=r.port;n.close(()=>e(i))})})}const Et=`android_snapshot_helper_session_request_timeout`;function Dt(e){return e instanceof n&&e.details?.reason===Et}function U(e,t,r,i){return new Promise((a,o)=>{let s=re.connect({host:`127.0.0.1`,port:e}),c=[],l=setTimeout(()=>{u(),s.destroy(),o(new n(`COMMAND_FAILED`,`Android snapshot helper session request timed out`,{command:t.split(` `,1)[0],timeoutMs:r,port:e,reason:Et}))},r),u=()=>{clearTimeout(l),i?.removeEventListener(`abort`,d)},d=()=>{u(),s.destroy(),o(i?.reason??new DOMException(`The operation was aborted`,`AbortError`))};if(i?.addEventListener(`abort`,d,{once:!0}),i?.aborted){d();return}s.on(`connect`,()=>s.write(`${t}\n`)),s.on(`data`,e=>c.push(Buffer.from(e))),s.on(`error`,e=>{u(),o(e)}),s.on(`close`,()=>{u(),a(Buffer.concat(c).toString(`utf8`))})})}async function Ot(e){let t=`snapshot-${Date.now()}-${Math.random().toString(16).slice(2)}`,n={full:`snapshot`,short:`snapshot-short-idle`,none:`snapshot-immediate`}[e.idleWait??`full`],r=e.commands.has(n)?n:`snapshot`;return Pt(await U(e.port,`${r} ${t}`,e.commandTimeoutMs,e.signal),t)}function kt(e){return new Promise(t=>{let n=setTimeout(t,250);e.closed.then(()=>{clearTimeout(n),t()})})}function At(e,t,r,i){return new Promise((a,o)=>{let s=``,c=setTimeout(()=>{r?.removeEventListener(`abort`,u),o(new n(`COMMAND_FAILED`,`Android snapshot helper session did not become ready`,{instrumentation:i.current(),timeoutMs:t,reason:`android_snapshot_helper_session_ready_timeout`}))},t),l=e=>{if(s+=e.toString(),s.includes(`agentDeviceProtocol=android-snapshot-helper-v1`)&&s.includes(`sessionReady=true`)&&s.includes(`INSTRUMENTATION_STATUS_CODE: 2`)){clearTimeout(c),r?.removeEventListener(`abort`,u);let e=s.match(/INSTRUMENTATION_STATUS: sessionCommands=([^\r\n]*)\r?\n/);a(new Set(e?.[1]?.split(`,`).filter(Boolean)))}},u=()=>{clearTimeout(c),o(r?.reason??new DOMException(`The operation was aborted`,`AbortError`))};if(r?.addEventListener(`abort`,u,{once:!0}),r?.aborted){u();return}e.stdout?.on(`data`,l),e.stderr?.on(`data`,l),e.once(`exit`,(e,t)=>{clearTimeout(c),kt(i).then(()=>{r?.removeEventListener(`abort`,u),o(new n(`COMMAND_FAILED`,`Android snapshot helper session exited before ready`,{exitCode:e,signal:t,instrumentation:i.exitResult()??i.current(),reason:`android_snapshot_helper_session_exited_before_ready`}))})}),e.on(`error`,e=>{clearTimeout(c),r?.removeEventListener(`abort`,u),o(e)})})}function jt(e){let t=e.indexOf(` `);return Lt(e.slice(0,t<0?e.length:t))}function Mt(e,t){let r=jt(e);if(r.agentDeviceProtocol!==`android-snapshot-helper-v1`)throw new n(`COMMAND_FAILED`,`Android automation helper session returned wrong protocol`,{headers:r});if(r.requestId!==t)throw new n(`COMMAND_FAILED`,`Android automation helper session returned stale output`,{headers:r,requestId:t});if(!e.includes(` `))throw new n(`COMMAND_FAILED`,`Android automation helper returned incomplete headers`);return r}function Nt(e,t){let n=jt(e);return n.agentDeviceProtocol===`android-snapshot-helper-v1`&&n.requestId===t&&n.ok===`true`}function Pt(e,t){let r=e.indexOf(` `);if(r<0)throw new n(`COMMAND_FAILED`,`Android snapshot helper session returned malformed output`,{responseLength:e.length});let i=Lt(e.slice(0,r)),a=e.slice(r+2);return Ft(i,t),It(i,a),{xml:a,metadata:Rt(i)}}function Ft(e,t){if(e.agentDeviceProtocol!==`android-snapshot-helper-v1`)throw new n(`COMMAND_FAILED`,`Android snapshot helper session returned wrong protocol`,{headers:e});if(e.outputFormat!==`uiautomator-xml`)throw new n(`COMMAND_FAILED`,`Android snapshot helper session returned wrong output format`,{headers:e});if(e.requestId!==t)throw new n(`COMMAND_FAILED`,`Android snapshot helper session returned stale output`,{headers:e,requestId:t});if(e.ok!==`true`)throw new n(`COMMAND_FAILED`,e.message||e.errorType||`Android snapshot helper session returned an error`,{helper:e,...F(P(e))})}function It(e,t){let r=v(e.byteLength);if(r!==void 0&&Buffer.byteLength(t,`utf8`)!==r)throw new n(`COMMAND_FAILED`,`Android snapshot helper session returned truncated XML`,{headers:e,actualByteLength:Buffer.byteLength(t,`utf8`)});if(!t.includes(`<hierarchy`)||!t.includes(`</hierarchy>`))throw new n(`COMMAND_FAILED`,`Android snapshot helper session did not return XML`,{headers:e,xmlLength:t.length})}function Lt(e){let t={};for(let n of e.split(/\r?\n/)){let e=n.indexOf(`=`);e<0||(t[n.slice(0,e)]=n.slice(e+1))}return t}function Rt(e){return{helperApiVersion:e.helperApiVersion,outputFormat:L,waitForIdleTimeoutMs:v(e.waitForIdleTimeoutMs),waitForIdleQuietMs:v(e.waitForIdleQuietMs),timeoutMs:v(e.timeoutMs),maxDepth:v(e.maxDepth),maxNodes:v(e.maxNodes),rootPresent:y(e.rootPresent),cacheInvalidated:y(e.cacheInvalidated),captureMode:e.captureMode===`interactive-windows`||e.captureMode===`active-window`?e.captureMode:void 0,windowCount:v(e.windowCount),missingRootWindowTypes:he(e.missingRootWindowTypes),nodeCount:v(e.nodeCount),truncated:y(e.truncated),elapsedMs:v(e.elapsedMs),pixelDensity:v(e.pixelDensity),displayWidth:v(e.displayWidth),displayHeight:v(e.displayHeight)}}const zt=5e3,Bt=Symbol(`androidSnapshotHelperSessions`),W=()=>g(Bt,()=>new Map),Vt=Symbol(`androidSnapshotHelperFailedSessions`),G=()=>g(Vt,()=>new Map);async function Ht(e){return await Ut(e)!==void 0}async function Ut(e){let t=e.deviceKey??`android:default`;if(await O({deviceKey:t,adb:e.adb,signal:e.signal}),!nn()||!e.adbProvider?.spawn)return;let n=R(e),r=en(n),i=await Gt({deviceKey:t,identity:$t(t,r,e),options:e,resolved:r,startBudgetMs:tn(n.commandTimeoutMs)});return i?{session:i,resolved:r,deviceKey:t}:void 0}async function Wt(e){let t=W().get(e);if(t&&j(t.process)){await K(e,{force:!0});return}return t}async function Gt(e){if(!Jt(e.identity))return await Kt(e.deviceKey,e.identity),W().get(e.deviceKey)??await qt(e)}async function Kt(e,t){let n=W().get(e);!n||Zt(n,t)||await K(e,{force:j(n.process)})}async function qt(e){let t=Date.now();try{return await Qt(e)}catch(i){e.options.signal?.throwIfAborted(),G().set(e.identity,Date.now()+Yt(Date.now()-t)),r({level:`warn`,phase:`android_snapshot_helper_session_start_failed`,data:{deviceKey:e.deviceKey,reason:i instanceof n?i.details?.reason:void 0,instrumentation:i instanceof n?i.details?.instrumentation:void 0,detail:i instanceof Error?i.message:String(i)}});return}}function Jt(e){let t=G().get(e);return t===void 0?!1:t>Date.now()||(G().delete(e),!1)}function Yt(e){return Math.min(Math.max(e,1e4),6e4)}async function Xt(e){if(await K(e.deviceKey,{force:!0,signal:e.signal,cause:e.cause}),!e.signal?.aborted){if(e.reusedSessionTimedOut){G().set(e.identity,1/0),r({level:`warn`,phase:`android_snapshot_helper_persistent_session_disabled`,data:{deviceKey:e.deviceKey,failedAfterMs:e.failedAfterMs}});return}G().set(e.identity,Date.now()+e.fallbackBudgetMs+Yt(e.failedAfterMs))}}function Zt(e,t){return e.identity===t&&!j(e.process)}async function Qt(e){let t=await Tt();await e.options.adb([`forward`,`tcp:${t}`,`tcp:${t}`],{allowFailure:!1,timeoutMs:zt,signal:e.options.signal});let n=B({...e.resolved,emitChunks:!1},{sessionPort:t}),i=e.options.adbProvider.spawn(n,{allowFailure:!0,captureOutput:!1}),a=Fe(i),o={identity:e.identity,deviceKey:e.deviceKey,helper:{packageName:e.resolved.packageName,runner:e.resolved.runner,helperVersion:e.options.helperVersion,helperVersionCode:e.options.helperVersionCode,sha256:e.options.helperSha256},port:t,adb:e.options.adb,process:i,processRecord:a,startedAtMs:Date.now(),capturedCount:0,commands:new Set};try{return o.commands=await At(i,e.startBudgetMs,e.options.signal,a),W().set(e.deviceKey,o),G().delete(e.identity),it(e.deviceKey),r({phase:`android_snapshot_helper_session_ready`,data:{deviceKey:e.deviceKey,port:t,packageName:e.resolved.packageName,runner:e.resolved.runner}}),o}catch(t){let n=nt(i);try{i.kill(`SIGTERM`)}catch{}throw await Promise.all([M(n.ended,250),tt({adb:o.adb,process:o.process,port:o.port,packageName:o.helper.packageName,timeoutMs:T,forceStopRuntime:!0})]),await k({deviceKey:e.deviceKey,packageName:o.helper.packageName,adb:o.adb,cause:t}),t}}function $t(e,t,n){return JSON.stringify({deviceKey:e,packageName:t.packageName,runner:t.runner,helperVersion:n.helperVersion,helperVersionCode:n.helperVersionCode,helperSha256:n.helperSha256,waitForIdleTimeoutMs:t.waitForIdleTimeoutMs,waitForIdleQuietMs:t.waitForIdleQuietMs,timeoutMs:t.timeoutMs,maxDepth:t.maxDepth,maxNodes:t.maxNodes})}function en(e){return{...e,timeoutMs:Math.min(e.timeoutMs,2e3),commandTimeoutMs:tn(e.commandTimeoutMs)}}function tn(e){return Math.min(e,Math.max(Math.floor(e/2),5e3))}function nn(){let e=l().environment.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION;return e===void 0||!/^(0|false|no|off)$/i.test(e)}async function K(e,t={}){let n=W().get(e);if(!n)return!1;W().delete(e),await rn(e,n);let i=nt(n.process),a=t.force===!0||t.signal?.aborted===!0,o=await an(n,i,a,t.signal),s=i.hasEnded(),c=o.acknowledged&&o.exited,l=c&&await oe({adb:n.adb,deviceKey:e,signal:t.signal}),u=a?t.signal?.aborted===!0?250:T:zt,d=a?250:2e3,[f,p]=await Promise.all([rt({process:n.process,processExit:i,timeoutMs:d}),tt({adb:n.adb,process:n.process,port:n.port,packageName:n.helper.packageName,timeoutMs:u,forceStopRuntime:t.resetRuntime===!0||!l})]),m=await k({deviceKey:e,packageName:n.helper.packageName,adb:n.adb,cause:t.cause,...l?{release:`released`}:{}});return r({phase:`android_snapshot_helper_session_stop`,data:{deviceKey:e,port:n.port,capturedCount:n.capturedCount,lifetimeMs:Date.now()-n.startedAtMs,quitAcknowledged:o.acknowledged,quitExitObserved:c,releaseProvenByQuit:l,release:m,forceKilled:!s&&f,forced:a||t.signal?.aborted===!0,externalCleanupTimedOut:p.timedOut}}),!0}async function rn(e,t){j(t.process)&&(await M(t.processRecord.closed,250),r({level:`warn`,phase:`android_snapshot_helper_session_exited`,data:{deviceKey:e,capturedCount:t.capturedCount,instrumentation:t.processRecord.exitResult()??t.processRecord.current()}}))}async function an(e,t,n,r){if(n)return{acknowledged:!1,exited:!1};let i=`quit-${Date.now()}`;try{let n=Nt(await U(e.port,`quit ${i}`,1e3,r),i);return{acknowledged:n,exited:n&&await M(t.ended,11e3,r)&&t.completedCleanly()}}catch{return{acknowledged:!1,exited:!1}}}async function on(e){await K(Qe(e))}async function sn(){try{await Promise.allSettled([...W().keys()].map(async e=>{await K(e)}))}finally{W().clear(),G().clear(),at(),se()}}function cn(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Android snapshot helper manifest must be an object.`);let t=e;return{name:J(t.name,`name`,`android-snapshot-helper`),version:Y(t.version,`version`),releaseTag:X(t.releaseTag),assetName:X(t.assetName),apkUrl:un(t.apkUrl,`apkUrl`),sha256:ln(t.sha256),checksumName:X(t.checksumName),packageName:Y(t.packageName,`packageName`),versionCode:q(t.versionCode,`versionCode`),instrumentationRunner:Y(t.instrumentationRunner,`instrumentationRunner`),minSdk:q(t.minSdk,`minSdk`),targetSdk:t.targetSdk===void 0?void 0:q(t.targetSdk,`targetSdk`),outputFormat:J(t.outputFormat,`outputFormat`,L),statusProtocol:J(t.statusProtocol,`statusProtocol`,I)}}function q(e,t){return ne(e,t,`snapshot helper`)}function J(e,t,n){return te(e,t,n,`snapshot helper`)}function ln(e){let t=Y(e,`sha256`).trim().toLowerCase();if(t.length!==64||!dn(t))throw new n(`INVALID_ARGS`,`Android snapshot helper manifest sha256 must be a 64-character hex string.`);return t}function Y(e,t){if(typeof e!=`string`||e.trim().length===0)throw new n(`INVALID_ARGS`,`Android snapshot helper manifest ${t} is required.`);return e}function X(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function un(e,t){return e===null?null:Y(e,t)}function dn(e){for(let t of e){let e=t.charCodeAt(0);if(!(e>=48&&e<=57)&&!(e>=97&&e<=102))return!1}return!0}const fn=1e4;async function pn(e,t){try{return await d(e,t)}catch(e){throw ee(e)}}async function mn(e){let{adb:t,adbProvider:n,packageName:r,versionCode:i,apkPath:a,sha256:o,cache:s,deviceKey:c,installTimeoutMs:l,helperLabel:u}=e,d=`${c}\0${r}\0${i}\0${o}`;if(s.has(d)){let e=await _n(t,r);if(e!==void 0&&e>=i)return{packageName:r,versionCode:i,installedSha256:o,installed:!1,reason:`current`}}await Q(a,o,u);let f=await Z({adb:t,adbProvider:n,packageName:r,versionCode:i,sha256:o});if(f.reason===`current`)return s.add(d),{packageName:r,versionCode:i,...f,installed:!1};let p=await pn(a,{provider:n,replace:!0,allowFailure:!0,timeoutMs:l});if(p.exitCode!==0)throw h(`Failed to install ${u}`,p,{packageName:r,versionCode:i,reason:f.reason});return s.add(d),{packageName:r,versionCode:i,...f,installed:!0}}async function Z(e){let{adb:t,adbProvider:n,packageName:r,versionCode:i,sha256:a,signal:o}=e,s=await _n(t,r,o);if(s===void 0)return{reason:`missing`};if(s<i)return{installedVersionCode:s,reason:`outdated`};if(s>i)return{installedVersionCode:s,reason:`current`};try{let e=await vn(t,n,r,o);return{installedVersionCode:s,installedSha256:e,reason:e===a?`current`:`mismatched`}}catch{return o?.throwIfAborted(),{installedVersionCode:s,reason:`unverifiable`}}}async function hn(t){let r=l().files,i=o(),a=_.join(s(),`android`,t.helperDirName,`dist`),c=_.join(a,t.manifestFileName(i));try{let e=t.parseManifest(JSON.parse(await r.readText(c))),n=_.join(a,e.assetName);return await r.access(n),{apkPath:n,manifest:e}}catch(r){throw new n(`UNSUPPORTED_OPERATION`,t.unavailableMessage,{manifestPath:c,error:e(r).message},r)}}function gn(e){return async t=>await mn({adb:t.adb,adbProvider:t.adbProvider,packageName:t.artifact.manifest.packageName,versionCode:t.artifact.manifest.versionCode,apkPath:t.artifact.apkPath,sha256:t.artifact.manifest.sha256,cache:e.cache,deviceKey:t.deviceKey,installTimeoutMs:e.installTimeoutMs,helperLabel:e.helperLabel})}async function _n(e,t,n){let r=await c(e,[`cmd`,`package`,`list`,`packages`,`--show-versioncode`,t],{allowFailure:!0,timeoutMs:5e3,signal:n});if(r.exitCode!==0)return;let i=RegExp(`package:${xn(t)}(?:\\s|$).*versionCode:(\\d+)`).exec(`${r.stdout}\n${r.stderr}`);return i?Number(i[1]):void 0}async function vn(e,t,r,i){let a=await c(e,[`pm`,`path`,r],{allowFailure:!0,timeoutMs:fn,signal:i}),o=yn(`${a.stdout}\n${a.stderr}`);if(a.exitCode!==0||!o)throw new n(`COMMAND_FAILED`,`Could not resolve installed Android helper APK`);let s=l().files,d=await s.makeTempDirectory(`agent-device-helper-`),f=_.join(d,`base.apk`);try{let e=await u(o,f,{provider:t,allowFailure:!0,timeoutMs:fn,signal:i});if(e.exitCode!==0)throw h(`Could not read installed Android helper APK`,e,{packageName:r,remotePath:o});return await bn(f)}finally{await s.remove(d,{recursive:!0,force:!0})}}function yn(e){return e.split(/\r?\n/).map(e=>e.startsWith(`package:`)?e.slice(8).trim():``).find(e=>e.endsWith(`/base.apk`))}async function Q(e,t,r){let i=await bn(e);if(i!==t)throw new n(`COMMAND_FAILED`,`${r} APK checksum mismatch`,{apkPath:e,expectedSha256:t,actualSha256:i})}async function bn(e){let t=l().files;return t.sha256(await t.readBytes(e))}function xn(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}const $=new Map;function Sn(e){let t=`${e.deviceKey}\0${e.packageName}\0${e.versionCode}\0`;for(let e of $.keys())e.startsWith(t)&&On(e)}const Cn=`android-snapshot-helper-not-current`;function wn(e){return t(e).details?.reason===Cn}function Tn(){$.clear()}function En(e,t,n,r){return e?`${e}\0${t}\0${n}\0${r}`:void 0}function Dn(e,t){if(!e)return;let[n,r]=e.split(`\0`),i=`${n}\0${r}\0`;for(let t of $.keys())t!==e&&t.startsWith(i)&&$.delete(t);$.set(e,t)}function On(e){e&&$.delete(e)}async function kn(e){let{adb:t,artifact:r}=e,i=e.installPolicy??`missing-or-outdated`,a=r.manifest.packageName,o=r.manifest.versionCode,s=r.manifest.sha256;if(i===`never`)return{packageName:a,versionCode:o,installed:!1,reason:`skipped`};let c=En(e.deviceKey,a,o,s),l=c?$.get(c):void 0;if(c&&i!==`always`&&l!==void 0)return{packageName:a,versionCode:o,installedVersionCode:l,installedSha256:s,installed:!1,reason:`current`};await Q(r.apkPath,s,`Android snapshot helper`);let{installedVersionCode:u,installedSha256:d,reason:f}=i===`always`?{installedVersionCode:await Mn(t,a,e.timeoutMs,e.signal),reason:`forced`,installedSha256:void 0}:await Z({adb:t,adbProvider:jn(e.adbProvider,t),packageName:a,versionCode:o,sha256:s,signal:e.signal});if(f===`current`)return Dn(c,u),{packageName:a,versionCode:o,installedVersionCode:u,installedSha256:d,installed:!1,reason:f};if(i===`current-only`)throw new n(`COMMAND_FAILED`,`Android snapshot helper is not installed at the current version`,{reason:Cn,packageName:a,versionCode:o,installedVersionCode:u});let p;try{p=await Nn(t,e.adbProvider??t,r.apkPath,{packageName:a,timeoutMs:e.timeoutMs,signal:e.signal})}catch(e){throw On(c),An(e,{packageName:a,versionCode:o})}if(p.exitCode!==0)throw On(c),An(h(`Failed to install Android snapshot helper`,p,{packageName:a,versionCode:o}));return Dn(c,o),{packageName:a,versionCode:o,installedVersionCode:u,installedSha256:d,installed:!0,reason:f}}function An(e,n){let r=t(e,`COMMAND_FAILED`);return r.details={...n,...r.details,androidSnapshotHelperInstallFailure:!0},r}function jn(e,t){return e?typeof e==`function`?{exec:e}:e:{exec:t}}async function Mn(e,t,n,r){let i=await c(e,[`cmd`,`package`,`list`,`packages`,`--show-versioncode`,t],{allowFailure:!0,timeoutMs:n,signal:r});if(i.exitCode===0)return Pn(`${i.stdout}\n${i.stderr}`,t)}async function Nn(e,t,n,r){let i=async()=>await pn(n,{allowFailure:!0,provider:t,replace:!0,timeoutMs:r.timeoutMs,signal:r.signal}),a=await i();if(a.exitCode===0||!Fn(a))return a;let o=await e([`uninstall`,r.packageName],{allowFailure:!0,timeoutMs:r.timeoutMs,signal:r.signal}),s=await i();return s.exitCode===0?s:{...s,stderr:[s.stderr,o.stderr?`Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${o.stderr}`:``].filter(Boolean).join(` `)}}function Pn(e,t){let n=`package:${t}`;for(let t of e.split(/\r?\n/)){if(!t.startsWith(n)||t.length>n.length&&!/\s/.test(t[n.length]??``))continue;let e=/(?:^|\s)versionCode:(\d+)(?:\s|$)/.exec(t);if(e)return Number(e[1])}}function Fn(e){return`${e.stdout}\n${e.stderr}`.includes(`INSTALL_FAILED_UPDATE_INCOMPATIBLE`)}export{oe as $,F as A,Je as B,ut as C,ct as D,R as E,O as F,Ke as G,We as H,D as I,Ie as J,C as K,N as L,P as M,Qe as N,lt as O,$e as P,v as Q,Ye as R,pt as S,ht as T,Ge as U,qe as V,Ue as W,le as X,Le as Y,y as Z,Dt as _,Z as a,U as b,Q as c,Ht as d,se as et,Wt as f,on as g,K as h,Tn as i,st as j,I as k,cn as l,Xt as m,Sn as n,gn as o,sn as p,He as q,wn as r,hn as s,kn as t,Ut as u,Mt as v,dt as w,B as x,Ot as y,w as z};