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 • 13.2 kB
JavaScript
import{S as e,v as t}from"./sdk-contracts.js";import{I as n,O as r,R as i,_ as a,at as o,ct as s,g as c,q as l}from"./sdk-io.js";import{h as u}from"./file.js";import{t as d}from"./base-url.js";import{t as f}from"./bundle-url.js";import"./command.js";import"./retry.js";import{n as p,r as m}from"./project-runtime.js";import{ensureMetroCompanion as h}from"./client-metro-companion.js";import{n as g,r as _,t as v}from"./metro-reload-endpoints.js";import y from"node:fs";import b from"node:path";function x(e){return typeof e==`string`&&e.trim()?d(e.trim()):``}function S(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function C(e,t,n){return u(e,{env:t,cwd:n})}function w(e){try{return y.accessSync(e,y.constants.F_OK),!0}catch{return!1}}function T(e){try{return y.statSync(e).isDirectory()}catch{return!1}}function E(e){let n=b.join(e,`package.json`),r=m(e);if(!r)throw new t(`INVALID_ARGS`,`package.json not found at ${n}`);return r}const D=[{file:`pnpm-lock.yaml`,command:`pnpm`},{file:`yarn.lock`,command:`yarn`},{file:`bun.lock`,command:`bun`},{file:`bun.lockb`,command:`bun`},{file:`package-lock.json`,command:`npm`}];function O(e){let t=e;for(;;){for(let{file:e,command:n}of D)if(w(b.join(t,e)))return{command:n,installArgs:[`install`]};if(w(b.join(t,`.git`)))return null;let e=b.dirname(t);if(e===t)return null;t=e}}function k(e){return O(e)??{command:`npm`,installArgs:[`install`]}}function A(e,t){if(t!==`auto`)return t;let n=p(e);return n===`expo`||n===`repack`?n:`react-native`}function j(e,t){return typeof{...e.dependencies??{},...e.devDependencies??{}}[t]==`string`}function M(e,t){return[`js`,`mjs`,`cjs`,`ts`,`mts`,`cts`].some(n=>w(b.join(e,`${t}.config.${n}`)))}function N(e,t){return M(e,`rspack`)?`rspack`:M(e,`webpack`)?`webpack`:j(t,`@rspack/core`)?`rspack`:j(t,`webpack`)?`webpack`:`rspack`}function P(e,t,n){if(e==null||e===``)return t;let r=Number.parseInt(String(e),10);return Number.isInteger(r)?Math.max(r,n):t}function F(e){return e===`expo`?v:`index.bundle`}function I(e,t,n){return{platform:t,bundleUrl:f(e,t,F(n))}}function L(e,t){return{platform:t,metroHost:S(e?.metro_host),metroPort:e?.metro_port,bundleUrl:S(e?.metro_bundle_url),launchUrl:S(e?.launch_url)}}function R(e,t){if(T(b.join(e,`node_modules`)))return{installed:!1};let n=k(e);try{s(n.command,n.installArgs,{cwd:e,env:t})}catch(e){throw z(e,n)}return{installed:!0,packageManager:n.command}}function z(n,r){let i=e(n),a=`Dependency install failed using detected package manager "${r.command}". If dependencies are already installed (for example via a monorepo root install), pass --no-install-deps to skip this step, or install manually with "${r.command} ${r.installArgs.join(` `)}" from the project root.`;return new t(i.code,i.message,{...i.details??{},hint:a,packageManager:r.command},i)}async function B(e){await l(e)}async function V(e,n,r={}){try{let t=await fetch(e,{headers:r,signal:AbortSignal.timeout(n)});return{ok:t.ok,status:t.status,body:await t.text()}}catch(r){throw r instanceof Error&&r.name===`TimeoutError`?new t(`COMMAND_FAILED`,`Timed out fetching ${e} after ${n}ms`):r}}async function H(e,t){try{let n=await V(e,t);return n.ok&&n.body.includes(`packager-status:running`)}catch{return!1}}function U(e,t,n,r){return e===`expo`?{command:`npx`,installArgs:[`expo`,`start`,`--host`,`lan`,`--port`,String(n)]}:e===`repack`?{command:`npx`,installArgs:[`react-native`,t===`webpack`?`webpack-start`:`rspack-start`,`--host`,r,`--port`,String(n)]}:{command:`npx`,installArgs:[`react-native`,`start`,`--host`,r,`--port`,String(n)]}}function W(e,r,i,a,s,c,l){let u=U(r,i,a,s);y.mkdirSync(b.dirname(c),{recursive:!0});let d=y.openSync(c,`a`),f=0;try{f=o(u.command,u.installArgs,{cwd:e,env:l,stdio:[`ignore`,d,d]})}finally{y.closeSync(d)}if(!Number.isInteger(f)||f<=0)throw new t(`COMMAND_FAILED`,`Failed to start React Native dev server. Expected a detached child PID.`);return{pid:f,startTime:n(f)??void 0}}function G(e,n,r,i){let o=`React Native dev server did not become ready at ${e} within ${n.startupTimeoutMs}ms. Check ${n.logPath}.`;if(`throws`in i)return new t(`COMMAND_FAILED`,o,{logPath:n.logPath},i.throws);if(i.status===`stopped`)return new t(`COMMAND_FAILED`,o,{logPath:n.logPath});let s=i.reason===`identity-unverified`?a(r,`the process this run started`):`pid ${r} is still running${i.reason===`signal-failed`?` and refused ${i.signal} (${i.errno})`:``}`;return new t(`COMMAND_FAILED`,`${o} Dev server ${s}; stop it before retrying.`,{logPath:n.logPath,...c(i,r)})}function K(e,t){return{Authorization:`Bearer ${t}`,"Content-Type":`application/json`,...e.includes(`ngrok`)?{"ngrok-skip-browser-warning":`1`}:{}}}function q(e,n){let r=new t(`COMMAND_FAILED`,e);return r.retryable=n,r}function J(e,t){return!!(e>=500||e===408||e===425||e===429||JSON.stringify(t).includes(`Metro companion is not connected`))}function Y(e){return!!(e&&typeof e==`object`&&`retryable`in e&&e.retryable===!0)}async function X(e){let t;try{t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:`POST`,headers:K(e.baseUrl,e.bearerToken),body:JSON.stringify({...e.scope,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){throw t instanceof Error&&t.name===`TimeoutError`?q(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0):q(t instanceof Error?t.message:String(t),!0)}let n=ee(await t.text(),t.status,e.baseUrl);if(!t.ok)throw q(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(n)}`,J(t.status,n));return Q(n)}function ee(e,t,n){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Expected a JSON object`);return t}catch(r){let i=e.slice(0,200);throw q(`/api/metro/bridge returned invalid JSON (${t}) from ${n}: ${r instanceof Error?r.message:String(r)}. body=${JSON.stringify(i)}`,J(t,e))}}function Z(e){return{enabled:e.enabled,baseUrl:e.base_url,statusUrl:e.status_url??``,bundleUrl:e.bundle_url??``,iosRuntime:L(e.ios_runtime,`ios`),androidRuntime:L(e.android_runtime,`android`),upstream:{bundleUrl:e.upstream.bundle_url??``,host:e.upstream.host??``,port:e.upstream.port??0,statusUrl:e.upstream.status_url??``},probe:{reachable:e.probe.reachable,statusCode:e.probe.status_code,latencyMs:e.probe.latency_ms,detail:e.probe.detail}}}function Q(e){let t=e.data??e;if(!t||typeof t!=`object`||Array.isArray(t))throw q(`/api/metro/bridge returned malformed descriptor: Expected a JSON object.`,!1);try{return Z(t)}catch(e){throw q(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function $(e,t,n,r,i){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&a.push(`bridgeError=${t}`),n?.probe.reachable===!1&&a.push(`bridgeProbe=${n.probe.detail||`unreachable (status ${n.probe.statusCode||0})`}`),r&&r!==t&&a.push(`initialBridgeError=${r}`),i&&a.push(`metroCompanionLog=${i}`),a.join(` `)}function te(e,n){if(!n?.iosRuntime.bundleUrl)throw new t(`COMMAND_FAILED`,$(e,`bridge descriptor is missing ios_runtime.metro_bundle_url`,n))}function ne(e,n,r){let i=n||S(r.AGENT_DEVICE_METRO_BEARER_TOKEN)||``,a=i||e&&S(r.AGENT_DEVICE_DAEMON_AUTH_TOKEN)||``;if(e&&!a)throw new t(`INVALID_ARGS`,`metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_METRO_BEARER_TOKEN or AGENT_DEVICE_DAEMON_AUTH_TOKEN.`);if(!e&&i)throw new t(`INVALID_ARGS`,`metro prepare requires --proxy-base-url when proxy auth is provided.`);return{proxyEnabled:!!(e&&a),proxyBaseUrl:e,proxyBearerToken:a}}function re(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new t(`INVALID_ARGS`,`metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.`);return e}function ie(e,n){if(!(e||n))throw new t(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`)}function ae(e,t,n){return e.runtimeFilePath?C(e.runtimeFilePath,t,n):null}function oe(e,t,n,r){return C(e.logPath??b.join(r,`.agent-device`,`metro.log`),t,n)}function se(e,t){let n=e.env??t.env,r=t.cwd,i=C(e.projectRoot??r,n,r),a=e.kind??`auto`,o=null,s;a===`auto`?(o=E(i),s=A(o,a)):s=a;let c=null;s===`repack`&&(o??=E(i),c=N(i,o));let l=x(e.publicBaseUrl),u=x(e.proxyBaseUrl);ie(l,u);let{proxyEnabled:d,proxyBaseUrl:f,proxyBearerToken:p}=ne(u,S(e.proxyBearerToken)??``,n);return{env:n,cwd:r,projectRoot:i,kind:s,repackBundler:c,metroPort:g(e.metroPort??8081,8081),listenHost:S(e.listenHost)??`0.0.0.0`,statusHost:S(e.statusHost)??`127.0.0.1`,publicBaseUrl:l,proxyBaseUrl:f,proxyBearerToken:p,bridgeScope:d?re(e.bridgeScope):null,startupTimeoutMs:P(e.startupTimeoutMs,18e4,3e4),probeTimeoutMs:P(e.probeTimeoutMs,1e4,1e3),reuseExisting:e.reuseExisting??!0,installProjectDeps:e.installDependenciesIfNeeded??!0,runtimeFilePath:ae(e,n,r),logPath:oe(e,n,r,i)}}async function ce(e,t,n){let r=Date.now()+t;for(;Date.now()<r;){let t=r-Date.now();if(await H(e,Math.min(n,Math.max(t,1))))return!0;let i=Math.min(500,Math.max(r-Date.now(),0));i>0&&await B(i)}return!1}async function le(e){let n=Date.now()+e.startupTimeoutMs,r=null,i=null;for(;Date.now()<n;){try{let t=await X({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(t.probe.reachable!==!1)return t;r=t,i=null}catch(n){if(i=n instanceof Error?n.message:String(n),!Y(n))throw new t(`COMMAND_FAILED`,$(e.baseUrl,i,r,e.initialBridgeError,e.companionLogPath),void 0,n)}let a=Math.min(1e3,Math.max(n-Date.now(),0));a>0&&await B(a)}throw new t(`COMMAND_FAILED`,$(e.baseUrl,i,r,e.initialBridgeError,e.companionLogPath))}async function ue(e){let t=`http://${e.statusHost}:${e.metroPort}/status`;if(e.reuseExisting&&await H(t,e.probeTimeoutMs))return{started:!1,reused:!0,pid:0,statusUrl:t};let n=W(e.projectRoot,e.kind,e.repackBundler,e.metroPort,e.listenHost,e.logPath,e.env);if(await ce(t,e.startupTimeoutMs,e.probeTimeoutMs))return{started:!0,reused:!1,pid:n.pid,statusUrl:t};let r=await i({pid:n.pid,identity:{startTime:n.startTime}},{termTimeoutMs:1e3,killTimeoutMs:1e3}).catch(e=>({throws:e}));throw G(t,e,n.pid,r)}async function de(e,t){let n=t.bridgeScope;if(!n)return null;let r=null,i=null;try{r=await X({baseUrl:t.proxyBaseUrl,bearerToken:t.proxyBearerToken,scope:n,timeoutMs:t.probeTimeoutMs})}catch(e){if(!Y(e))throw e;i=e instanceof Error?e.message:String(e)}return(!r||r.probe.reachable===!1)&&(r=await fe(e,t,n,r,i)),te(t.proxyBaseUrl,r),r}async function fe(e,n,i,a,o){let s;try{s=(await h({projectRoot:n.projectRoot,serverBaseUrl:n.proxyBaseUrl,bearerToken:n.proxyBearerToken,bridgeScope:i,localBaseUrl:`http://${n.statusHost}:${n.metroPort}`,launchUrl:S(e.launchUrl),profileKey:S(e.companionProfileKey),consumerKey:S(e.companionConsumerKey),env:n.env,cwd:n.cwd})).logPath}catch(e){throw new t(`COMMAND_FAILED`,$(n.proxyBaseUrl,e instanceof Error?e.message:String(e),a,o),e instanceof t?r(e.details):void 0,e)}try{return await le({baseUrl:n.proxyBaseUrl,bearerToken:n.proxyBearerToken,scope:i,probeTimeoutMs:n.probeTimeoutMs,startupTimeoutMs:n.startupTimeoutMs,initialBridgeError:o,companionLogPath:s})}catch(e){throw e instanceof Error?e:Error(String(e))}}function pe(e,t){return{baseIosRuntime:e?I(e,`ios`,t):{platform:`ios`},baseAndroidRuntime:e?I(e,`android`,t):{platform:`android`}}}function me(e,t){e&&(y.mkdirSync(b.dirname(e),{recursive:!0}),y.writeFileSync(e,JSON.stringify(t,null,2)))}async function he(e,t){let n=se(e,t),r=n.installProjectDeps?R(n.projectRoot,n.env):{installed:!1},i=await ue(n),{baseIosRuntime:a,baseAndroidRuntime:o}=pe(n.publicBaseUrl,n.kind),s=await de(e,n),c=s?.iosRuntime??a,l=s?.androidRuntime??o,u={projectRoot:n.projectRoot,kind:n.kind,dependenciesInstalled:r.installed,packageManager:r.packageManager??null,started:i.started,reused:i.reused,pid:i.pid,logPath:n.logPath,statusUrl:i.statusUrl,runtimeFilePath:n.runtimeFilePath,iosRuntime:c,androidRuntime:l,bridge:s};return me(n.runtimeFilePath,u),u}function ge(e){let t=e.trimStart().slice(0,15).toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}async function _e(e,n){await new Promise((r,i)=>{let a=new WebSocket(e),o=e=>{clearTimeout(s);try{a.close()}catch{}i(new t(`COMMAND_FAILED`,e))},s=setTimeout(()=>{o(`Timed out broadcasting reload to ${e} after ${n}ms`)},n);a.addEventListener(`open`,()=>{a.send(JSON.stringify({version:2,method:`reload`}));let e=()=>{if(a.bufferedAmount===0){clearTimeout(s),a.close(),r();return}setTimeout(e,20)};e()}),a.addEventListener(`error`,()=>{o(`Failed to reach the dev server message socket at ${e}`)})})}async function ve(e={}){let n=P(e.timeoutMs,1e4,1e3),{reloadUrl:r,messageSocketUrl:i}=_(e),a=await V(r,n);if(a.ok&&!ge(a.body))return{reloaded:!0,reloadUrl:r,status:a.status,body:a.body,transport:`http`};try{await _e(i,n)}catch(e){throw new t(`COMMAND_FAILED`,`React Native dev server reload failed (${a.status}).`,{reloadUrl:r,status:a.status,body:a.body.slice(0,500),messageSocketUrl:i,hint:`Verify Metro or Re.Pack is running and the target React Native app is connected to this dev server instance.`},e instanceof Error?e:void 0)}return{reloaded:!0,reloadUrl:i,status:a.status,body:``,transport:`message-socket`}}export{he as prepareMetroRuntime,ve as reloadMetro};