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.
2 lines • 41.4 kB
JavaScript
import{r as e}from"./rolldown-runtime.js";import{Dn as t,ki as n}from"./sdk-batch.js";import{j as r,v as i}from"./sdk-contracts.js";import{u as a}from"./sdk-device.js";import{d as o}from"./scroll-gesture.js";import{a as s}from"./sdk-remote-config.js";import{b as c,y as l}from"./device.js";import{a as u,i as ee,o as d,r as te,s as f,t as ne}from"./runtime-deployment.js";import p from"node:fs";import m from"node:path";import re,{stat as ie}from"node:fs/promises";import{setTimeout as ae}from"node:timers/promises";function h(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function g(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function _(e,t,n,r,i,a){let o=n[r],s=typeof o==`string`?o.trim():``;if(s.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:s,availability:`ready`}}function v(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function y(e,t){try{await t()}catch(t){e instanceof i&&(e.details={...e.details,cleanupError:r(t)})}}function b(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function oe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function se(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function ce(e,t){let n=new URL(e);return n.pathname=`${se(n.pathname)}/${t}`,n}function le(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}async function ue(e,t,n){if(!(await ie(e).catch(()=>void 0))?.isFile())throw new i(`INVALID_ARGS`,`${n.service} can only upload a regular app file: ${e}`,{provider:n.provider,appPath:e,hint:`Use an existing .ipa, .apk, or .aab file, or a .zip of the iOS simulator .app bundle.`});let r=new FormData;return r.set(t,await p.openAsBlob(e),m.basename(e)),r}const x=9e5;async function de(e,t,n){let r=AbortSignal.timeout(x),a,o;try{a=await fetch(t.endpoint,{method:`POST`,headers:{...v(t.clientVersion),Authorization:b(t.auth)},body:e,signal:n?AbortSignal.any([n,r]):r}),o=await C(a)}catch(e){if(n?.aborted)throw e;let a=r.aborted;throw new i(`COMMAND_FAILED`,`${t.service} app upload failed.`,{reason:a?`hub_app_upload_timeout`:`hub_app_upload_transport_failed`,...a?{timeoutMs:x}:{},hint:`Check network access to the ${t.service} upload API, then retry.`},e)}if(a.status===401||a.status===403)throw new i(`UNAUTHORIZED`,`${t.service} rejected the app upload credentials.`,{status:a.status,hint:`Check the ${t.service} username and access key.`});let s=t.readAppReference(o)?.trim();if(!a.ok||!s)throw new i(`COMMAND_FAILED`,`${t.service} app upload failed.`,{status:a.status,response:o});return s}function fe(e){return async({appPath:t,options:n,signal:r})=>({appReference:await e(t,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}async function pe(e){let{app:t}=e,n=e.parseReference(t);if(n!==void 0)return n;if(/^https?:\/\//i.test(t))return t;let r=m.isAbsolute(t)?t:m.resolve(me(e),t);if(!p.existsSync(r))throw new i(`INVALID_ARGS`,`${e.service} --provider-app must be ${e.referenceLabel}, URL, or existing local app path.`,{providerApp:t});return await e.uploadFile(r,e.signal)}function me(e){if(e.cwd!==void 0)return e.cwd;throw new i(`INVALID_ARGS`,`${e.service} --provider-app ${e.app} is a relative path and the request names no working directory; pass an absolute path.`,{providerApp:e.app,reason:`provider_app_cwd_missing`})}const S=15e3;async function he(e,t){let{service:n,unauthorizedHint:r,networkHint:a}=t.hints,o=`Retry connect or check the ${n} service status.`;try{let a=await fetch(e,{headers:{...v(t.clientVersion),...t.auth?{Authorization:b(t.auth)}:{}},signal:AbortSignal.timeout(S)});if(!a.ok){let e=a.status===401||a.status===403;throw new i(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`${n} rejected connection verification.`,{status:a.status,hint:e?r:o})}let s=await C(a);if(s===void 0)throw new i(`COMMAND_FAILED`,`${n} connection verification answer was not JSON.`,{status:a.status,hint:o});return s}catch(e){throw e instanceof i?e:new i(`COMMAND_FAILED`,`${n} connection verification failed.`,{hint:a},e)}}async function ge(e,t){let n,r;try{n=await fetch(e,{headers:{...v(t.clientVersion),Authorization:b(t.auth)},signal:AbortSignal.timeout(S)}),r=await C(n)}catch(e){throw new i(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{hint:`Check network access to the ${t.service} API, then retry.`},e)}let a=r&&typeof r==`object`&&!Array.isArray(r)?r:void 0;if(!n.ok||!a)throw new i(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{status:n.status,response:r});return a}async function C(e){let t=await e.text();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function _e(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function ve(e,t){let n=s.find(e=>e===t);if(n)return n;throw new i(`INVALID_ARGS`,`Invalid ${e.flag} value: ${t}.`,{hint:`Use ${s.join(`|`)}.`,flag:e.flag,capability:e.capability})}function ye(e,t){if(e)return e;throw new i(`INVALID_ARGS`,`${t} lease allocation requires provider profile flags on the request.`)}function be(e,t){let n=e.flags?.platform;if(n===`android`||n===`ios`)return n;throw new i(`INVALID_ARGS`,`${t} requires --platform ios|android.`)}function xe(e,t,n){let r=w(e,t);if(r)return r;throw new i(`INVALID_ARGS`,n)}function w(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function T(e,t,n){let r=e[t];if(r?.trim())return r;throw new i(`INVALID_ARGS`,`${n} requires ${t} in the environment.`)}function E(e,t){if(e.platform===`android`||e.platform===`ios`)return e.platform;throw new i(`INVALID_ARGS`,`connect ${t} requires --platform ios|android.`)}function D(e,t,n){if(e?.trim())return e;throw new i(`INVALID_ARGS`,`connect ${t} requires ${n}.`)}function O(e,t,n){let r=m.resolve(t,e);if(p.statSync(r,{throwIfNoEntry:!1})?.isFile())return r;throw new i(`INVALID_ARGS`,`${n} app file not found: ${r}`)}const k=`webdriver_request_timeout`;function A(e){return e instanceof i&&e.details?.reason===k}function j(e){return{dispatched:e}}const M=`webdriver_connect_refused`,N=`webdriver_request_interrupted`,Se=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function Ce(e){return e instanceof i&&e.details?.reason===M}const we=new Set([`GET`,`HEAD`]),Te=Object.freeze({});var Ee=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=le(new URL(e.endpoint)),this.headers={...v(e.clientVersion),...e.auth?{Authorization:b(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return(await this.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??we.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!Oe(e,a,r.retryAttempts,r.signal))throw e;await ae(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i);if(a)return{status:o,value:ke(s?Ae(s,o):{})};let c=s?je(s):{json:{}};if(c===void 0)throw Ne(o,s);let l=c.json,u=Me(o,l);throw V(u)&&B(L,{method:e,path:t,status:o,code:z(l)??null}),u}async fetchWebDriver(e,t,n,r,i){let a=new URL(oe(t),this.endpoint),o=n===void 0&&e===`POST`?Te:n,s=AbortSignal.timeout(r),c=i?AbortSignal.any([i,s]):s,l={method:e,path:t,timeoutMs:r,timeoutSignal:s,requestSignal:i},u;try{u=await fetch(a,{method:e,headers:{Accept:`application/json`,...o===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:o===void 0?void 0:JSON.stringify(o),signal:c})}catch(e){throw P(e,l,`request`)}try{return{ok:u.ok,status:u.status,text:await u.text()}}catch(e){throw P(e,l,`response`)}}};function P(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Re(r,i,a,e):n===`request`&&De(e)?ze(r,i,e):n===`response`||e instanceof TypeError?Be(r,i,e):e}function De(e){let t=F(e,0);return t.length>0&&t.every(e=>Se.has(e))}function F(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...F(r,t+1),...i.flatMap(e=>F(e,t+1))]}function Oe(e,t,n,r){return!r?.aborted&&Ve(e)&&t<n}function ke(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function Ae(e,t){try{return JSON.parse(e)}catch(n){throw new i(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{status:t,text:I(e),...j(`unknown`)},n)}}function je(e){try{return{json:JSON.parse(e)}}catch{return}}function I(e){return e.length>500?`${e.slice(0,500)}…`:e}function Me(e,t){let n=t&&typeof t==`object`&&`value`in t?t.value:t,r=n&&typeof n==`object`&&typeof n.message==`string`?n.message:`WebDriver request failed with HTTP ${e}.`;return Le(e,t)?new i(`COMMAND_FAILED`,r,{...R(),status:e,response:t}):new i(`COMMAND_FAILED`,r,{status:e,response:t,...e>=500?j(`unknown`):{}})}function Ne(e,t){return new i(`COMMAND_FAILED`,`WebDriver request failed with HTTP ${e}.`,{status:e,response:I(t),...j(`unknown`)})}const L=`webdriver_route_unsupported`;function Pe(e){return e instanceof i&&e.details?.status===404&&z(e.details.response)?.toLowerCase()===`invalid session id`}function R(){return{reason:L,...j(`no`)}}const Fe=new Set([`unknown command`,`unknown method`]),Ie=new Set([404,405,501]);function Le(e,t){let n=z(t);return n===void 0?Ie.has(e):Fe.has(n.toLowerCase())}function z(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function B(e,t){import(`./diagnostics.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function V(e){return e instanceof i&&e.details?.reason===L}function Re(e,t,n,r){return new i(`COMMAND_FAILED`,`WebDriver ${e} ${t} timed out after ${n}ms.`,{reason:k,method:e,path:t,timeoutMs:n,...j(`unknown`)},r instanceof Error?r:void 0)}function ze(e,t,n){return new i(`COMMAND_FAILED`,`WebDriver ${e} ${t} could not reach the driver.`,{reason:M,method:e,path:t,...j(`no`)},n instanceof Error?n:void 0)}function Be(e,t,n){return new i(`COMMAND_FAILED`,`WebDriver ${e} ${t} lost its connection to the driver.`,{reason:N,method:e,path:t,...j(`unknown`)},n instanceof Error?n:void 0)}function Ve(e){if(A(e)||Ce(e)||e instanceof i&&e.details?.reason===N)return!0;if(e instanceof i){let t=e.details?.status;return typeof t==`number`&&t>=500}return!1}var He=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new Ee(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=We(await this.requestValue(`POST`,`/session`,{capabilities:Ue(e)},{timeoutMs:Ke(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();try{await this.requestValue(`DELETE`,`/session/${e}`,void 0,{idempotent:!0})}catch(e){if(!Pe(e))throw e}this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!V(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});B(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async clearElement(e){await this.sessionRequest(`POST`,`/element/${encodeURIComponent(e)}/clear`)}async sendElementKeys(e,t){await this.sessionRequest(`POST`,`/element/${encodeURIComponent(e)}/value`,{text:t,value:Array.from(t)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e,t){let n;try{n=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}})}catch(e){if(V(e))return`unsupported`;throw e}return typeof n==`boolean`?n:`unsupported`}async activeElementReference(e){let t=e===void 0?void 0:Date.now()+e;try{let e=Ge(await this.sessionRequest(`GET`,`/element/active`,void 0,W(t)));return e===void 0?`unsupported`:{id:e}}catch(e){if(V(e))return`unsupported`;if(K(e))return`none`;throw e}}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n=await this.activeElementReference(W(t).timeoutMs);if(typeof n==`string`)return n;let r=n.id;try{return{id:r,rect:H(await this.sessionRequest(`GET`,`/element/${encodeURIComponent(r)}/rect`,void 0,W(t)))}}catch(e){if(V(e))return`unsupported`;if(K(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(e){let t=await this.sessionRequest(`GET`,`/source`,void 0,e);if(typeof t!=`string`)throw new i(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof t});return t}async screenshot(e){let t=await this.sessionRequest(`GET`,`/screenshot`);if(typeof t!=`string`)throw new i(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof t});await re.writeFile(e,Buffer.from(t,`base64`))}async windowRect(e){return H(await this.sessionRequest(`GET`,`/window/rect`,void 0,e))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new i(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function H(e){if(!e||typeof e!=`object`)throw new i(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let t=e,n={x:U(t,`x`),y:U(t,`y`),width:U(t,`width`),height:U(t,`height`)};if(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)throw new i(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:t});return n}function U(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ue(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function We(e){if(!e||typeof e!=`object`)throw new i(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let t=e,n=typeof t.sessionId==`string`?t.sessionId:typeof t.session_id==`string`?t.session_id:void 0;if(!n)throw new i(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:t});return{sessionId:n,capabilities:t.capabilities&&typeof t.capabilities==`object`?t.capabilities:{}}}function Ge(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function W(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:G(e)}}function Ke(e,t){return t===void 0?e:Math.min(e,G(t))}function G(e){return Math.max(0,e-Date.now())}function K(e){return e instanceof i&&qe(e).toLowerCase()===`no such element`}function qe(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function q(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function Je(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return J(t(e,`android`).nodes)}async function Ye(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return J(t(e).nodes)}function J(e){let t=e.flatMap(e=>Xe(e)&&Ze(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function Xe(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ze(e){return!!e&&e.width>=50&&e.height>=50}async function Qe(e,t,n){let r=[];for(let i of t===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await $e(e,i,n);return}catch(e){if(!V(e))throw e;r.push({transport:i,error:e instanceof Error?e.message:String(e)})}throw new i(`COMMAND_FAILED`,`Could not set device orientation to ${n} on the hosted WebDriver session.`,{...R(),hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:n,attempts:r})}async function $e(e,t,n){if(t===`rotation`){await e.setRotation(c(n));return}await e.setOrientation(l(n))}const Y=1500;function et(e){return new Promise(t=>setTimeout(t,e))}function tt(e,t,n){return new i(`COMMAND_FAILED`,`fill tapped (${e}, ${t}) but ${n}`,{reason:`text_entry_focus_not_observed`,x:e,y:t,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function X(){return new i(`UNSUPPORTED_OPERATION`,`fill requires a focused element reference to clear and replace the field`,{reason:`text_entry_clear_target_unavailable`})}function nt(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}const Z={home:3,appSwitcher:187};function Q(e){return new rt(e.client,e.backend,e.capabilities,e.targetId)}var rt=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){let n=this.backend===`xctest`?{bundleId:e}:{package:e};await this.client.executeScript(`mobile: deepLink`,[{url:t.url,...n}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,t,n,r){this.requireSupport(`fill`);let i=await this.client.activeElementReference(Y);if(i===`unsupported`)throw X();let a=i===`none`?void 0:i.id;await this.tap(e,t);let o=await this.awaitTextEntryReadiness(a,e,t);return await this.client.clearElement(o),n.length>0&&await this.client.sendElementKeys(o,n),{backend:`webdriver`,x:e,y:t,text:n,textEntryReadiness:`focused-element`}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),i=o({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),a={...i,x1:i.x1+r.x,y1:i.y1+r.y,x2:i.x2+r.x,y2:i.y2+r.y};return await this.swipe(a.x1,a.y1,a.x2,a.y2,n),{backend:`webdriver`,...a,distance:i.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport(at(e)),await this.client.performActions(e.pointers.map(e=>q(`gesture-pointer-${e.pointerId}`,it(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),await this.captureSource(e?.signal)}async captureSource(e){let t=this.backend===`android`?await this.readAndroidSnapshotViewport(e):void 0,n=await this.readSource(e);e?.throwIfAborted();let r=await this.readSnapshotKeyboardVisibility(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(n,this.targetId,r)}let{parseWebDriverAndroidSnapshotNodes:i}=await import(`./webdriver-android-source.js`),[{acquireProviderKeyboard:a},{stampSnapshotIdentity:o}]=await Promise.all([import(`./tap-keyboard-occlusion.js`).then(e=>e.a),import(`./sdk-batch.js`).then(e=>e.Ui)]),s=i(n),c=t===void 0?void 0:await this.readAndroidSnapshotViewport(e),l=t!==void 0&&c!==void 0&&t.width===c.width&&t.height===c.height?t:void 0;return o({...a({nodes:s,viewport:null,visibility:r}),...l===void 0?{}:{viewport:l}},{backend:`android`,producer:`appium-source`})}async readAndroidSnapshotViewport(e){try{let t=await this.client.windowRect({timeoutMs:500,retryAttempts:0,...e===void 0?{}:{signal:e}});return n(t)}catch{e?.throwIfAborted();return}}async readSnapshotKeyboardVisibility(e){try{let t=await this.client.isKeyboardShown(500,e);return e?.throwIfAborted(),t}catch{return e?.throwIfAborted(),`failed`}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw A(e)?ot(e):e}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){if(this.requireSupport(`home`),this.backend===`android`){await this.client.executeScript(`mobile: pressKey`,[{keycode:Z.home}]);return}await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await Qe(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressKey`,[{keycode:Z.appSwitcher}])}async volumeUp(){await this.pressVolumeKey(`volumeUp`,`volumeup`)}async volumeDown(){await this.pressVolumeKey(`volumeDown`,`volumedown`)}async pressVolumeKey(e,t){if(this.backend===`android`){await this.pressAndroidHardwareKey(e);return}this.requireSupport(e),await this.client.executeScript(`mobile: pressButton`,[{name:t}])}async power(){await this.pressAndroidHardwareKey(`power`)}async pressAndroidHardwareKey(e){this.requireSupport(e);let{HARDWARE_BUTTON_NAME_LABELS:t}=await import(`./device.js`).then(e=>e.t),{toAndroidTvRemoteKeyevent:n}=await import(`./tv-remote.js`).then(e=>e.d),r=Number(n(t[e]));await this.client.executeScript(`mobile: pressKey`,[{keycode:r}])}async mute(){await this.pressAndroidHardwareKey(`mute`)}async sleep(){await this.pressAndroidHardwareKey(`sleep`)}async wake(){await this.pressAndroidHardwareKey(`wake`)}async mediaPlayPause(){await this.pressAndroidHardwareKey(`mediaPlayPause`)}async mediaNext(){await this.pressAndroidHardwareKey(`mediaNext`)}async mediaPrevious(){await this.pressAndroidHardwareKey(`mediaPrevious`)}async mediaRewind(){await this.pressAndroidHardwareKey(`mediaRewind`)}async mediaFastForward(){await this.pressAndroidHardwareKey(`mediaFastForward`)}async tvRemote(e,t){this.unsupported(`tvRemote`)}async keyboardStatus(){return this.requireSupport(`keyboard`),{kind:`ime-probe`,visible:await this.keyboardVisible()}}async keyboardDismiss(){this.requireSupport(`keyboard`);let e=await this.keyboardVisibility();if(e===!1)return this.dismissResult({wasVisible:e,visible:!1,dismissed:!1});await this.client.hideKeyboard();let t=await this.keyboardVisibilityAfterMutation();return this.dismissResult({...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t,dismissed:e===!0&&!t}})}dismissResult(e){return this.backend===`android`?{kind:`ime-probe`,...e}:{kind:`mechanism`,mechanism:`appium-hide-keyboard`,...e}}async keyboardEnter(){if(this.requireSupport(`keyboard`),this.backend===`android`)return await this.client.executeScript(`mobile: pressKey`,[{keycode:66}]),{kind:`android-acknowledged`};let e=await this.keyboardVisibility();await this.client.sendKeys(`
`);let t=await this.keyboardVisibilityAfterMutation();return{kind:`visibility-echo`,...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t}}}async keyboardVisibilityAfterMutation(){try{return await this.keyboardVisibility()}catch{return}}async keyboardVisibility(){let e=await this.client.isKeyboardShown(Y);return e===`unsupported`?void 0:e}async keyboardVisible(){let e=await this.keyboardVisibility();if(e===void 0)throw new i(`UNSUPPORTED_OPERATION`,`This driver does not implement the keyboard visibility route.`,{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:`keyboard`});return e}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeReadScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=Date.now()+2e3,i,a=await this.pollWithinBudget(r,async r=>{let a=await this.client.activeElement(r);return a===`unsupported`?`abandon`:a===`none`||a.id===e&&!nt(a.rect,t,n)?`retry`:(i=a.id,`satisfied`)});if(i!==void 0)return i;throw a===`abandon`?X():tt(t,n,`nothing there took text-entry focus, so the text was not sent`)}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(Y,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await et(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([q(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ye(e):Je(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){u(this.capabilities,e)||this.unsupported(e)}unsupported(e){throw new i(`UNSUPPORTED_OPERATION`,f(this.capabilities,e),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:e})}};function it(e){let t=e[0];if(!t)throw new i(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let n=[{type:`pointerMove`,duration:0,x:t.point.x,y:t.point.y},{type:`pointerDown`,button:0}];for(let t=1;t<e.length;t+=1){let r=e[t-1],i=e[t];n.push({type:`pointerMove`,duration:i.offsetMs-r.offsetMs,x:i.point.x,y:i.point.y})}return n.push({type:`pointerUp`,button:0}),n}function at(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`;case`tap`:return`tapGesture`}}function ot(e){return new i(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...e.details,hint:`A screen that never goes idle (looping video, live ticker, continuous animation) gives the driver no moment to read the UI tree. This read has the transport's own budget and does not grow with --timeout; take a screenshot, or drive the screen from refs an earlier snapshot already captured.`},e)}function st(e){return Object.fromEntries(e.map(e=>[e.code,e.message]))}var ct=class{entriesByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;shutDown=!1;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return this.liveSessions().find(t=>t.device.id===e.id)}findSessionForLease(e){return this.liveSession(this.entriesByLeaseId.get(e))}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.liveSession(this.entriesByLeaseId.get(e.leaseId)))return this.liveLeaseEnvelope()}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;this.entriesByLeaseId.get(e.leaseId)!==void 0&&await this.rejectRefusedProfileFields(t);let n=this.entriesByLeaseId.get(e.leaseId);if(n===void 0){if(this.shutDown)throw pt(this.options.provider,e);n=this.beginAllocation(e,t)}if(n.taken)throw ft(this.options.provider,e,n.taken);if(n.session)return this.liveLeaseEnvelope();let r=await n.creation;if(n.taken)throw await this.refusalForTakenSession(e,n.taken);return this.allocationResult(r)}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.entriesByLeaseId.get(e.leaseId);if(t===void 0)return;let n=this.take(t,`release`),r=await n.disposal;if(r.session===void 0)return;let i=await n.artifacts;return{provider:this.options.provider,providerSessionId:r.session.providerSessionId,...r.cleanupPayload,...r.warnings.length>0?{warnings:r.warnings}:{},...i?{cloudArtifacts:i}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.findSessionForLease(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){this.shutDown=!0;let e=[...this.entriesByLeaseId.values()].map(e=>this.take(e,`shutdown`)),t=await Promise.all(e.map(e=>e.disposal));this.ownedDeviceIds.clear();let n=t.filter(e=>e.cleanup===`uncertain`);if(n.length>0)throw ht(this.options.provider,n)}beginAllocation(e,t){let n,r,i={lease:e,creation:new Promise((e,t)=>{n=e,r=t}),session:void 0,taken:void 0};return this.entriesByLeaseId.set(e.leaseId,i),this.createSessionForLease(e,t).then(e=>{i.session=e,this.ownedDeviceIds.add(e.device.id),n(e)},t=>{i.taken===void 0&&this.entriesByLeaseId.get(e.leaseId)===i&&this.entriesByLeaseId.delete(e.leaseId),r(t)}),i}async createSessionForLease(e,t){await this.rejectRefusedProfileFields(t);let n=await this.prepareSession(e,t),r=new He({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n,e,t),a=this.deviceForLease(e,n,i.capabilities),o=d({provider:this.options.provider,platform:n.platform,overrides:this.options.capabilityOverrides});return Object.freeze({lease:e,device:a,client:r,prepared:n,capabilities:o,webDriverSessionId:i.sessionId,providerSessionId:n.providerSessionId??i.sessionId,interactor:Q({client:r,backend:te(n.platform),capabilities:o,targetId:a.id})})}take(e,t){let n=e.taken;if(n)return n;let i,a=new Promise(e=>{i=e}),o={by:t,providerSessionId:e.session?.providerSessionId,disposal:a,settled:void 0,artifacts:void 0};e.taken=o;let s=t=>{o.settled=t,o.providerSessionId=t.session?.providerSessionId,o.artifacts=t.session===void 0?void 0:this.safeListArtifacts(t.session,!0).catch(()=>void 0),this.entriesByLeaseId.get(e.lease.leaseId)===e&&this.entriesByLeaseId.delete(e.lease.leaseId),i(t)};return this.disposeTakenEntry(e).then(s,t=>{s({cleanup:`uncertain`,session:e.session,warnings:[{code:`PROVIDER_CLEANUP_FAILED`,message:r(t)}]})}),o}async disposeTakenEntry(e){let t=e.session??await e.creation.catch(()=>void 0);if(e.session=t,t===void 0)return{cleanup:`none`,session:void 0,warnings:[]};this.releasedProviderSessionIdsByLeaseId.set(e.lease.leaseId,t.providerSessionId);let n=[],i;try{await t.client.deleteSession()}catch(e){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:r(e)})}try{i=await this.providerCallback(`${this.options.provider} cleanup for lease ${e.lease.leaseId}`,()=>t.prepared.cleanup?.())}catch(e){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:r(e)})}return{cleanup:n.length>0?`uncertain`:`confirmed`,session:t,warnings:n,cleanupPayload:i}}async providerCallback(e,t){let n=this.options.providerCallbackTimeoutMs??3e4,r=Promise.resolve(t());r.catch(()=>void 0);let a;try{return await Promise.race([r,new Promise((t,r)=>{a=setTimeout(()=>{r(new i(`COMMAND_FAILED`,`${e} did not answer within ${String(n)}ms.`))},n),a.unref?.()})])}finally{a!==void 0&&clearTimeout(a)}}async refusalForTakenSession(e,t){let n=await t.disposal;return $(this.options.provider,e,t.by,{providerSessionId:n.session?.providerSessionId,cleanup:n.cleanup,warnings:n.warnings})}liveLeaseEnvelope(){return{provider:this.options.provider}}allocationResult(e){return{provider:this.options.provider,deviceId:e.device.id,sessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId,capabilities:e.capabilities,...e.prepared.providerData}}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=A(e)?dt(e,this.options.provider,n,t):e;throw await y(r,()=>this.providerCallback(`${this.options.provider} cleanup for lease ${n.leaseId}`,()=>t.cleanup?.())),r}}async rejectRefusedProfileFields(e){let{rejectRefusedProviderProfileFields:t}=await import(`./provider-profile-fields.js`).then(e=>e.t);t(e?.flags,this.options.profileFields)}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:ee(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t,n){return{...a(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,...lt(n),booted:!0}}liveSession(e){return e?.taken===void 0?e?.session:void 0}liveSessions(){return[...this.entriesByLeaseId.values()].flatMap(e=>{let t=this.liveSession(e);return t?[t]:[]})}async safeListArtifacts(e,t=!1){let n=e.prepared.listArtifacts??this.options.listArtifacts;if(!n)return;let r={provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId};try{return t?await this.providerCallback(`${this.options.provider} artifact lookup for session ${e.providerSessionId}`,()=>n(r)):await n(r)}catch(t){return g({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function lt(e){let t=ut(e,`platformVersion`);return t?{osVersion:t}:{}}function ut(e,t){for(let n of[e[t],e[`appium:${t}`]])if(typeof n==`string`&&n.trim().length>0)return n.trim()}function dt(e,t,n,r){let a=e.details?.timeoutMs;return new i(`COMMAND_FAILED`,`${t} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:t,leaseId:n.leaseId,runId:n.runId,timeoutMs:a,...r.providerSessionId?{providerSessionId:r.providerSessionId}:{},hint:`${t} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${t} for a running session created for lease ${n.leaseId} (run ${n.runId}) and stop it.`},e)}function $(e,t,n,r){return new i(`COMMAND_FAILED`,`${e} ended the WebDriver session allocated for lease ${t.leaseId} before the allocation returned.`,{reason:n===`release`?`provider_session_released_during_allocation`:`provider_session_shutdown_during_allocation`,provider:e,leaseId:t.leaseId,runId:t.runId,...r.providerSessionId?{providerSessionId:r.providerSessionId}:{},cleanup:r.cleanup,...r.warnings.length>0?{cleanupWarnings:st(r.warnings)}:{},hint:mt(e,n,r.cleanup)})}function ft(e,t,n){let r=n.settled?.cleanup??`pending`,a=n.providerSessionId??n.settled?.session?.providerSessionId;return n.by===`shutdown`?$(e,t,`shutdown`,{providerSessionId:a,cleanup:r,warnings:n.settled?.warnings??[]}):new i(`DEVICE_IN_USE`,`${e} is releasing lease ${t.leaseId} and allocated no WebDriver session for it.`,{reason:`provider_session_release_in_progress`,provider:e,leaseId:t.leaseId,runId:t.runId,...a?{providerSessionId:a}:{},cleanup:r,hint:r===`uncertain`?`agent-device could not stop the previous session of this lease. Check ${e} for it before allocating again.`:`Wait for this lease to finish releasing, then allocate it again.`})}function pt(e,t){return new i(`COMMAND_FAILED`,`${e} is shut down and created no WebDriver session for lease ${t.leaseId}.`,{reason:`provider_session_shutdown_during_allocation`,provider:e,leaseId:t.leaseId,runId:t.runId,cleanup:`none`,hint:`Start the daemon again to allocate a provider session.`})}function mt(e,t,n){return n===`uncertain`?`${e} did not confirm it stopped the session this allocation created, and that session may keep billing. Check ${e} for it before allocating the lease again.`:n===`pending`?`agent-device is still stopping the session this allocation created. Wait for that ${t===`release`?`release`:`shutdown`} to finish before allocating the lease again.`:n===`none`?`Nothing was billed for this allocation. Allocate the lease again.`:`Allocate the lease again; agent-device stopped the session this allocation created.`}function ht(e,t){let n=t.map(e=>e.session?.providerSessionId);return new i(`COMMAND_FAILED`,`${e} left ${String(t.length)} WebDriver session(s) running after shutdown: ${n.join(`, `)}.`,{reason:`provider_session_cleanup_incomplete`,provider:e,providerSessionIds:n,cleanup:`uncertain`,cleanupWarnings:t.flatMap(e=>e.warnings.map(t=>({providerSessionId:e.session?.providerSessionId,code:t.code,message:t.message}))),hint:`${e} did not stop these sessions and they keep billing. Stop the session ids above on ${e}.`})}var gt=e({createCloudWebDriverRuntime:()=>_t});function _t(e){return new vt(e)}var vt=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=t(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new ct(e),this.deployment=ne({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};export{pe as _,ge as a,h as b,w as c,E as d,T as f,be as g,ye as h,fe as i,y as l,ve as m,ue as n,he as o,xe as p,ce as r,de as s,gt as t,D as u,O as v,_ as x,_e as y};