agent-device 0.14.3 → 0.14.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/6953.js DELETED
@@ -1,8 +0,0 @@
1
- import{AsyncLocalStorage as e}from"node:async_hooks";import{spawn as t}from"node:child_process";import{promises as a}from"node:fs";import n from"node:os";import i from"node:path";import{withoutCommandExecutorOverride as r,runCmd as o,withCommandExecutorOverride as s,resolveFileOverridePath as l,whichCmd as d,runCmdDetached as u}from"./9818.js";import{asAppError as c,AppError as p}from"./9152.js";import{emitDiagnostic as m}from"./7599.js";import{ensureAndroidSdkPathConfigured as f,resolveAndroidArchivePackageName as w}from"./7651.js";import{sleep as h}from"./4829.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as _}from"./989.js";import{parseAndroidForegroundApp as y,parseAndroidLaunchablePackages as M,parseAndroidUserInstalledPackages as b}from"./9366.js";let v=new e;function g(e){var t;return t=e.id,async(e,a)=>await r(async()=>await o("adb",["-s",t,...e],a))}function I(e,t){return t??v.getStore()?.exec??g(e)}function E(e,a,n){return(function(e){return v.getStore()?.spawn??((a,n)=>t("adb",["-s",e,...a],n??{}))})(e)(a,n)}async function O(e,t){var a;if(!e)return await t();let n="function"==typeof e?{exec:e}:e,i=(a=n,(e,t,n)=>{if("adb"!==e)return;let i=function(e){if("-s"===e[0]&&e[1])return e.slice(2)}(t);if(i)return r(async()=>await a.exec(i,n))});return await v.run(n,async()=>await s(i,t))}function D(e){let t=e.trim();if(!t||/\s/.test(t))return!1;let a=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(t);if(!a)return!1;let n=a[1]?.toLowerCase(),i=a[2]??"";return"http"!==n&&"https"!==n&&"ws"!==n&&"wss"!==n&&"ftp"!==n&&"ftps"!==n||i.startsWith("//")}function N(e,t){let a,n=e?.trim();return n?n:"http"===(a=t.trim().split(":")[0]?.toLowerCase())||"https"===a?"com.apple.mobilesafari":void 0}function T(e={}){let t=e.ttlMs??3e4,a=e.nowMs??Date.now,n=new Map,i=e=>{var t;let a=[(t=e).platform,t.deviceId,""].join("\0");for(let e of n.keys())e.startsWith(a)&&n.delete(e)};return{get(e,t){let i=C(e,t),r=n.get(i);if(r)return r.expiresAtMs<=a()?void n.delete(i):r.value},set:(e,i,r)=>(n.set(C(e,i),{value:r,expiresAtMs:a()+t}),r),clear(e){i(e)},async invalidateWhile(e,t){i(e);try{return await t()}finally{i(e)}}}}function C(e,t){return[e.platform,e.deviceId,e.variant??"",t.trim().toLowerCase()].join("\0")}let L=S(process.env.AGENT_DEVICE_RETRY_LOGS);function S(e){return["1","true","yes","on"].includes((e??"").trim().toLowerCase())}let k={ios_boot:{startupMs:12e4,operationMs:2e4,totalMs:12e4},ios_runner_connect:{startupMs:12e4,operationMs:15e3,totalMs:12e4},android_boot:{startupMs:6e4,operationMs:1e4,totalMs:6e4}};class x{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(e,t=Date.now()){return new x(t,e)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return 0>=this.remainingMs(e)}}async function R(e,t={},a={}){let n,i={maxAttempts:t.maxAttempts??3,baseDelayMs:t.baseDelayMs??200,maxDelayMs:t.maxDelayMs??2e3,jitter:t.jitter??.2,shouldRetry:t.shouldRetry};for(let t=1;t<=i.maxAttempts;t+=1){if(a.signal?.aborted)throw new p("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(a.deadline?.isExpired()&&t>1)break;try{let n=await e({attempt:t,maxAttempts:i.maxAttempts,deadline:a.deadline});return a.onEvent?.({phase:a.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),U({phase:a.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),n}catch(d){n=d;let e=a.classifyReason?.(d),r={phase:a.phase,event:"attempt_failed",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:e};if(a.onEvent?.(r),U(r),t>=i.maxAttempts||i.shouldRetry&&!i.shouldRetry(d,t))break;let o=function(e,t,a,n){let i=Math.min(t,e*2**(n-1));return Math.max(0,i+i*a*(2*Math.random()-1))}(i.baseDelayMs,i.maxDelayMs,i.jitter,t),s=a.deadline?Math.min(o,a.deadline.remainingMs()):o;if(s<=0)break;let l={phase:a.phase,event:"retry_scheduled",attempt:t,maxAttempts:i.maxAttempts,delayMs:s,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:e};a.onEvent?.(l),U(l),await function(e,t){return new Promise(a=>{if(t?.aborted)return void a();let n=!1,i=()=>{n||(n=!0,t&&t.removeEventListener("abort",o),a())},r=setTimeout(i,e);function o(){clearTimeout(r),i()}t&&t.addEventListener("abort",o,{once:!0})})}(s,a.signal)}}let r={phase:a.phase,event:"exhausted",attempt:i.maxAttempts,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:a.classifyReason?.(n)};if(a.onEvent?.(r),U(r),n)throw n;throw new p("COMMAND_FAILED","retry failed")}async function P(e,t={}){return R(()=>e(),{maxAttempts:t.attempts,baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,jitter:t.jitter,shouldRetry:t.shouldRetry})}function U(e){m({level:"attempt_failed"===e.event||"exhausted"===e.event?"warn":"debug",phase:"retry",data:{...e}}),L&&process.stderr.write(`[agent-device][retry] ${JSON.stringify(e)}
2
- `)}let F=["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET","IOS_SIMULATOR_DEVICE_SET"],B=["AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST","ANDROID_DEVICE_ALLOWLIST"];function V(e){return e?.trim()||void 0}function $(e,t){for(let a of e){let e=V(t[a]);if(e)return e}}function G(e,t=process.env){return V(e)??$(F,t)}function W(e){return new Set(e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean))}function j(e,t=process.env){let a=V(e)??$(B,t);if(a)return W(a)}function H(e){let t=e.error?c(e.error):null,a=e.context?.platform,n=e.context?.phase;if(t?.code==="TOOL_MISSING")return"android"===a?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let i=t?.details??{},r="string"==typeof i.message?i.message:void 0,o="string"==typeof i.stdout?i.stdout:void 0,s="string"==typeof i.stderr?i.stderr:void 0,l=i.boot&&"object"==typeof i.boot?i.boot:null,d=i.bootstatus&&"object"==typeof i.bootstatus?i.bootstatus:null,u=[e.message,t?.message,e.stdout,e.stderr,r,o,s,"string"==typeof l?.stdout?l.stdout:void 0,"string"==typeof l?.stderr?l.stderr:void 0,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===a&&(u.includes("runner did not accept connection")||"connect"===n&&(u.includes("timed out")||u.includes("timeout")||u.includes("econnrefused")||u.includes("connection refused")||u.includes("fetch failed")||u.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===a&&"boot"===n&&(u.includes("timed out")||u.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===a&&"boot"===n&&(u.includes("timed out")||u.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":u.includes("resource temporarily unavailable")||u.includes("killed: 9")||u.includes("cannot allocate memory")||u.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===a&&(u.includes("device not found")||u.includes("no devices")||u.includes("device offline")||u.includes("offline")||u.includes("unauthorized")||u.includes("not authorized")||u.includes("unable to locate device")||u.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":t?.code==="COMMAND_FAILED"||u.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function K(e){switch(e){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI consider increasing AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}let q=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];async function z(e,t,a){let n=Array(e.length),i=0,r=Math.min(t,e.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<e.length;){let t=i;i+=1,n[t]=await a(e[t])}})),n}function J(e){return`${e.stdout}
3
- ${e.stderr}`}function Z(e,t){return["-s",e,...t]}function X(e){return e.startsWith("emulator-")}function Y(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}async function Q(e,t=k.android_boot.operationMs){return o("adb",Z(e,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:t})}async function ee(e,t){let a=t.replace(/_/g," ").trim();if(!X(e))return a||e;let n=await ea(e);return n?n.replace(/_/g," "):a||e}async function et(e,t,a){try{return await a("adb",Z(e,t),{allowFailure:!0,timeoutMs:1e4})}catch(e){var n;if("COMMAND_FAILED"===(n=c(e)).code&&"number"==typeof n.details?.timeoutMs)return;throw e}}async function ea(e,t=o){for(let a of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let n=await et(e,["shell","getprop",a],t);if(!n)continue;let i=n.stdout.trim();if(0===n.exitCode&&i.length>0)return i}let a=await et(e,["emu","avd","name"],t);if(!a)return;let n=function(e){let t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(0!==t.length)return"OK"===t.at(-1)&&t.pop(),t.join("\n").trim()||void 0}(a.stdout);if(0===a.exitCode&&n)return n}async function en(e,t){let a=J(await o("adb",Z(e,["shell","cmd","package","has-feature",t]),{allowFailure:!0,timeoutMs:k.android_boot.operationMs})).toLowerCase();return!!a.includes("true")||!a.includes("false")&&null}async function ei(e){return(await z(q,2,async t=>await en(e,t))).some(e=>!0===e)}async function er(e){var t;let a;return"tv"===((a=J(await o("adb",Z(e,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:k.android_boot.operationMs})).toLowerCase()).includes("tv")||a.includes("leanback")?"tv":null)||await ei(e)?"tv":(t=J(await o("adb",Z(e,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:k.android_boot.operationMs})),/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(t))?"tv":"mobile"}async function eo(e={}){if(await f(),!await d("adb"))throw new p("TOOL_MISSING","adb not found in PATH");let t=e.serialAllowlist??j(void 0),a=(await es()).filter(e=>!t||t.has(e.serial));return await z(a,3,async({serial:e,rawModel:t})=>{let[a,n,i]=await Promise.all([ee(e,t),ec(e),er(e)]);return{platform:"android",id:e,name:a,kind:X(e)?"emulator":"device",target:i,booted:n}})}async function es(){return(await o("adb",["devices","-l"],{timeoutMs:k.android_boot.operationMs})).stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("List of devices")).map(e=>e.split(/\s+/)).filter(e=>"device"===e[1]).map(e=>({serial:e[0],rawModel:(e.find(e=>e.startsWith("model:"))??"").replace("model:","")}))}async function el(){let e=await o("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:k.android_boot.operationMs});if(0!==e.exitCode)throw new p("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return e.stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}async function ed(e){let t=Date.now();for(;Date.now()-t<e.timeoutMs;){try{let t=await eu(e.avdName,e.serial);if(t)return{platform:"android",id:t,name:e.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await h(1e3)}throw new p("COMMAND_FAILED","Android emulator did not appear in time",{avdName:e.avdName,serial:e.serial,timeoutMs:e.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function eu(e,t){let a=Y(e);for(let e of(await es()).filter(e=>(!t||e.serial===t)&&X(e.serial)))if(Y(e.rawModel)===a||Y(await ee(e.serial,e.rawModel))===a)return e.serial}async function ec(e){try{let t=await Q(e);return"1"===t.stdout.trim()}catch{return!1}}async function ep(e){var t,a;let n;await f();let i=e.avdName.trim();if(!i)throw new p("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let r=e.timeoutMs??12e4;if(!await d("adb"))throw new p("TOOL_MISSING","adb not found in PATH");if(!await d("emulator"))throw new p("TOOL_MISSING","emulator not found in PATH");let o=await el(),s=function(e,t){let a=e.find(e=>e===t);if(a)return a;let n=Y(t);return e.find(e=>Y(e)===n)}(o,i);if(!s)throw new p("DEVICE_NOT_FOUND",`No Android emulator AVD named ${e.avdName}`,{requestedAvdName:i,availableAvds:o,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let l=Date.now(),c=(t=await eo(),a=e.serial,n=Y(s),t.find(e=>"android"===e.platform&&"emulator"===e.kind&&(!a||e.id===a)&&Y(e.name)===n));if(!c){let t=["-avd",s];e.headless&&t.push("-no-window","-no-audio"),u("emulator",t)}let m=c??await ed({avdName:s,serial:e.serial,timeoutMs:r}),w=Math.max(1e3,r-(Date.now()-l));await em(m.id,w);let h=(await eo()).find(e=>e.id===m.id);return h?{...h,name:s,booted:!0}:{...m,name:s,booted:!0}}async function em(e,t=6e4){let a,n=x.fromTimeoutMs(t),i=Math.max(1,Math.ceil(t/1e3)),r=!1;try{await R(async({deadline:i})=>{if(i?.isExpired())throw r=!0,new p("COMMAND_FAILED","Android boot deadline exceeded",{serial:e,timeoutMs:t,elapsedMs:n.elapsedMs(),message:"timeout"});let o=Math.max(1e3,i?.remainingMs()??t),s=await Q(e,Math.min(o,k.android_boot.operationMs));if(a=s,"1"!==s.stdout.trim())throw new p("COMMAND_FAILED","Android device is still booting",{serial:e,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode})},{maxAttempts:i,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:e=>{let t=H({error:e,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==t&&"ANDROID_BOOT_TIMEOUT"!==t}},{deadline:n,phase:"boot",classifyReason:e=>H({error:e,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}})})}catch(m){let i=c(m),o=a?.stdout,s=a?.stderr,l=a?.exitCode,d=H({error:m,stdout:o,stderr:s,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===d&&"Android device is still booting"===i.message&&(d="ANDROID_BOOT_TIMEOUT");let u={serial:e,timeoutMs:t,elapsedMs:n.elapsedMs(),reason:d,hint:K(d),stdout:o,stderr:s,exitCode:l};if(r||"ANDROID_BOOT_TIMEOUT"===d)throw new p("COMMAND_FAILED","Android device did not finish booting in time",u);if("TOOL_MISSING"===i.code)throw new p("TOOL_MISSING",i.message,{...u,...i.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===d)throw new p("COMMAND_FAILED",i.message,{...u,...i.details??{}});throw new p(i.code,i.message,{...u,...i.details??{}},i.cause)}}function ef(e,t){return["-s",e.id,...t]}async function ew(){if(await f(),!await d("adb"))throw new p("TOOL_MISSING","adb not found in PATH")}function eh(e,t){let a=`${e}
4
- ${t}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let eA=/\.(?:apk|aab)$/i,e_=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ey(e){var t,a;let n=e.trim();return 0===n.length?"other":eA.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(t=n,!e_.test(t))?"binary":"package":(a=n,e_.test(a))?"package":"other"}function eM(e){return`Android runtime hints require an installed package name, not "${e}". Install or reinstall the app first, then relaunch by package.`}async function eb(e,t){let a="url"===e.kind&&_(e.url),n=await A({source:e,isInstallablePath:(e,t)=>{var a;let n;return t.isFile()&&(a=e,".apk"===(n=i.extname(a).toLowerCase())||".aab"===n)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==e.kind||a,signal:t?.signal}),r=t?.resolveIdentity===!1?{}:await ev(n.installablePath);return{archivePath:n.archivePath,installablePath:n.installablePath,packageName:r.packageName,cleanup:n.cleanup}}async function ev(e){let t=i.extname(e).toLowerCase();return".apk"!==t&&".aab"!==t?{}:{packageName:await w(e)}}let eg={settings:{type:"intent",value:"android.settings.SETTINGS"}},eI="android.intent.category.LAUNCHER",eE="android.intent.category.LEANBACK_LAUNCHER",eO="android.intent.category.DEFAULT",eD="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",eN=T();function eT(e){return{platform:"android",deviceId:e.id,variant:e.target??""}}async function eC(e,t){let a=t.trim();if("package"===ey(a))return{type:"package",value:a};let n=eg[a.toLowerCase()];if(n)return n;let i=eT(e),r=eN.get(i,a);if(r)return r;let s=(await o("adb",ef(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean).filter(e=>e.toLowerCase().includes(a.toLowerCase()));if(1===s.length)return eN.set(i,a,{type:"package",value:s[0]});if(s.length>1)throw new p("INVALID_ARGS",`Multiple packages matched "${t}"`,{matches:s,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new p("APP_NOT_INSTALLED",`No package found matching "${t}"`,{hint:eD})}async function eL(e,t="all"){let a=await eS(e);return("user-installed"===t?(await ex(e)).filter(e=>a.has(e)):Array.from(a)).sort((e,t)=>e.localeCompare(t)).map(e=>({package:e,name:eR(e)}))}async function eS(e){let t=new Set;for(let a of ek(e,{includeFallbackWhenUnknown:!0})){let n=await o("adb",ef(e,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",a]),{allowFailure:!0});if(0===n.exitCode&&0!==n.stdout.trim().length)for(let e of M(n.stdout))t.add(e)}return t}function ek(e,t={}){return"tv"===e.target?[eE]:"mobile"===e.target?[eI]:t.includeFallbackWhenUnknown?[eI,eE]:[eI]}async function ex(e){return b((await o("adb",ef(e,["shell","pm","list","packages","-3"]))).stdout)}function eR(e){let t=new Set(["com","android","google","app","apps","service","services","mobile","client"]),a=e.split(".").flatMap(e=>e.split(/[_-]+/)).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),n=a[a.length-1]??e;for(let e=a.length-1;e>=0;e-=1){let i=a[e];if(!t.has(i)){n=i;break}}return n.split(/[^a-z0-9]+/i).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async function eP(e){let t=await eU(e,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(t)return t;let a=await eU(e,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return a||{}}async function eU(e,t){for(let a of t){let t=y((await o("adb",ef(e,a),{allowFailure:!0})).stdout??"");if(t)return t}return null}async function eF(e,t,a){var n,i;let r;e.booted||await em(e.id);let s=t.trim();if(D(s)){if(a)throw new p("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await o("adb",ef(e,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",s]));return}let l=await eC(e,t),d=ek(e)[0]??eI;if("intent"===l.type){if(a)throw new p("INVALID_ARGS","Activity override requires a package name, not an intent");await o("adb",ef(e,["shell","am","start","-W","-a",l.value]));return}if(a){let t=a.includes("/")?a:`${l.value}/${a.startsWith(".")?a:`.${a}`}`;try{await o("adb",ef(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",eO,"-c",d,"-n",t]))}catch(t){throw await e$(e,l.value,t),t}return}let u=await o("adb",ef(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",eO,"-c",d,"-p",l.value]),{allowFailure:!0});if(0===u.exitCode&&(n=u.stdout,i=u.stderr,r=`${n}
5
- ${i}`,!/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(r)))return;let c=await eW(e,l.value);if(!c){if(!await eV(e,l.value))throw eB(l.value);throw new p("COMMAND_FAILED",`Failed to launch ${l.value}`,{stdout:u.stdout,stderr:u.stderr})}await o("adb",ef(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",eO,"-c",d,"-n",c]))}function eB(e){return new p("APP_NOT_INSTALLED",`No package found matching "${e}"`,{package:e,hint:eD})}async function eV(e,t){let a=await o("adb",ef(e,["shell","pm","path",t]),{allowFailure:!0}),n=`${a.stdout}
6
- ${a.stderr}`;return!!(0===a.exitCode&&/\bpackage:/i.test(n))||(eG(n),!1)}async function e$(e,t,a){if(eG(a instanceof p?`${String(a.details?.stdout??"")}
7
- ${String(a.details?.stderr??"")}`:"")||!await eV(e,t))throw eB(t)}function eG(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 eW(e,t){for(let a of Array.from(new Set(ek(e,{includeFallbackWhenUnknown:!0})))){let n=await o("adb",ef(e,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",a,t]),{allowFailure:!0});if(0!==n.exitCode)continue;let i=function(e){let t=e.split("\n").map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e-=1){let a=t[e];if(a.includes("/"))return a.split(/\s+/)[0]}return null}(n.stdout);if(i)return i}return null}async function ej(e){e.booted||await em(e.id)}async function eH(e,t){if("settings"===t.trim().toLowerCase())return void await o("adb",ef(e,["shell","am","force-stop","com.android.settings"]));let a=await eC(e,t);if("intent"===a.type)throw new p("INVALID_ARGS","Close requires a package name, not an intent");await o("adb",ef(e,["shell","am","force-stop",a.value]))}async function eK(e,t){let a=await eC(e,t);if("intent"===a.type)throw new p("INVALID_ARGS","App uninstall requires a package name, not an intent");let n=await o("adb",ef(e,["uninstall",a.value]),{allowFailure:!0});if(0!==n.exitCode){let e=`${n.stdout}
8
- ${n.stderr}`.toLowerCase();if(!e.includes("unknown package")&&!e.includes("not installed"))throw new p("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let eq=null;async function ez(){let e=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(eq?.key===e)return eq.invocation;if(await d("bundletool")){let t={cmd:"bundletool",prefixArgs:[]};return eq={key:e,invocation:t},t}let t=await l(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!t)throw new p("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let a={cmd:"java",prefixArgs:["-jar",t]};return eq={key:e,invocation:a},a}async function eJ(e){let t=await ez();await o(t.cmd,[...t.prefixArgs,...e])}async function eZ(e,t){let r,o=await a.mkdtemp(i.join(n.tmpdir(),"agent-device-aab-")),s=i.join(o,"bundle.apks"),l=(r=process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim())&&r.length>0?r:"universal";try{await eJ(["build-apks","--bundle",t,"--output",s,"--mode",l]),await eJ(["install-apks","--apks",s,"--device-id",e.id])}finally{await a.rm(o,{recursive:!0,force:!0})}}async function eX(e,t){".aab"===i.extname(t).toLowerCase()?await eZ(e,t):await o("adb",ef(e,["install","-r",t]))}async function eY(e){return new Set((await o("adb",ef(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean))}async function eQ(e,t){let a=Array.from(await eY(e)).filter(e=>!t.has(e));if(1===a.length)return a[0]}async function e0(e,t){await eN.invalidateWhile(eT(e),async()=>{e.booted||await em(e.id),await eX(e,t)})}async function e1(e,t,a){let n=a?void 0:await eY(e);return await e0(e,t),a??(n?await eQ(e,n):void 0)}async function e2(e,t){e.booted||await em(e.id);let a=await eb({kind:"path",path:t});try{let t=await e1(e,a.installablePath,a.packageName),n=t?eR(t):void 0;return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:t,appName:n,launchTarget:t}}finally{await a.cleanup()}}async function e3(e,t,a){return await eN.invalidateWhile(eT(e),async()=>{e.booted||await em(e.id);let{package:n}=await eK(e,t),i=await eb({kind:"path",path:a},{resolveIdentity:!1});try{await e0(e,i.installablePath)}finally{await i.cleanup()}return{package:n}})}export{x as Deadline,k as TIMEOUT_PROFILES,ef as adb_adbArgs,K as bootFailureHint,ey as classifyAndroidAppTarget,H as classifyBootFailure,eH as closeAndroidApp,T as createAppResolutionCache,g as createDeviceAdbExecutor,ew as ensureAdb,ep as ensureAndroidEmulatorBooted,eM as formatAndroidInstalledPackageRequiredMessage,eP as getAndroidAppState,eR as inferAndroidAppName,e2 as installAndroidApp,e1 as installAndroidInstallablePathAndResolvePackageName,eh as isClipboardShellUnsupported,D as isDeepLinkTarget,S as isEnvTruthy,eL as listAndroidApps,eo as listAndroidDevices,eF as openAndroidApp,ej as openAndroidDevice,W as parseSerialAllowlist,eb as prepareAndroidInstallArtifact,e3 as reinstallAndroidApp,I as resolveAndroidAdbExecutor,eC as resolveAndroidApp,j as resolveAndroidSerialAllowlist,N as resolveIosDeviceDeepLinkBundleId,G as resolveIosSimulatorDeviceSetPath,R as retryWithPolicy,E as spawnAndroidAdbBySerial,em as waitForAndroidBoot,O as withAndroidAdbProvider,P as withRetry};
package/dist/src/9366.js DELETED
@@ -1 +0,0 @@
1
- function e(e){let t=new Set;for(let n of e.split("\n")){let e=n.trim();if(!e)continue;let r=e.split(/\s+/)[0],i=r.includes("/")?r.split("/")[0]:r;i&&t.add(i)}return Array.from(t)}function t(e){return e.split("\n").map(e=>{let t=e.trim();return t.startsWith("package:")?t.slice(8):t}).filter(Boolean)}function n(e){let t=e.split("\n");for(let e of["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"])for(let n of t){let t=n.indexOf(e);if(-1===t)continue;let i=function(e){for(let t of e.trim().split(/\s+/)){let e=t.indexOf("/");if(e<=0)continue;let n=r(t.slice(0,e),!1),i=r(t.slice(e+1),!0);if(n&&i&&n.length===e)return{package:n,activity:i}}return null}(n.slice(t+e.length));if(i)return i}return null}function r(e,t){let n=0;for(;n<e.length&&function(e,t){if(!e)return!1;let n=e.charCodeAt(0);return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"_"===e||"."===e||t&&"$"===e}(e[n],t);)n+=1;return e.slice(0,n)}export{n as parseAndroidForegroundApp,e as parseAndroidLaunchablePackages,t as parseAndroidUserInstalledPackages};
@@ -1,12 +0,0 @@
1
- export declare type AndroidForegroundApp = {
2
- package?: string;
3
- activity?: string;
4
- };
5
-
6
- export declare function parseAndroidForegroundApp(text: string): AndroidForegroundApp | null;
7
-
8
- export declare function parseAndroidLaunchablePackages(stdout: string): string[];
9
-
10
- export declare function parseAndroidUserInstalledPackages(stdout: string): string[];
11
-
12
- export { }
@@ -1 +0,0 @@
1
- export{parseAndroidForegroundApp,parseAndroidLaunchablePackages,parseAndroidUserInstalledPackages}from"./9366.js";