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.

4 lines • 13.1 kB
import{r as e}from"./rolldown-runtime.js";import{C as t,S as n,v as r}from"./sdk-contracts.js";import{a as i}from"./sdk-batch-runner.js";import{H as a,K as o,Q as s,q as c}from"./sdk-io.js";import"./command.js";import{_ as l,o as u,p as d}from"./adb-executor.js";import{n as ee}from"./device-shell.js";import{i as te,o as ne}from"./adb-transport.js";import{n as f}from"./adb-failure.js";import"./retry.js";import{o as p}from"./adb.js";import{t as m}from"./boot-diagnostics.js";import{n as re,r as h,t as ie}from"./app-deployment-resolution.js";import{a as ae,s as oe}from"./app-parsers.js";import{n as g,t as se}from"./launcher-categories.js";import{i as ce,n as le}from"./window-state.js";const _=1e4;async function ue(e,t=_,n){return await l(te(ne(e),ee(`adb`,`shell`,[`getprop`,`sys.boot_completed`])),{signal:n,timeoutMs:t})}async function v(e,t=6e4,n){let i=a.fromTimeoutMs(t),s=Math.min(1e3,Math.max(50,Math.floor(t/20))),c=Math.max(1,Math.ceil(t/s)),l,u=!1;try{await o(async({deadline:a})=>{if(a?.isExpired())throw u=!0,new r(`COMMAND_FAILED`,`Android boot deadline exceeded`,{serial:e,timeoutMs:t,elapsedMs:i.elapsedMs(),message:`timeout`});let o=Math.max(1e3,a?.remainingMs()??t),s=await ue(e,Math.min(o,_),n);if(n?.aborted)throw y(n);if(l=s,s.stdout.trim()!==`1`)throw new r(`COMMAND_FAILED`,`Android device is still booting`,{serial:e,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,bootObservation:`not_ready`})},{maxAttempts:c,baseDelayMs:s,maxDelayMs:s,jitter:0,shouldRetry:b},{deadline:i,phase:`boot`,signal:n,classifyReason:e=>x(e)})}catch(r){if(n?.aborted)throw y(n);de({error:r,serial:e,timeoutMs:t,deadline:i,lastBootResult:l,timedOut:u})}}function y(e){return e.reason instanceof r?e.reason:t(void 0,e.reason)}function b(e){let t=n(e).details;return t?.bootObservation===`not_ready`||t?.retriable===!0&&(t.adbFailure===`device_offline`||t.adbHostRefusal!==!0)}function x(e){let t=n(e);return t.code===`TOOL_MISSING`||t.details?.adbHostRefusal===!0||t.details?.adbFailure===`device_unauthorized`?`ADB_TRANSPORT_UNAVAILABLE`:t.details?.adbFailure===`timeout`||s(t)?`ANDROID_BOOT_TIMEOUT`:`BOOT_COMMAND_FAILED`}function de(e){let t=n(e.error),r=fe(e,t);throw me(t,r,e.timedOut,pe(e,r))}function fe(e,t){return b(e.error)||e.timedOut?`ANDROID_BOOT_TIMEOUT`:x(t)}function pe(e,t){return{serial:e.serial,timeoutMs:e.timeoutMs,elapsedMs:e.deadline.elapsedMs(),hint:m(t),stdout:e.lastBootResult?.stdout,stderr:e.lastBootResult?.stderr,exitCode:e.lastBootResult?.exitCode,...n(e.error).details??{},reason:t}}function me(e,t,n,i){return n||t===`ANDROID_BOOT_TIMEOUT`?new r(`COMMAND_FAILED`,`Android device did not finish booting in time`,i):e.code===`TOOL_MISSING`?new r(`TOOL_MISSING`,e.message,i):t===`ADB_TRANSPORT_UNAVAILABLE`?new r(`COMMAND_FAILED`,e.message,i):new r(e.code,e.message,i,e.cause)}var he=e({androidActivityComponent:()=>A,closeAndroidApp:()=>H,isAmStartError:()=>z,killAndroidApp:()=>Ie,listAndroidApps:()=>_e,openAndroidApp:()=>M,openAndroidDevice:()=>V,parseAndroidLaunchComponent:()=>B,passedAndroidRelaunchStopFences:()=>W});const S=`android.intent.category.DEFAULT`,ge=new Set([`localhost`,`127.0.0.1`,`::1`,`[::1]`]),C=2e3,w=2e3,T=1e4,E=3e4;async function _e(e,t){let n=await ve(e);return(t===`user-installed`?(await ye(e)).filter(e=>n.has(e)):Array.from(n)).sort((e,t)=>e.localeCompare(t)).map(e=>({package:e,name:re(e)}))}async function ve(e){let t=new Set;for(let n of g(e.target,{includeFallbackCategories:!0})){let r=await p(e,[`cmd`,`package`,`query-activities`,`--brief`,`-a`,`android.intent.action.MAIN`,`-c`,n],{allowFailure:!0});if(r.exitCode===0&&r.stdout.trim().length!==0)for(let e of ae(r.stdout))t.add(e)}return t}async function ye(e){let t=await p(e,[`pm`,`list`,`packages`,`-3`]);return oe(t.stdout)}function be(e){let t;try{t=new URL(e)}catch{return null}let n=t.hostname.toLowerCase();if(!ge.has(n)||!t.port)return null;let r=Number(t.port);return Number.isInteger(r)?`tcp:${r}`:null}async function D(e,t){let n=be(t);if(!n)return;let i=d(u(e));try{await i.ensure({local:n,remote:n,ownerId:`localhost-url`})}catch(e){let t={localPort:n.replace(`tcp:`,``),operation:`adb reverse ${n} ${n}`};throw e instanceof r&&Object.assign(t,{reason:e.details?.reason,hint:e.details?.hint,diagnosticId:e.details?.diagnosticId,logPath:e.details?.logPath}),new r(`COMMAND_FAILED`,`Failed to ensure Android port reverse ${n} before opening localhost URL`,t,e)}}const xe=String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`,O=String.raw`[A-Za-z_$][A-Za-z0-9_$]*`,Se=RegExp(`^(?:${xe}/)?\\.?${O}(?:\\.${O})*$`);function k(e){if(!Se.test(e))throw new r(`INVALID_ARGS`,`Invalid Android activity component: ${e}`,{reason:`invalid-android-activity-component`,activity:e,hint:"Pass --activity as <package>/<Class>, .<Class>, or <Class>, using letters, digits, `_`, `.`, and `$`."})}function A(e,t){return k(t),t.includes(`/`)?t:`${e}/${t.startsWith(`.`)?t:`.${t}`}`}function j(e){return e.launchArgs??[]}async function M(e,t,n){return N(await Ce(e,t,n))}async function Ce(e,t,n){let r=Me(n),a=r.activity;a!==void 0&&k(a),e.booted||await v(e.id);let o=t.trim();if(i(o))return await De(e,o,r);if(r.url!==void 0)return await Oe(e,t,r);let s=await we(e,t,r);if(s)return s;let c=await h(e,t),l=se(e.target);return c.type===`intent`?await ke(e,c.value,r):(r.terminateRunningApp&&await U(e,c.value),a?await Ae(e,c.value,a,l,r):await P(e,c.value,l,r))}async function we(e,t,n){let i=t.trim();if(e.target===`tv`||n.activity!==void 0||j(n).length>0||n.terminateRunningApp||!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/.test(i))return;let{runAndroidAutomationHelper:o}=await import(`./automation-helper.js`),s=a.fromTimeoutMs(E),c=await o(e,{action:`app`,input:{kind:`open`,packageName:i}});if(!c)return;if(c.kind===`component-unavailable`&&!await L(e,i))throw I(i);let l=c.kind===`launched`?c.output:``,u={stdout:l,stderr:``,exitCode:0};if(/^Status: ok\r?$/m.test(l))return u;if(!Te(u,i))throw new r(`COMMAND_FAILED`,`Android helper could not launch the application`,{packageName:i,stdout:l});if(!await Ee(e,i,s))throw new r(`COMMAND_FAILED`,`Android helper launch timed out before the application reached the foreground`,{reason:`android-launch-not-foreground`,packageName:i,stdout:l,timeoutMs:E});return u}function Te(e,t){return/^Status: timeout\r?$/m.test(e.stdout)&&N(e)===t}function Ee(e,t,n){return Y(e,n,250,e=>e===t)}function N(e){return e.stdout.split(` `).find(e=>e.trim().startsWith(`Activity:`))?.split(`:`)[1]?.trim().split(`/`)[0]||void 0}async function De(e,t,n){if(n.activity)throw new r(`INVALID_ARGS`,`Activity override is not supported when opening a deep link URL`);return await D(e,t),await p(e,[`am`,`start`,`-W`,`-a`,`android.intent.action.VIEW`,`-d`,t,...Ne(n.appBundleId),...j(n)])}async function Oe(e,t,n){if(n.activity)throw new r(`INVALID_ARGS`,`Activity override is not supported when opening an app-bound deep link URL`);let a=n.url?.trim()??``;if(!i(a))throw new r(`INVALID_ARGS`,`Android app-bound open requires a valid URL target`);await D(e,a);let o=await je(e,t,`app-bound open`);return n.terminateRunningApp&&await U(e,o),await p(e,[`am`,`start`,`-W`,`-a`,`android.intent.action.VIEW`,`-d`,a,`-p`,o,...j(n)])}async function ke(e,t,n){if(n.activity)throw new r(`INVALID_ARGS`,`Activity override requires a package name, not an intent`);return await p(e,[`am`,`start`,`-W`,...n.terminateRunningApp?[`-S`]:[],`-a`,t,...j(n)])}async function Ae(e,t,n,r,i){let a=A(t,n);try{return await p(e,F(a,r,i))}catch(n){throw await Pe(e,t,n),n}}async function P(e,t,n,r){let i=await p(e,[`am`,`start`,`-W`,`-a`,`android.intent.action.MAIN`,`-c`,S,`-c`,n,`-p`,t,...j(r)],{allowFailure:!0});if(i.exitCode===0&&!z(i.stdout,i.stderr))return i;let a=await Fe(e,t);if(!a)throw await L(e,t)?f(`Failed to launch ${t}`,i):I(t);return await p(e,F(a.component,a.category,r))}function F(e,t,n){return[`am`,`start`,`-W`,`-a`,`android.intent.action.MAIN`,`-c`,S,`-c`,t,`-n`,e,...j(n)]}async function je(e,t,n){let i=await h(e,t);if(i.type===`intent`)throw new r(`INVALID_ARGS`,`Android ${n} requires a package name, not an intent`);return i.value}function Me(e){return typeof e==`string`?{activity:e}:e??{}}function Ne(e){let t=e?.trim();return t?[`-p`,t]:[]}function I(e){return new r(`APP_NOT_INSTALLED`,`No package found matching "${e}"`,{package:e,hint:ie})}async function L(e,t){let n=await p(e,[`pm`,`path`,t],{allowFailure:!0}),r=`${n.stdout}\n${n.stderr}`;return n.exitCode===0&&/\bpackage:/i.test(r)?!0:(R(r),!1)}async function Pe(e,t,n){if(R(n instanceof r?`${String(n.details?.stdout??``)}\n${String(n.details?.stderr??``)}`:``)||!await L(e,t))throw I(t)}function R(e){return/\bunknown package\b/i.test(e)||/\bpackage .* (?:was|is) not found\b/i.test(e)||/\bpackage .* does not exist\b/i.test(e)||/\bcould not find package\b/i.test(e)}async function Fe(e,t){let n=g(e.target,{includeFallbackCategories:!0});for(let r of n){let n=await p(e,[`cmd`,`package`,`resolve-activity`,`--brief`,`-a`,`android.intent.action.MAIN`,`-c`,r,t],{allowFailure:!0});if(n.exitCode!==0)continue;let i=B(n.stdout);if(i)return{component:i,category:r}}return null}function z(e,t){return`${e}\n${t}`.split(` `).some(e=>{let t=e.toLowerCase();return t.startsWith(`error:`)&&(t.includes(`activity not started`)||t.includes(`unable to resolve intent`))})}function B(e){let t=e.split(` `).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n===void 0||!n.includes(`/`))continue;let r=n.split(/\s+/)[0];if(r!==void 0)return r}return null}async function V(e){e.booted||await v(e.id)}async function H(e,t){await K(e,await G(e,t,`Close`))}async function U(e,t){await K(e,t).catch(e=>{if(!W(e))throw e})}function W(e){return e instanceof r&&e.details?.reason===`android-app-close-timeout`&&e.details.phase===`process`}async function G(e,t,n){if(t.trim().toLowerCase()===`settings`)return`com.android.settings`;let i=await h(e,t);if(i.type===`intent`)throw new r(`INVALID_ARGS`,`${n} requires a package name, not an intent`);return i.value}async function K(e,t){let n=await $(e,t,w);if(!n)throw q(t);await p(e,[`am`,`force-stop`,t]);let r=await Re(e,t,n);if(r)throw Be(t,r)}async function Ie(e,t){await Le(e,await G(e,t,`Kill`))}async function Le(e,t){let n=await ce(e);if(n.status===`resumed`&&n.package===t)throw new r(`COMMAND_FAILED`,`Cannot kill foreground app ${t}`,{reason:`android-kill-requires-background-app`,hint:`Background the app before killApp (for example pressKey: Home): am kill only reaps background processes.`});if(n.status===`unknown`)throw new r(`COMMAND_FAILED`,`Could not read resumed activity state before killing ${t}`,{reason:`android-process-probe-unavailable`,hint:`adb dumpsys did not answer; retry once the device is reachable.`});await p(e,[`am`,`kill`,t]),await J(e,t),await Z(e,t);let i=await Q(e,t);if(i===`running`)throw new r(`COMMAND_FAILED`,`am kill did not stop ${t}`,{reason:`android-kill-process-survived`,hint:`The process survived am kill (for example a foreground service keeps it alive): use stopApp (am force-stop) to terminate it.`});if(i===`unknown`)throw q(t)}function q(e){return new r(`COMMAND_FAILED`,`Could not read process state for ${e}`,{reason:`android-process-probe-unavailable`,hint:`adb pidof did not answer; retry once the device is reachable.`})}async function Re(e,t,n){if(!await J(e,t))return`foreground`;if(!await He(e,t,n))return`exit`;if(!await Z(e,t))return`process`}const ze={foreground:{message:`remained foreground after close`,timeoutMs:C},exit:{message:`process that ran before close did not exit`,timeoutMs:T},process:{message:`process remained running after close`,timeoutMs:w}};function Be(e,t){let{message:n,timeoutMs:i}=ze[t];return new r(`COMMAND_FAILED`,`Android app ${e} ${n}`,{reason:`android-app-close-timeout`,phase:t,packageName:e,timeoutMs:i})}function J(e,t){return Y(e,a.fromTimeoutMs(C),50,e=>e!==t)}async function Y(e,t,n,r){for(;!t.isExpired();){let i=await X(t,()=>Ve(e));if(!i)break;if(r(i.value?.package))return!0;await c(n)}return!1}async function X(e,t){let n=await t();return e.isExpired()?void 0:{value:n}}async function Ve(e){let t=await le(e);return t.package?t:null}async function He(e,t,n){if(n.size===0)return!0;let r=a.fromTimeoutMs(T);for(;!r.isExpired();){let i=await X(r,()=>$(e,t,r.remainingMs()));if(!i)break;if(!i.value)throw q(t);if(![...i.value].some(e=>n.has(e)))return!0;await c(50)}return!1}async function Z(e,t){let n=a.fromTimeoutMs(w),r=()=>X(n,async()=>await Q(e,t)===`running`);for(;!n.isExpired();){let e=await r();if(!e)break;if(!e.value){if(await c(150),n.isExpired())break;let e=await r();if(!e)break;if(!e.value)return!0}await c(50)}return!1}async function Q(e,t){let n=await $(e,t);return n?n.size>0?`running`:`gone`:`unknown`}async function $(e,t,n){let r;try{r=await p(e,[`pidof`,t],{allowFailure:!0,...n===void 0?{}:{timeoutMs:n}})}catch(e){if(s(e))return;throw e}if((r.stderr??``).trim()!==``)return;let i=(r.stdout??``).trim();if(r.exitCode===0&&/^\d+(\s+\d+)*$/.test(i))return new Set(i.split(/\s+/));if((r.exitCode===0||r.exitCode===1)&&i===``)return new Set}export{M as a,v as c,z as i,he as n,V as o,H as r,B as s,A as t};