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 • 11.4 kB
import{v as e}from"./sdk-contracts.js";import{H as t,St as n,Z as r}from"./sdk-io.js";import"./diagnostics.js";import"./command.js";import"./retry.js";import{O as i}from"./host-file.js";import{d as a}from"./config.js";import{c as o}from"./tool-provider.js";import{a as s,c,i as l,l as u,n as d,o as f,r as p,s as m,t as h}from"./devicectl.js";import{n as g,r as _,t as v}from"./physical-device-constants.js";async function y(e,t){return await l(e,t)}async function b(e,t){await u(e,t)}async function x(e,t){return await s(e,t)}function S(e){return e.includes(`not installed`)||e.includes(`not found`)||e.includes(`no such file`)}const C=1e4;async function w(e,t,n={}){let r=[`device`,`process`,`launch`,`--device`,e.id];n.payloadUrl&&r.push(`--payload-url`,n.payloadUrl),r.push(t),n.launchArgs&&n.launchArgs.length>0&&r.push(`--`,...n.launchArgs),await m(r,{action:`launch iOS app`,deviceId:e.id})}async function ee(t,n){try{let i=await k(t.id,g,v,n);if(i.status===`unreadable`)throw new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{kind:`probe_inconclusive`,deviceId:t.id,stdout:i.result.stdout,stderr:i.result.stderr,hint:`CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device.`});if(i.status===`reported`){let n=i.details.tunnelState?.toLowerCase();if(n===`connecting`)throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,{kind:`not_ready`,deviceId:t.id,tunnelState:n,hint:`Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry.`});if(!_(n))throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,{kind:`not_ready`,deviceId:t.id,tunnelState:n,hint:`CoreDevice cannot reach the device. Connect it by cable or to the same network as this Mac, unlock it, and wait until Xcode Devices lists it as available, then retry.`});return}throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,r(i.result,{kind:`not_ready`,deviceId:t.id,tunnelState:i.details.tunnelState,hint:U(i.result.stdout,i.result.stderr)}))}catch(e){throw T(t.id,e)}}function T(t,n){return!(n instanceof e)||n.code!==`COMMAND_FAILED`?D(t,n):(typeof n.details?.kind==`string`?n.details.kind:``)===`not_ready`?n:E(t,n)}function E(t,n){let r=n.details??{},i=String(r.stdout??``),a=String(r.stderr??``),o=Number(r.timeoutMs??15e3),s=`CoreDevice did not respond within ${o}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,cause:n.message,timeoutMs:o,stdout:i,stderr:a,hint:i||a?U(i,a):s},n)}function D(t,n){return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,hint:`Reconnect the device, keep it unlocked, and retry.`},n instanceof Error?n:void 0)}async function te(e,t){return(await O(e,t??C))?.tunnelIp??null}async function O(e,t,n){if(!(t>0))return null;let r=Math.max(1,Math.min(C,t));try{let t=await k(e.id,r,0,n);return t.status!==`reported`||t.details.outcome&&t.details.outcome!==`success`?null:t.details}catch{return null}}async function k(e,t,n=0,r){let i=Math.max(5,Math.ceil(t/1e3)),a=await c({jsonPrefix:`agent-device-coredevice-info`,args:[`devicectl`,`device`,`info`,`details`,`--device`,e,`--timeout`,String(i)],signal:r,timeoutMs:t+n});return a.ok?{status:`reported`,details:N(a.payload)}:a.reason===`unreadable-json`?{status:`unreadable`,result:a.result}:{status:`failed`,result:a.result,details:N(a.payload)}}function A(e){let t=e,n=M(t.device);return{connectionProperties:j(M(t.connectionProperties),M(n?.connectionProperties)),deviceProperties:j(M(t.deviceProperties),M(n?.deviceProperties))}}function j(e,t){if(!e)return t;if(!t)return e;let n={...t};for(let[t,r]of Object.entries(e))r!==void 0&&(n[t]=r);return n}function M(e){return e&&typeof e==`object`?e:void 0}function N(e){let t=M(e?.result);if(!t)return{};let{connectionProperties:n,deviceProperties:r}=A(t);return{...P(`outcome`,F(e?.info?.outcome)),...P(`tunnelState`,F(n?.tunnelState)),...P(`tunnelIp`,F(n?.tunnelIPAddress)),...P(`developerModeStatus`,F(r?.developerModeStatus)),...P(`developerDiskImageServicesAvailable`,I(r?.ddiServicesAvailable)),...P(`bootState`,F(r?.bootState))}}function P(e,t){return t===void 0?{}:{[e]:t}}function F(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function I(e){return typeof e==`boolean`?e:void 0}const L={developerModeOff:p,developerDiskImageUnavailable:d};function R(e){return e.tunnelState===`connected`&&e.bootState===`booted`}function z(e){return`The device reported its developer disk image as unavailable while it was not observable (tunnelState=${e.tunnelState??`unknown`}, bootState=${e.bootState??`unknown`}). Unlock it, keep it connected by cable until \`xcrun devicectl device info details\` reports tunnelState=connected and bootState=booted, then retry.`}async function B(e,t=1e4,n){let r=await O(e,t,n);if(!r)return{available:!1,reason:`device_readiness_unreadable`,hint:"Read the device state directly with `xcrun devicectl device info details --device <id> --json-output -`, keeping the device unlocked and connected by cable, then retry."};let i=V(r.developerModeStatus),a=H(r.developerDiskImageServicesAvailable);return a===`unavailable`&&i!==`disabled`&&!R(r)?{available:!1,reason:`device_readiness_unreadable`,hint:z(r)}:{available:!0,developerMode:i,developerDiskImage:a,remedies:L}}function V(e){let t=e?.toLowerCase();return t===`enabled`?`enabled`:t===`disabled`?`disabled`:`unknown`}function H(e){return e===!0?`available`:e===!1?`unavailable`:`unknown`}function U(e,t){return f(e,t)||(`${e}\n${t}`.toLowerCase().includes(`timed out waiting for all destinations`)?`Xcode destination did not become available in time. Keep device unlocked and retry.`:h)}async function W(n,r,i,s,c=a){let l=t.fromTimeoutMs(c),{resolveRunnerContainerBundleIds:u}=await import(`./src8.js`).then(e=>e.u),d={exitCode:1,stdout:``,stderr:``};for(let e of u(s))if(d=await o([`devicectl`,`device`,`copy`,`from`,`--device`,n.id,`--source`,r,`--destination`,i,`--domain-type`,`appDataContainer`,`--domain-identifier`,e],{allowFailure:!0,timeoutMs:G(l,c)}),d.exitCode===0)return;let f=d.stderr.trim()||d.stdout.trim()||`devicectl exited with code ${d.exitCode}`;throw new e(`COMMAND_FAILED`,`Failed to copy runner file from iOS device: ${f}`)}function G(t,n){let r=t.remainingMs();if(r>0)return r;throw new e(`COMMAND_FAILED`,`iOS runner file copy timed out after ${n}ms`,{timeoutMs:n,step:`runner file copy`})}function K(t){if(!(t instanceof e))return{reason:t instanceof Error?t.message:String(t)};let n=t.details??{},r=Array.isArray(n.args)?n.args.filter(e=>typeof e==`string`).join(` `):void 0;return{errorCode:t.code,reason:t.message,timeoutMs:typeof n.timeoutMs==`number`?n.timeoutMs:void 0,exitCode:typeof n.exitCode==`number`?n.exitCode:void 0,stderr:typeof n.stderr==`string`&&n.stderr.trim()?n.stderr:void 0,stdout:typeof n.stdout==`string`&&n.stdout.trim()?n.stdout:void 0,commandArgs:r}}function q(e){let t=e.details??{},n=typeof t.stdout==`string`?t.stdout:``,r=typeof t.stderr==`string`?t.stderr:``,i=Array.isArray(t.args)?t.args.filter(e=>typeof e==`string`).join(` `):``;return`${e.message}\n${n}\n${r}\n${i}`.toLowerCase()}async function J(e,t,n){if(!n.preferRunner)try{return await m([`device`,`capture`,`screenshot`,`--device`,e.id,`--destination`,t],{action:`capture iOS screenshot`,deviceId:e.id}),{iosPhysicalCaptureBackend:`coredevice`}}catch(t){if(!re(t))throw t;ne(e,t)}let r=await X(e,n,!1);return await Z(r,t)||await W(e,Q(r),t,n.env),{iosPhysicalCaptureBackend:`xctest`}}async function Y(t,n,r){if(await Z(await X(t,r,!0),n))return{iosPhysicalCaptureBackend:`xctest`};throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: XCTest runner returned no inline image`,{deviceId:t.id,backend:`xctest`})}async function X(e,t,n){return await t.runRunnerCommand(e,{command:`screenshot`,appBundleId:t.appBundleId,fullscreen:t.fullscreen,inlineScreenshot:n},t.runnerOptions??{})}async function Z(e,t){let n=e.imageBase64;return typeof n!=`string`||n.length===0?!1:(await i(t,Buffer.from(n,`base64`)),!0)}function Q(t){let n=t.message;if(typeof n==`string`&&n.length>0)return n;throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: runner returned no file path`)}function ne(e,t){n({level:`warn`,phase:`ios_screenshot_fallback`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:`devicectl_screenshot`,to:`runner`,...K(t)}})}function re(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=q(t);return n.includes(`unknown option '--device'`)||n.includes(`unknown subcommand`)&&n.includes(`screenshot`)||n.includes(`unrecognized subcommand`)&&n.includes(`screenshot`)}const ie={coredevice:{backend:`coredevice`,ensureReady:ee,listApps:y,launchApp:w,terminateApp:async(e,t)=>await b(e,t),resolveAppProcesses:x,captureScreenshot:J,copyRunnerFile:W,resolveTunnel:async(e,t)=>({tunnelIp:await te(e,t)}),readDeviceReadiness:B},xctest:{backend:`xctest`,ensureReady:ue,listApps:oe,launchApp:de,terminateApp:fe,resolveAppProcesses:$,captureScreenshot:Y,copyRunnerFile:le,resolveTunnel:se,readDeviceReadiness:ce}};function ae(e){return ie[e.iosPhysicalDeviceBackend===`xctest`?`xctest`:`coredevice`]}async function oe(t){throw new e(`UNSUPPORTED_OPERATION`,`App inventory is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use an installed app bundle ID when opening the device.`})}async function $(t){throw new e(`UNSUPPORTED_OPERATION`,`Process lookup is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use a CoreDevice-backed iOS device for performance sampling.`})}async function se(t){throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices have no CoreDevice tunnel.`,{deviceId:t.id,backend:`xctest`,hint:`Connect the device by cable so it is reachable through usbmux.`})}async function ce(e){return{available:!1,reason:`device_readiness_unreadable`,hint:`This device is driven through XCTest (device ${e.id}), which does not report Developer Mode or developer disk image state. Check the device's own Settings if development tooling fails to start on it.`}}async function le(t,n,r,i){throw new e(`UNSUPPORTED_OPERATION`,`Runner file copy is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`})}async function ue(t,n){let i=[`xcdevice`,`wait`,`--both`,`--timeout=${Math.max(1,Math.ceil(g/1e3))}`,t.id],a=await o(i,{allowFailure:!0,signal:n,timeoutMs:g+v});if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`iOS device is not ready for XCTest automation`,r(a,{cmd:`xcrun`,args:i,deviceId:t.id,backend:`xctest`,hint:"Keep the device unlocked, trusted, connected, and visible in `xcrun xcdevice list`, then retry."}))}async function de(t,n,r){if(r.payloadUrl||r.launchArgs&&r.launchArgs.length>0)throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices do not support deep links or launch arguments during open.`,{deviceId:t.id,backend:`xctest`,hint:`Open the installed app by bundle ID without a URL or --launch-args.`});await r.runRunnerCommand(t,{command:`activate`,appBundleId:n},r.runnerOptions??{})}async function fe(e,t,n){await n.runRunnerCommand(e,{command:`terminate`,appBundleId:t},n.runnerOptions??{})}export{K as n,S as r,ae as t};