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.

1 lines • 8.81 kB
import{F as e,v as t}from"./sdk-contracts.js";import{G as n,l as r,t as i}from"./host2.js";import{a,o,r as s,t as c}from"./runner-startup-transport.js";import{h as l,i as u,l as d,p as f,v as p,w as m}from"./runner-contract.js";import{C as h,E as g,S as _,T as v,h as y,p as b,s as x,u as S,w as C}from"./runner-error-classification.js";import{r as w,t as T,u as ee}from"./runner-session-types.js";import{r as te}from"./runner-io.js";import E from"node:fs/promises";const D=2e3;async function O(e,t={}){if(e){try{await te(e,{timeoutMs:Math.min(D,t.timeoutMs??D),signal:t.signal})}catch{return}try{return{logPath:e,byteOffset:(await E.stat(e)).size}}catch{return{logPath:e,byteOffset:0}}}}async function k(e){let n=await A(e.logSince)??M(e.error);return n?new t(n.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${n.hint}`:n.hint,runnerFailureReason:n.reason},e.error):e.error}async function A(e){if(!e)return;let t=await I(e,65536);if(t)return j(t)}function j(e){let t=e.toLowerCase();if(N(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(P(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function M(e){if(F(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function N(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function P(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function F(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function I(e,t){let n;try{let r=await E.stat(e.logPath),i=Math.max(e.byteOffset,r.size-t),a=r.size-i;if(a<=0)return;n=await E.open(e.logPath,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}async function L(e,t,n,r,i,a,o){try{return await R(e,t,n,r,i,a,o)}catch(e){let n=b(e);throw n&&(t.lastHealthyMutation=void 0,await a(n)),e}}async function R(e,t,n,r,a,o,s){let c=await O(r,{timeoutMs:a,signal:s}),l=m(n),u=C(l),d=i.fromTimeoutMs(a),f=ne(t,l);f.action===`run`?await q({device:e,session:t,runnerCommand:l,logAttempt:c,deadline:d,signal:s,decision:f}):J(l,t,f);let p;try{p=await U({device:e,session:t,runnerCommand:l,logPath:r,deadline:d,timeoutMs:a,signal:s,readOnlyCommand:u})}catch(e){throw H(e,t,f)}try{let e=await Y(p,t,c);return await z(t,l,e,o),e}catch(e){let n=B(t,l,e);throw b(e)||n?e:H(e,t,f)}}async function z(e,t,n,r){e.commandCharges.settleAnswered(t.commandId);let i=V(n);i!==void 0&&(e.runnerMainThreadBusy=i);let a=Z(n);a?(e.lastHealthyMutation=void 0,await r(a)):_(t)&&(e.lastHealthyMutation={atMs:Date.now(),appBundleId:t.appBundleId})}function B(e,t,n){let r=S(n);r?e.commandCharges.settleAnswered(t.commandId):e.commandCharges.markAbandoned(t.commandId);let i=y(n);return i!==`silent`&&(e.runnerMainThreadBusy=i===`occupied`),r}function V(e){return typeof e.runnerMainThreadBusy==`boolean`?e.runnerMainThreadBusy:void 0}function H(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,Q(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function U(e){let{device:r,session:i,runnerCommand:c,logPath:l,deadline:u,timeoutMs:d,signal:f,readOnlyCommand:p}=e,m=u.remainingMs();if(m<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:d});let g=p?{command:c.command,commandId:c.commandId,readOnly:!0,sessionReady:i.state===`ready`,timeoutMs:m}:{command:c.command,commandId:c.commandId};o(f);let _=h(c);_&&i.commandCharges.charge(c.commandId);try{return await n(`ios_runner_command_send`,async()=>p?await s(r,i.endpoint,c,l,m,i,f):await a(r,i.endpoint,c,m,f),g)}catch(e){throw _&&await W({device:r,session:i,runnerCommand:c,deadline:u,signal:f,error:e}),e}}async function W(t){let{session:n,runnerCommand:r,signal:i,error:a}=t;if(x(a)){n.commandCharges.withdrawUnsent(r.commandId);return}n.commandCharges.markAbandoned(r.commandId),!(!e(i?.reason)||n.state!==`ready`)&&await G(t)}async function G(e){let{device:t,session:n,runnerCommand:i,deadline:a}=e,o=Date.now(),s=`deadline_exceeded`,c,l=0;for(;a.remainingMs()>0;){l+=1;try{c=await K(t,n,i,Math.min(1e3,a.remainingMs()))}catch{s=`status_unavailable`;break}if(ee(n,i,c)!==void 0){s=`terminal`;break}if(!T.has(c)){s=`not_in_flight`;break}let e=Math.min(100,a.remainingMs());await new Promise(t=>setTimeout(t,e))}r({level:s===`terminal`?`debug`:`warn`,phase:`ios_runner_canceled_command_drain`,durationMs:Date.now()-o,data:{command:i.command,commandId:i.commandId,outcome:s,lifecycleState:c,polls:l}})}async function K(e,t,n,r){let i=await Y(await a(e,t.endpoint,{command:`status`,statusCommandId:n.commandId},r),t);return typeof i.lifecycleState==`string`?i.lifecycleState:``}async function q(e){let{device:t,session:r,runnerCommand:i,logAttempt:a,deadline:o,signal:c,decision:l}=e,d=a?.logPath,f=r.state===`ready`?Math.min(u,o.remainingMs()):Math.min($(r),o.remainingMs());try{let e=V(await Y(await n(`ios_runner_readiness_preflight`,async()=>await s(t,r.endpoint,m({command:`uptime`}),d,f,r,c),{command:i.command,commandId:i.commandId,reason:l.reason,lastHealthyMutationAgeMs:l.lastHealthyMutationAgeMs,sessionReady:r.state===`ready`,timeoutMs:f}),r,a));e!==void 0&&(r.runnerMainThreadBusy=e)}catch(e){throw re(e)}}function J(e,t,n){r({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:n.reason,lastHealthyMutationAgeMs:n.reason===`recent_healthy_mutation`?n.lastHealthyMutationAgeMs:void 0,sessionReady:t.state===`ready`}})}async function Y(e,t,n){let r=f(await e.text());if(!l(r))throw await k({error:d(r,n?.logPath),logSince:n});w(t,`ready`);let i=p(r);return X(i),i}function X(e){let t=e.gestureFallback;typeof t==`string`&&t.length!==0&&r({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function Z(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function ne(e,t){let n=C(t);if(e.state!==`ready`)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(v(t))return{action:`skip`,reason:`preflight_exempt_command`};if(g(t))return{action:`skip`,reason:`readiness_probe_command`};if(!_(t))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function re(e){return Q(e,{runnerReadinessPreflightFailed:!0})}function Q(e,n){let r=e instanceof t?e:new t(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new t(r.code,r.message,{...r.details??{},...n},r.cause??e)}function $(e){let t=e.launchDeadline;return t?Math.max(0,Math.floor(t.remainingMs())):c}export{L as executeRunnerExchange,$ as readRunnerStartupTimeoutMs};