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.

17 lines • 16.3 kB
import{C as e,v as t}from"./sdk-contracts.js";import{H as n,K as r,St as i,Z as a}from"./sdk-io.js";import"./diagnostics.js";import{a as o}from"./version.js";import"./command.js";import{r as s}from"./archive.js";import"./retry.js";import{n as c}from"./entities.js";import{t as l}from"./await-with-signal.js";import{r as u}from"./scoped-provider.js";import{S as d}from"./runner-contract.js";import{D as f}from"./runner-disposal.js";import"./runner-operations-facade.js";import{t as p}from"./limrun-download-file.js";import{t as m}from"./limrun-ios-files.js";import{createHash as h,randomInt as g,randomUUID as _}from"node:crypto";import{createReadStream as v,promises as y}from"node:fs";import b from"node:os";import x from"node:path";import{Readable as S}from"node:stream";import{pipeline as C}from"node:stream/promises";import{isIP as w}from"node:net";import{createGzip as T}from"node:zlib";const E={limrun_xctest_slot_occupied:`Another XCTest run owns this simulator. Stop its agent-device or Appium session, wait for its run stream to close, then retry. If the previous client died and the slot stays occupied, recreate the Limrun instance.`,limrun_runner_launch_failed:`Inspect runner.log and the Limrun XCTest stream. Use a simulator runner built for this instance’s Xcode and iOS runtime.`,limrun_runner_products_invalid:`Set AGENT_DEVICE_LIMRUN_IOS_RUNNER_APP to the simulator runner .app built for this instance’s Xcode and iOS runtime, or use a matching release runner.`,limrun_runner_upload_failed:`Check the Limrun instance connection and retry preparing the runner.`,limrun_runner_bind_address_missing:`The simulator must expose USE_IP for HTTP forwarding. Check the instance connection and simulator configuration.`};function D(e,n,r={},i=`COMMAND_FAILED`){return new t(i,n,{...r,reason:e,hint:r.hint??E[e]})}async function ee(e){try{return await e()}catch(e){if(!(e instanceof t))throw e;if(e.details?.runnerConnectFailureReason)throw new t(e.code,e.message,{...e.details,hint:E.limrun_runner_launch_failed},e);let n=e.details?.snapshotQuality;throw(e.details?.reason===`invalid-viewport`||e.details?.reason===`missing-viewport`||e.details?.reason===`empty-snapshot`)&&n?.state===`sparse`&&(n.reasonCode===`capture-failed`||n.reasonCode===`budget`)?new t(e.code,`The Limrun XCTest runner could not capture the simulator screen`,{...e.details,reason:`limrun_runner_snapshot_unavailable`,hint:`Close and reopen the agent-device session to restart its XCTest runner. If snapshots still fail on this reused simulator, recreate the Limrun instance. Use a screenshot and coordinate actions to inspect its current screen; do not reuse snapshot refs.`},e):e}}function te(n,r,i){let o=async()=>{throw new t(`UNSUPPORTED_OPERATION`,`This host tool is unavailable on a Limrun simulator`)},s=(n={})=>{let a=n.timeoutMs===void 0?void 0:AbortSignal.timeout(n.timeoutMs),o=AbortSignal.any([r,n.requestCancellation===`ignore`?void 0:i,n.signal,a].filter(e=>!!e)),s=(r={})=>a?.aborted?new t(`COMMAND_FAILED`,`Remote simulator operation timed out`,{timeoutMs:n.timeoutMs,...r}):e();if(o.aborted)throw s();return{signal:o,abortError:s}},c=async(e,r={})=>{let i=[...e];i[0]===`--set`&&i.splice(0,2);let o=i.indexOf(n.device.id);o!==-1&&(i[o]=`booted`);let{signal:c,abortError:u}=s(r),d=n.client.simctl(i,r.stdin===void 0?void 0:{stdin:String(r.stdin)}),f=[],p=[],m=e=>f.push(e),h=e=>p.push(e);d.on(`stdout`,m),d.on(`stderr`,h);try{let e=await l(d.wait(),c,()=>(d.stop(),u({cmd:`simctl`,args:i,stdout:Buffer.concat(f).toString(),stderr:Buffer.concat(p).toString()}))),o=e.stdout;if(i[0]===`list`&&(i.includes(`devices`)||i.includes(`-j`)||i.includes(`--json`))&&e.code===0)try{o=O(o,n)}catch(n){throw new t(`COMMAND_FAILED`,`Invalid simulator device inventory`,{cmd:`simctl`,args:i,stdout:o,stderr:e.stderr},n)}if(e.code!==0&&!r.allowFailure)throw new t(`COMMAND_FAILED`,`xcrun exited with code ${e.code}`,{cmd:`simctl`,args:i,...a({exitCode:e.code,stdout:o,stderr:e.stderr})});return{exitCode:e.code,stdout:o,stderr:e.stderr}}finally{d.off(`stdout`,m),d.off(`stderr`,h)}},{simulatorFiles:u,readInfoPlist:d}=m(n,r,i);return{simctl:{run:c},devicectl:{run:o},runCommand:async(e,t,n)=>e===`xcrun`&&t[0]===`simctl`?await c(t.slice(1),n):await o(),whichCommand:async e=>e===`xcrun`,plist:{readJson:async()=>null},simulatorScreenshotBackend:`runner`,simulatorFiles:u,simulatorApps:{readInfoPlist:d,list:async(e,t)=>{let{signal:r,abortError:i}=s(t),a=await l(n.client.listApps(),r,()=>i({cmd:`listapps`}));if(r.aborted)throw i({cmd:`listapps`});return{type:`listed`,apps:a.map(e=>({bundleId:e.bundleId,name:e.name,applicationType:e.installType}))}}}}}function O(e,t){let n=JSON.parse(e);for(let e of Object.values(n.devices??{}))for(let n of e)n.udid===t.client.deviceInfo.udid&&(n.udid=t.device.id);return JSON.stringify(n)}function k(e,n,r){let a=n=>{if((typeof n==`string`?n:n.id)!==e.id)throw new t(`DEVICE_NOT_FOUND`,`Apple lifecycle tools belong to a different Limrun lease`)};return{resolveOpenTarget:async(e,t)=>(a(e),await r.resolveOpenTarget(e,t)),prewarmRunnerCache:async(e,t,r)=>{a(e),await n.prepareCache(r)},prewarmRunnerSession:async(e,t,r,o,s)=>{a(e);try{await n.prewarm(t,r,s)}catch(e){if(o)throw e;i({level:`warn`,phase:`limrun.runner.prewarm_failed`,data:{error:String(e)}})}},notifyRunnerAppRelaunched:async(e,t,r)=>{a(e),await n.resetTarget(r)},stopRunnerSession:async e=>{a(e),await n.stop()},hasLiveRunnerSession:async e=>(a(e),n.isReady()),releaseSpeculativeRunner:async e=>(a(e),await n.releaseSpeculative()),releaseRunnerOnClose:async(e,t)=>{a(e),await n.release(t.retain)},prepareRunner:async(e,t,r)=>(a(e),await n.prepare(e,t,r)),applyRuntimeHints:async(e,t)=>{a(e),await r.applyRuntimeHints(e,t)},clearRuntimeHints:async(e,t)=>{a(e),await r.clearRuntimeHints(e,t)},dismissCloseAlerts:async e=>{a(e)},detachRunnerSessionsForShutdown:async()=>(await n.stop(),[]),finalizeRunnerSessionsForShutdown:async()=>{let t=n.isStarted();return await n.stop(),t?[e.id]:[]}}}async function A(e){if(w(e.bindAddress)!==4||e.bindAddress===`0.0.0.0`)throw D(`limrun_runner_products_invalid`,`Limrun USE_IP must be a concrete IPv4 address`);let t=x.join(e.directory,`runner-${_()}`);await y.mkdir(t);let n=e.appPath;if(!n){if(!/^\d+\.\d+\.\d+$/.test(e.version))throw D(`limrun_runner_products_invalid`,`Nightly and development builds require AGENT_DEVICE_LIMRUN_IOS_RUNNER_APP`,{hint:`Point it at the simulator runner .app built from this agent-device checkout.`},`INVALID_ARGS`);let t=`agent-device-ios-runner-${e.version}`,r=`https://github.com/callstack/agent-device/releases/download/v${e.version}`,i=x.join(e.directory,`manifest.json`);await p({url:`${r}/${t}.manifest.json`,headers:{},destinationPath:i,timeoutMs:12e4,signal:e.signal});let a=JSON.parse(await y.readFile(i,`utf8`));if(a.version!==e.version||a.platform_target!==`iphonesimulator`||typeof a.sha256!=`string`||!/^[a-f0-9]{64}$/.test(a.sha256))throw D(`limrun_runner_products_invalid`,`Invalid iOS runner release manifest`);let o=x.join(e.directory,`runner.tar.gz`);if(await p({url:`${r}/${t}.app.tar.gz`,headers:{},destinationPath:o,timeoutMs:12e4,signal:e.signal}),e.signal.throwIfAborted(),h(`sha256`).update(await y.readFile(o,{signal:e.signal})).digest(`hex`)!==a.sha256)throw D(`limrun_runner_products_invalid`,`iOS runner checksum mismatch`);let c=x.join(e.directory,`extracted`);await s({archivePath:o,outputRoot:c,type:`tgz`,signal:e.signal}),n=x.join(c,`${t}.app`)}if(e.signal.throwIfAborted(),!n.endsWith(`.app`)||!(await y.stat(n).catch(e=>{if(e.code!==`ENOENT`&&e.code!==`ENOTDIR`)throw e}))?.isDirectory())throw D(`limrun_runner_products_invalid`,`The Limrun XCTest runner must be an iOS simulator .app`,{},`INVALID_ARGS`);if(!(await y.readdir(x.join(n,`PlugIns`)).catch(e=>{if([`ENOENT`,`ENOTDIR`].includes(e.code??``))return[];throw e})).includes(`AgentDeviceRunnerUITests.xctest`))throw D(`limrun_runner_products_invalid`,`The app does not contain AgentDeviceRunnerUITests.xctest`,{},`INVALID_ARGS`);if((await y.stat(x.join(n,`Frameworks`,`XCTest.framework`)).catch(()=>null))?.isDirectory())throw D(`limrun_runner_products_invalid`,`The Limrun XCTest runner embeds XCTest.framework from an Xcode older than 27`,{hint:`Build and package the simulator runner with Xcode 27, for example with DEVELOPER_DIR set to an Xcode 27 install.`},`INVALID_ARGS`);return await y.cp(n,x.join(t,`Runner.app`),{recursive:!0}),await j(t,e.bindAddress,e.endpoint),t}async function j(e,t,n){let r=e=>`<string>${c(e)}</string>`,i=d(n,t),a=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"><dict><key>AgentDeviceRunnerUITests</key><dict> <key>BlueprintName</key><string>AgentDeviceRunnerUITests</string> <key>ProductModuleName</key><string>AgentDeviceRunnerUITests</string> <key>TestHostPath</key><string>__TESTROOT__/Runner.app</string> <key>TestBundlePath</key><string>__TESTHOST__/PlugIns/AgentDeviceRunnerUITests.xctest</string> <key>IsUITestBundle</key><true/> <key>UITargetAppPath</key><string>__TESTROOT__/Runner.app</string> ${Object.entries(f).map(([e,t])=>`<key>${e}</key>${r(t)}`).join(``)} <key>OnlyTestIdentifiers</key><array><string>RunnerTests/testCommand</string></array> <key>TestingEnvironmentVariables</key><dict> <key>DYLD_FRAMEWORK_PATH</key><string>__PLATFORMS__/iPhoneSimulator.platform/Developer/Library/Frameworks</string> <key>DYLD_LIBRARY_PATH</key><string>__PLATFORMS__/iPhoneSimulator.platform/Developer/usr/lib</string> </dict> <key>EnvironmentVariables</key><dict>${Object.entries(i).map(([e,t])=>`<key>${e}</key>${r(t)}`).join(``)}</dict> </dict><key>__xctestrun_metadata__</key><dict><key>FormatVersion</key><integer>1</integer></dict></dict></plist>`;await y.writeFile(x.join(e,`Runner.xctestrun`),a,{mode:384})}async function M(e,t,n,r,i){let a=[],o=async t=>{for(let n of await y.readdir(x.join(e,t),{withFileTypes:!0})){r.throwIfAborted();let i=x.posix.join(t,n.name);if(n.isDirectory()){await o(i);continue}if(!n.isFile())throw D(`limrun_runner_products_invalid`,`Runner products must contain regular files`,{},`INVALID_ARGS`);let s=x.join(e,i),c=await y.stat(s),l=h(`sha256`).update(await y.readFile(s,{signal:r})).digest(`hex`);a.push({path:i,size:c.size,mode:c.mode&511,sha256:l})}};await o(``);let s=i?a.filter(e=>i.includes(e.path)):a;for(let e=0;e<2;e++){r.throwIfAborted();let t=await c(e===0?s:a);if(t.ok===!0&&!t.needFull?.length)return;if(!t.needFull?.length||e===1)throw D(`limrun_runner_upload_failed`,`Limrun runner products could not be synchronized`,{needFull:t.needFull})}async function c(i){let o=Buffer.from(JSON.stringify({id:_(),rootName:x.basename(e),install:!1,files:a,payloads:i.map(e=>({kind:`full`,path:e.path,targetSha256:e.sha256,length:e.size}))})),s=Buffer.alloc(4);s.writeUInt32BE(o.length);async function*c(){yield s,yield o;for(let t of i)yield*v(x.join(e,t.path),{signal:r})}let l=T(),u=C(S.from(c()),l,{signal:r}).catch(()=>{});try{let e=await fetch(`${t}/sync`,{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/octet-stream`,"Content-Encoding":`gzip`},body:S.toWeb(l),duplex:`half`,signal:r,redirect:`error`});if(!e.ok)throw await e.body?.cancel(),D(`limrun_runner_upload_failed`,`Limrun runner upload failed (${e.status})`,{status:e.status});return await e.json()}finally{l.destroy(),await u}}}async function N(e,a,s){let{createAppleRunnerRuntime:c,createLaunchedAppleRunnerProvider:d,RUNNER_STARTUP_TIMEOUT_MS:f,mintRunnerToken:p}=await import(`./runner-operations-facade.js`).then(e=>e.t),{withAppleToolProvider:m,hasScopedAppleToolProvider:h,runXcrun:_}=await import(`./tool-provider-facade.js`).then(e=>e.t),{buildSimctlArgsForDevice:v}=await import(`./simctl-facade.js`),S=new AbortController,C=(t,n)=>m(te(e,S.signal,n),()=>ee(t)),w=u({...s},e=>h()?e():C(e)),T=g(2e4,5e4),E=e.apiUrl.replace(/\/$/,``),O=new URL(`targetHttpPort${T}/command`,`${E}/../`).href,N={Authorization:`Bearer ${e.token}`},P,F,I,L=0,R=!1,z=!1,B={port:T,token:p(),http:{url:O,headers:N}},V=await d(e.device,{endpoint:B,launch:Z},a.env),{stop:H,release:U,prepare:W,isStarted:G,releaseSpeculative:K}=V,q=V.hasLiveSession,J=await c({device:e.device,host:a,provider:V}),Y=async t=>{let n=AbortSignal.any([S.signal,...t?[t]:[]]);P=await y.mkdtemp(x.join(b.tmpdir(),`agent-device-limrun-runner-`));let r=e.client.simctl([`getenv`,`booted`,`USE_IP`]),i=AbortSignal.any([n,AbortSignal.timeout(15e3)]),s=await l(r.wait(),i).finally(()=>{i.aborted&&r.stop()});if(s.code!==0)throw D(`limrun_runner_bind_address_missing`,`Limrun did not expose USE_IP`);let c=await A({directory:P,version:o(),appPath:a.env.AGENT_DEVICE_LIMRUN_IOS_RUNNER_APP,bindAddress:s.stdout.trim(),endpoint:B,signal:n});return n.throwIfAborted(),await M(c,E,e.token,AbortSignal.any([n,AbortSignal.timeout(3e5)])),{directory:c,bindAddress:s.stdout.trim()}},X=async e=>{if(S.signal.throwIfAborted(),e?.throwIfAborted(),F&&I?.signal.aborted)return await l(F.catch(()=>{}),e),await X(e);i({level:`info`,phase:`limrun.runner.prepare`,data:{cached:R}}),F||=(I=new AbortController,Y(I.signal).then(e=>(R=!0,e)).catch(async e=>{throw P&&await y.rm(P,{recursive:!0,force:!0}),P=void 0,F=void 0,e}));let t=F;L++;try{return await l(t,e)}finally{L--,e?.aborted&&L===0&&!R&&(I?.abort(e.reason),await t.catch(()=>{}))}};async function Z(a,o,s){let c=new AbortController,u=AbortSignal.any([S.signal,c.signal]),d=()=>c.abort(o.reason);o.addEventListener(`abort`,d,{once:!0});let f,p=!1,m;try{o.throwIfAborted();let{directory:c,bindAddress:d}=await X(u);await j(c,d,a),await M(c,E,e.token,u,[`Runner.xctestrun`]),i({level:`info`,phase:`limrun.runner.launch`,data:{path:`/xctest/run`,port:T}});let h=s?.remainingMs()??12e4,g=Math.max(1,Math.floor(Math.min(9e4,h*.75))),_=AbortSignal.any([u,AbortSignal.timeout(g)]);if(f=await r(async()=>{p=!0;let e=await l(fetch(`${E}/xctest/run`,{method:`POST`,headers:{...N,"Content-Type":`application/json`},body:JSON.stringify({root:x.basename(c),xctestrun:`Runner.xctestrun`}),signal:u,redirect:`error`}),_);if(!e.ok){let t=D(e.status===409?`limrun_xctest_slot_occupied`:`limrun_runner_launch_failed`,`Limrun XCTest launch failed (${e.status})`,{status:e.status,response:await l(e.text(),_).catch(()=>void 0)});throw e.status===409&&(m=t),t}return e},{maxAttempts:90,baseDelayMs:250,maxDelayMs:1e3,shouldRetry:e=>z&&e instanceof t&&e.details?.status===409},{signal:u,deadline:n.fromTimeoutMs(Math.min(6e4,Math.max(0,h/2))),phase:`limrun.runner.wait_for_canceled_run`}),!f.body)throw D(`limrun_runner_launch_failed`,`Limrun XCTest launch returned no stream`);z=!1}catch(e){p&&!(e instanceof t&&typeof e.details?.status==`number`)&&(z=!0);let n=!u.aborted&&e instanceof t&&e.details?.reason===`operation_deadline_expired`;throw c.abort(e),m&&n?m:e}finally{o.removeEventListener(`abort`,d)}let h=f.body.getReader(),g,_=new Promise(e=>{g=e});async function*v(){let e=new TextDecoder;try{for(;;){let{done:t,value:n}=await h.read();if(t)break;yield e.decode(n,{stream:!0})}yield e.decode()}catch(e){if(z=!0,!u.aborted)throw e}finally{g()}}return{exited:_,output:v(),terminate:async()=>{z=!0,c.abort(),await h.cancel().catch(()=>{}),g(),await _}}}let Q=async e=>{try{await J.resetTarget(e)}catch(e){throw await H(),e}},$=k(e.device,{prepareCache:async e=>{await X(e)},prewarm:async(t,n,r)=>{let i={...t,signal:n,speculative:!0};if(r?.healthCheck===!1){await V.ensure(i);return}await W(e.device,{...i,healthTimeoutMs:f})},prepare:(e,t,n)=>J.prepare(t,n),resetTarget:Q,isReady:q,release:U,isStarted:G,stop:H,releaseSpeculative:K},w);return{applicationTools:$,bindDeployment:e=>u({...J.bindDeployment(e)},t=>C(t,e.signal)),facts:J.facts,createInteractor:(e={})=>u(J.createInteractor(e),t=>C(t,e.signal)),bindRunnerOperations:J.bindRunnerOperations,bindApplicationLifecycle:e=>{let t=J.bindApplicationLifecycle({...e,appleApplications:$,ensureReady:async(e,t,n)=>(await _(v(e,[`bootstatus`,e.id,`-b`]),{signal:t,...n?.deadlineAtMs===void 0?{}:{timeoutMs:Math.max(1,n.deadlineAtMs-Date.now())}}),{...e,booted:!0})});return u({...t},t=>C(t,e.signal))},resetTarget:Q,dispose:async()=>{try{await $.finalizeRunnerSessionsForShutdown(),await J.shutdown()}finally{S.abort(),await F?.catch(()=>{}),P&&await y.rm(P,{recursive:!0,force:!0})}}}}export{N as createLimrunIosRunner};