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 • 19.9 kB
import{An as e,Dn as t,Mn as n,jn as r}from"./sdk-batch.js";import{T as i,v as a}from"./sdk-contracts.js";import{J as o,X as s,w as c}from"./sdk-device.js";import{a as l,o as u}from"./device2.js";import{n as d,t as f}from"./request-cancellation.js";import{a as p,r as m}from"./durable-resource.js";import{n as ee,t as h}from"./application-lifecycle-runtime.js";import{t as te}from"./async-lifecycle.js";import{i as ne,n as re}from"./touch-runtime.js";import{r as ie,t as ae}from"./gesture-admission.js";import{B as oe,C as se,D as ce,E as le,F as ue,L as de,M as fe,P as pe,R as me,U as he,V as ge,W as _e,_ as ve,h as ye,j as be,k as xe,l as Se,o as Ce,p as we,r as g,v as _,x as v}from"./tv-remote-runtime.js";import{n as y}from"./audio-probe-runtime.js";import{n as b}from"./perf-runtime.js";import{a as x,i as S,r as C}from"./screenshot-runtime2.js";import{t as w}from"./viewport-runtime.js";import{i as T,t as E,u as D}from"./application-lifecycle-interaction.js";import{n as O}from"./interactor-operation-catalog.js";import{a as k,i as Te,n as Ee,o as De,r as Oe,s as ke}from"./network-traffic.js";import{t as A}from"./app-log-runtime.js";import{r as Ae}from"./platform-runtime-unavailable.js";import{n as je,r as Me,t as Ne}from"./screen-recording-transport.js";import{randomUUID as Pe}from"node:crypto";import{setTimeout as Fe}from"node:timers/promises";function Ie(e,t){let n=async()=>{t.throwIfAborted();let n=await e();if(t.throwIfAborted(),!n)throw new a(`DEVICE_NOT_FOUND`,`Limrun Android session is unavailable`);return n};return{perfFrames:async e=>(await n()).perfFrames(e),perfMemorySample:async e=>(await n()).perfMemorySample(e),perfMemorySnapshot:async e=>(await n()).perfMemorySnapshot(e)}}const j=Object.freeze({available:!0}),M=r(`unsupported-provider-mode`),Le=r(`unsupported-platform-leaf`,"Run `agent-device settings --help` for the settings each target serves."),N=r(`unsupported-provider-mode`,`Limrun exposes the commanded hinge angle, but fold requires an independently observed angle to verify the pose.`),P=r(`unsupported-provider-mode`,`telephony sends calls and SMS to an Android emulator's console through local adb; agent-device does not route it through a Limrun session.`);function Re(e){let t=e.target===`tv`;return{...ge({focus:j}),...ce({type:j}),...ne({unsupported:M,tap:j,longPress:j,fill:j}),...me({unsupported:M,plan:j,directionalFling:j,viewport:j,multiTouch:t?r(`unsupported-platform-leaf`,ae):j,targetAuthoredDrag:t?r(`unsupported-platform-leaf`,ie):j}),...ue({scroll:j}),...se({back:j}),...Ce({orientation:j,unlock:j}),...g({tvRemote:t?j:r(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets.`)}),...Se({unsupported:M,status:j,dismiss:j,enter:j}),...we({unsupported:M,read:j,write:j}),...ve({unsupported:M,home:j,appSwitcher:j,...ye(e)}),...v({read:j,wait:j,accept:j,dismiss:j}),..._({triggerAppEvent:j})}}function ze(e){let{device:t,signal:r}=e,i=n=>e.getInteractor(t,n);return Object.freeze({...n(e.facts.readTextAtPoint,()=>he({device:t,signal:r,resolveInteractor:i})),...xe({device:t,signal:r,resolveInteractor:i,presentIosAcquisition:e.presentIosAcquisition}),...oe({device:t,signal:r,resolveInteractor:i}),...le({device:t,signal:r,resolveInteractor:i}),...re({device:t,signal:r,resolveInteractor:i,facts:e.facts,pause:async e=>await Fe(e,void 0,{signal:r})}),...C({device:t,signal:r,resolveInteractor:i,captureCapabilities:S(`Limrun captures through its provider endpoint`)}),...de({device:t,signal:r,facts:e.facts,resolveInteractor:i}),...pe({device:t,signal:r,resolveInteractor:i})})}function Be(e){return D({target:e??j,unsupported:Le,write:{wifi:j,bluetooth:j,airplane:j,"mobile-data":j,location:j,animations:j,appearance:j,"text-size":j,fingerprint:j,"clear-app-state":j,permission:j},read:{"text-size":j}})}function Ve(e){let t=e.setSetting;return{readSetting:e.readSetting??M,setSetting:t?.available?{...t,subjects:{...t.subjects,"reset-keychain":r(`unsupported-provider-mode`,`Limrun does not expose keychain reset.`)}}:t??M}}const F=5e3;async function He(e){let t=new te,n=!1;t.defer(async()=>{n||await e.reader[Symbol.asyncDispose]()});try{let r=await e.host.outputs.readTail(e.outputPath,262144),i=await e.host.outputs.openAppend(e.outputPath);t.defer(async()=>{n||await i[Symbol.asyncDispose]()});let a=Ue(e,i,Je(r));return n=!0,a}finally{await t[Symbol.asyncDispose]()}}function Ue(e,t,n){let{backend:r,host:i}=e,a=i.clock.now(),o=`active`,s=new AbortController,c=n,l,u=()=>{let t=Ge(e,s.signal),n=t.settled.then(()=>{l===n&&(l=void 0)});return l=n,t.outcome},d=async()=>{if(l)return`recovering`;let e=await u();if(e.status===`timeout`||s.signal.aborted)return`recovering`;let n=I(c,e.text);return n&&await t.write(n.endsWith(` `)?n:`${n}\n`),c=e.text,`active`},f=(async()=>{for(;!s.signal.aborted;){let e=await d().catch(()=>`recovering`);if(s.signal.aborted)return;o=e,await i.clock.sleep(1e3,s.signal).catch(()=>void 0)}})(),p=new Set([e.reader,t]),m;return k({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>m??=(async()=>{s.abort(),await f;let t=await We(l,i,F),n=await Ye(p,t?void 0:e.reader);return t||n.push(Error(`provider read still in flight`)),n.length>0?(m=void 0,o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`${e.provider} app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:e.outputPath,completedAt:i.clock.now()}})})()})}async function We(e,t,n){if(!e)return!0;let r=new AbortController;try{return await Promise.race([e.then(()=>!0),t.clock.sleep(n,r.signal).then(()=>!1)])}finally{r.abort()}}function Ge(e,t){let n=new AbortController,r=AbortSignal.any([n.signal,t]),i=e.reader.readLogs(e.appBundleId,1e3,r).then(e=>({status:`read`,text:e})),a=i.then(()=>void 0,()=>void 0);return{outcome:Promise.race([i,e.host.clock.sleep(F,r).then(()=>({status:`timeout`}))]).finally(()=>n.abort()),settled:a}}function I(e,t){if(!e||!t)return t;let n=Ke(t),r=Math.min(e.length,t.length),i=e.slice(e.length-r);return t.slice(qe(i,t,n))}function Ke(e){let t=new Uint32Array(e.length),n=0;for(let r=1;r<e.length;r+=1){for(;n>0&&e[r]!==e[n];)n=t[n-1];e[r]===e[n]&&(n+=1),t[r]=n}return t}function qe(e,t,n){let r=0;for(let i=0;i<e.length;i+=1){for(;r>0&&e[i]!==t[r];)r=n[r-1];e[i]===t[r]&&(r+=1),r===t.length&&i<e.length-1&&(r=n[r-1])}return r}function Je(e){return e.split(` `).filter(e=>!e.startsWith(`[agent-device][mark]`)).join(` `)}async function Ye(e,t){return(await Promise.allSettled([...e].filter(e=>e!==t).map(async t=>{await t[Symbol.asyncDispose](),e.delete(t)}))).flatMap(e=>e.status===`rejected`?[e.reason]:[])}function Xe(e){let{host:t,signal:n}=e,r=`${e.provider} app-log descriptor does not match the bound device or owning session`,i=(n,r)=>e.matchesDevice(n)&&Oe(t,r,n),o=async(n,r)=>await He({host:t,provider:e.provider,backend:e.backend,reader:n,appBundleId:r.appBundleId,outputPath:r.outputPath}),s=De({codec:e.codec,reattach:async(t,a)=>{if(!i(t,a.sessionId))return{status:`unreattachable`,reason:`descriptor-invalid`,message:r};let s=await e.reconnect(t,n);return s.status===`missing`?{status:`missing`}:s.status===`ownership-lost`?{status:`unreattachable`,reason:`ownership-fence-lost`}:{status:`active`,handle:await o(s.reader,t)}},cleanup:async(e,t)=>i(e,t.sessionId)?{status:`cleaned`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:r}});return Object.freeze({appLogInspect:async()=>({backend:e.backend}),appLogDoctor:async()=>({backend:e.backend,checks:{[e.sessionCheck]:await Qe(e)},notes:[]}),appLogStart:async r=>{Te(t,r),n.throwIfAborted();let i=await e.openCurrent();if(!i)throw new a(`UNSUPPORTED_OPERATION`,e.unavailableMessage);let s=!1;try{n.throwIfAborted();let t=Ze({provider:e.provider,codec:e.codec,sessionId:r.sessionId,device:e.device,owner:e.owner,fence:r.fence,descriptor:e.describe(i,r)});return s=!0,ke(await o(i,r),t)}catch(e){throw s||await i[Symbol.asyncDispose](),e}},...s,networkDump:async n=>{let r=await t.appLogs.readRecent(n.sessionId,n.maxScanLines),{dump:i}=Ee(r.text,{...n,path:r.path,exists:r.exists,lineNumberOffset:r.skippedLines,backend:e.backend}),a=i.entries.length===0?[`No HTTP(s) entries were found in recent session app logs.`]:[];return Object.freeze({source:`app-log`,backend:e.backend,dump:i,notes:a})}})}function Ze(e){let{device:t}=e;if(t.platform===`apple`&&!t.appleOs)throw TypeError(`${e.provider} Apple app-log persistence requires an explicit appleOs identity`);return m({resourceKind:A,sessionId:e.sessionId,device:o(t),owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:p(e.codec,e.descriptor)})}async function Qe(e){e.signal.throwIfAborted();let t=await e.openCurrent();if(!t)return!1;try{e.signal.throwIfAborted()}finally{await t[Symbol.asyncDispose]()}return!0}const $e=Object.freeze({resourceKind:A,version:1,encode:e=>({...e}),decode:e=>{let t=et(e.ownership);return!t||e.transport!==`limrun-log-poller`||e.platform!==`ios`&&e.platform!==`android`||!L(e.leaseId)||!L(e.instanceId)||!L(e.appBundleId)||!L(e.outputPath)?{status:`invalid`,message:`Invalid Limrun app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`limrun-log-poller`,platform:e.platform,leaseId:e.leaseId,instanceId:e.instanceId,ownership:t,appBundleId:e.appBundleId,outputPath:e.outputPath})}}});function et(e){return e===void 0?`created`:e===`created`||e===`attached`?e:void 0}function L(e){return typeof e==`string`&&e.trim().length>0}function tt(e,t){let n=t??E({owner:`Limrun`,openTargetIdentity:`bundle-id`,closeBeforeRelaunch:!0,configureProviderPortReverse:async t=>await e.configurePortReverse(t),binding:T({device:e.device,signal:e.signal,resolveInteractor:t=>e.getInteractor(e.device,t)})}),r=e.resolveAppReference;return r?Object.freeze({...n,resolveOpenTarget:async e=>await n.resolveOpenTarget(nt(e,r)),openApplication:async e=>await n.openApplication(rt(e,r)),closeApplication:async e=>await n.closeApplication(it(e,r))}):n}function nt(e,t){return e.target===void 0?e:{...e,target:t(e.target)}}function rt(e,t){return{...e,target:z(e.target,t),positionals:R(e.positionals,t),appBundleId:z(e.appBundleId,t)}}function it(e,t){return{...e,positionals:R(e.positionals,t),appBundleId:z(e.appBundleId,t)}}function R(e,t){let n=e[0];return n===void 0?e:[t(n),...e.slice(1)]}function z(e,t){return e===void 0?void 0:t(e)}function at(e){let t=u(e.id);return!t||e.target!==`mobile`?!1:t.platform===`ios`?e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&e.iosPhysicalDeviceBackend===void 0:e.platform===`android`&&e.appleOs===void 0&&e.kind===`emulator`&&e.iosPhysicalDeviceBackend===void 0}const ot=Object.freeze({available:!0}),B=r(`owner-capability-missing`,`The Limrun provider session is no longer active for this device.`),st=r(`unsupported-provider-mode`,`Push notifications are unavailable for Limrun provider-owned devices.`);function V(e,t){let n=e.isSessionActive?.(t)??e.ownsDevice(t),r=at(t)&&n&&e.bindDeployment?ot:B;return Object.freeze({deployApp:r,materializeAppSource:r,deployMaterializedApp:r,uninstallApp:r,sendPushNotification:t.platform===`apple`?r:n?st:B})}function ct(e,t,n,r){if(!V(e,t).deployApp.available)return{};let i=e.bindDeployment,o=async()=>{n.throwIfAborted();let{deployApp:e,materializeAppSource:o,deployMaterializedApp:s,uninstallApp:c,sendPushNotification:l}=await i(t,n,r);if(!e||!o||!s||!c)throw new a(`UNSUPPORTED_OPERATION`,`The Limrun provider session is no longer active.`);return{deployApp:e,materializeAppSource:o,deployMaterializedApp:s,uninstallApp:c,sendPushNotification:l}};return{...t.platform===`apple`?{sendPushNotification:async e=>{let t=(await o()).sendPushNotification;if(!t)throw new a(`UNSUPPORTED_OPERATION`,`Apple push operation is unavailable`);return await t(e)}}:{},deployApp:async e=>f(r,(await o()).deployApp(e),n),materializeAppSource:async e=>(await o()).materializeAppSource(e),deployMaterializedApp:async e=>(await o()).deployMaterializedApp(e),uninstallApp:async e=>(await o()).uninstallApp(e)}}const lt=Object.freeze({medium:5,high:8});function ut(e){return Object.freeze({screenRecordingStart:async t=>await dt(e,t),screenRecordingReattach:async()=>Me(`Limrun recordings cannot be reattached after daemon restart.`),screenRecordingCleanup:async()=>je(`Limrun recordings cannot be cleaned after daemon restart; the instance disposes them when it terminates.`)})}async function dt(e,t){let n=e.getDeviceSession(e.device);if(!n)throw new a(`UNSUPPORTED_OPERATION`,`Limrun recording requires a live provider session for this device.`,{deviceId:e.device.id});let r=Pe();return await Ne({host:e.host,device:e.device,owner:e.owner,input:t,signal:e.signal,transport:{backend:`limrun-recorder`,targetLabel:`Limrun recording`,start:async()=>{await n.startRecording({recordingId:r,quality:lt[t.exportQuality??`medium`]})},stop:async()=>(await n.stopRecording(r)).downloadUrl,collect:async(e,t)=>{await n.downloadRecording({downloadUrl:e,outPath:t})}},support:{scopes:[`app`,`device`,`system`],fps:!1,exportQuality:!0,hideTouches:!1},unsupported:e=>`Limrun recordings do not support ${e.join(`, `)}`})}const H=Object.freeze({available:!0}),U=r(`unsupported-provider-mode`,`Custom snapshot actions are available only for Limrun iOS simulator sessions.`),ft=r(`unsupported-provider-mode`,`Limrun does not expose viewport resizing.`),W=r(`unsupported-provider-mode`,`Read element text from the captured snapshot.`),pt=r(`unsupported-provider-mode`,`Headless boot is unavailable for provider-owned devices.`),G=r(`owner-capability-missing`,`Limrun requires a matching live provider session for this device.`),mt=r(`unsupported-provider-mode`,`Apple runner preparation is unavailable for Limrun-owned devices.`),ht=r(`unsupported-provider-mode`,`Limrun open requires a Limrun-owned iOS simulator or Android emulator.`),gt=r(`unsupported-provider-mode`,`Limrun close requires a Limrun-owned iOS simulator or Android emulator.`),K=r(`unsupported-provider-mode`,`Runtime hints are not applied to provider-owned devices.`),_t=r(`unsupported-provider-mode`,`Limrun port reverse requires an active Android Limrun session.`),q=r(`unsupported-provider-mode`,`Limrun does not expose the audio probe.`);function J(e){return{...e,isSessionActive:e.hasLiveSession}}function Y(e,t){let n=vt(e,t),r=yt(e,t),i=bt(e,t);return h({resolveOpenTarget:n,prepareApplicationOpen:n,openApplication:n,applyRuntimeHints:c(e)&&n.available?H:K,clearRuntimeHints:c(e)&&n.available?H:K,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:c(e)&&n.available?H:mt,configureProviderPortReverse:i})}function vt(e,t){return l(e)?t?H:G:ht}function yt(e,t){return l(e)?t?H:G:gt}function bt(e,t){return t?e.platform===`android`?H:_t:G}function X(e,t){let n=V(J(e),t),r=t.platform===`android`,a=e.getIosRunner(t);if(!r&&!a)throw i(`Limrun iOS session has no Apple runner`);let o=r?Re(t):a.facts;return Object.freeze({device:{...s(t),providerMode:`provider-runtime`},operations:{...$(e,t).operations,appLogInspect:H,appLogDoctor:H,appLogStart:H,appLogReattach:H,appLogCleanup:H,...n,...r?{appState:H}:{},networkDump:H,screenRecordingStart:H,screenRecordingReattach:H,screenRecordingCleanup:H,...r?{...be({capture:H,customActions:U,withoutActiveApp:H}),...fe({findText:U,querySelector:U}),..._e({readTextAtPoint:H})}:{},...x({capture:H}),...w({setViewport:ft}),...Y(t,!0),...o,setFoldPose:N,sendTelephonyEvent:P,...r?Be():Ve(o),...y({capture:q,query:q}),...b({frames:r?H:W,memorySample:r?H:W,memorySnapshot:r?H:W,nativeCapture:W,profileReport:W}),ensureReady:H,bootTarget:H,bootTargetHeadless:pt,listApps:H,shutdownTarget:H}})}function Z(e,t){let n=$(e,t);return{device:n.device,operations:{...n.operations,appLogReattach:H,appLogCleanup:H}}}function Q(e,t){let n=Z(e,t);return{...n,operations:{...n.operations,resolveOpenTarget:H,closeApplication:H,finalizeApplicationClose:H,clearRuntimeHints:c(t)?H:K,shutdownTarget:H}}}function $(e,n){let r=t(`limrun`,e.runtimeInstance);return Ae(n,r,{appLog:G,appState:G,appDeployment:G,network:G,screenshot:G,viewport:G,focus:G,gesture:G,scroll:G,typeText:G,touch:G,elementText:G,back:G,orientation:G,tvRemote:G,keyboard:G,clipboard:G,systemButton:G,fold:N,telephony:P,triggerAppEvent:G,settings:G,readAlert:G,awaitAlert:G,acceptAlert:G,dismissAlert:G,audioProbeCapture:G,audioProbeQuery:G,perf:G,readiness:G,shutdown:G,lifecycle:Y(n,!1)})}function xt(n){let r=t(`limrun`,n.runtimeInstance),i=e=>l(e)&&n.ownsDevice(e),o=e=>i(e)&&n.hasLiveSession(e);return Object.freeze({owner:r,ownsDevice:i,inspectFacts:async e=>o(e)?X(n,e):i(e)&&n.hasPendingRelease?.(e)?Q(n,e):$(n,e),bind:async t=>{if(t.intent.kind===`exact-owner`&&!e(t.intent.owner,r))throw new a(`UNSUPPORTED_OPERATION`,`Limrun app-log owner identity does not match`);if(!l(t.device))throw new a(`UNSUPPORTED_PLATFORM`,`Limrun app logs require an iOS simulator or Android emulator device identity`);let i=o(t.device),s=n.hasPendingRelease?.(t.device)===!0;if(t.intent.kind!==`exact-owner`&&!i&&!s)throw new a(`UNSUPPORTED_OPERATION`,`Limrun provider session is no longer live for the selected device`,{reason:`provider-session-unavailable`});return St(n,r,t.device,t.scope.signal,s?`release`:i?`live`:`recovery`)},shutdown:async()=>void 0})}function St(e,t,r,i,o){let s=o===`release`?Q(e,r):o===`recovery`?Z(e,r):X(e,r),c=d(),l=Xe({host:e.host,device:r,owner:t,signal:i,provider:`Limrun`,backend:r.platform===`apple`?`ios-simulator`:`android`,sessionCheck:`limrunSessionAvailable`,unavailableMessage:`Limrun app logs require an active instance`,codec:$e,openCurrent:async()=>await e.openCurrent(r),describe:(e,t)=>({transport:`limrun-log-poller`,platform:e.platform,leaseId:e.leaseId,instanceId:e.instanceId,ownership:e.ownership,appBundleId:t.appBundleId,outputPath:t.outputPath}),matchesDevice:e=>Ct(e,r),reconnect:async(t,n)=>await e.reconnect(t,n)}),f=(t,n)=>{let r=e.getInteractor(t,n);if(!r)throw new a(`DEVICE_NOT_FOUND`,`Limrun session is unavailable`);return r},p=ze({device:r,signal:i,getInteractor:f,presentIosAcquisition:e.host.snapshot.presentIosAcquisition,facts:s.operations}),m=e.getIosRunner(r)?.bindRunnerOperations({signal:i,resolveInteractor:async(e,t)=>f(e,t),snapshot:{capture:p,present:e.host.snapshot.presentIosAcquisition}}),h={...l,ensureReady:async()=>({...r,booted:!0}),bootTarget:async()=>({...r,booted:!0}),shutdownTarget:async e=>{let t=u(r.id);if(!t)throw new a(`DEVICE_NOT_FOUND`,`Limrun device identity is unavailable`);return await e.releaseLease(t.leaseId)},listApps:async t=>await e.listApps(t.device,t.filter,i),...ee(tt({device:r,signal:i,getInteractor:f,resolveAppReference:t=>e.resolveAppReference?.(r,t)??t,configurePortReverse:e.configurePortReverse},e.getIosRunner(r)?.bindApplicationLifecycle({signal:i,clock:e.host.clock,resolveInteractor:async(e,t)=>f(e,t)})),s.operations),...p,...m,...n(s.operations.perfFrames,()=>Ie(()=>e.bindPerformance(r),i)),appState:async t=>{let n=await m?.appState(t);return n?.applicationState===void 0?await e.getAppState(r,i):n},...O({device:r,signal:i,resolveInteractor:e=>f(r,e),facts:s.operations}),...ct(J(e),r,i,c),...ut({host:e.host,device:r,owner:t,signal:i,getDeviceSession:e.getDeviceSession})};return Object.freeze({device:r,owner:t,facts:s,operations:Object.freeze(o===`release`?{appLogReattach:l.appLogReattach,appLogCleanup:l.appLogCleanup,resolveOpenTarget:h.resolveOpenTarget,closeApplication:h.closeApplication,finalizeApplicationClose:async()=>({}),...n(s.operations.clearRuntimeHints,()=>({clearRuntimeHints:async()=>void 0})),shutdownTarget:h.shutdownTarget}:o===`recovery`?{appLogReattach:l.appLogReattach,appLogCleanup:l.appLogCleanup}:h),[Symbol.asyncDispose]:async()=>await c[Symbol.asyncDispose]()})}function Ct(e,t){if(!l(t))return!1;let n=u(t.id);return n!==void 0&&n.leaseId===e.leaseId&&n.platform===e.platform&&(t.platform===`apple`?e.platform===`ios`:e.platform===`android`)}export{xt as createLimrunPlatformRuntimeOwner};