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 • 9.65 kB
import{C as e,v as t}from"./sdk-contracts.js";import{f as n}from"./file.js";import{a as r,i,n as a,r as o}from"./archive.js";import{t as s}from"./byte-limit-stream.js";import{r as c,t as l}from"./install-source-network-transport.js";import{AsyncLocalStorage as u}from"node:async_hooks";import{createWriteStream as ee,promises as d}from"node:fs";import f from"node:os";import p from"node:path";import{Transform as m}from"node:stream";import{pipeline as h}from"node:stream/promises";function g(e,t){return{archivePath:t.archivePath,...t.containingArchivePath?{containingArchivePath:t.containingArchivePath}:{},installablePath:e}}async function _(e,n){n.signal?.throwIfAborted();let r=await d.stat(e).catch(()=>null);if(!r)throw new t(`INVALID_ARGS`,`App source not found: ${e}`);if(n.isInstallablePath(e,r))return g(e,n);if(r.isFile()&&x(e))return await v(e,n);if(r.isDirectory()){let r=await b(e,n.isInstallablePath);if(r.length===1)return g(r[0],n);if(r.length>1)throw new t(`INVALID_ARGS`,`Found multiple ${n.installableLabel} candidates under ${e}: ${r.join(`, `)}`,{matches:r});let i=await b(e,(e,t)=>!!(t.isFile()&&x(e)));if(i.length===1)return await v(i[0],n);if(i.length>1)throw new t(`INVALID_ARGS`,`Found multiple nested archives under ${e}; expected one ${n.installableLabel} source`,{matches:i})}throw new t(`INVALID_ARGS`,`Expected ${n.installableLabel} source, but got ${e}`)}async function v(e,t){let n=await y(e,t.budget,t.archiveDepth+1,t.signal);return t.onArchiveAccepted?.(t.archiveDepth+1),t.registerCleanup(n.cleanup),await _(n.outputPath,{...t,archivePath:t.archivePath??e,containingArchivePath:e,archiveDepth:t.archiveDepth+1})}async function y(e,n,r,i){let s=a(e);if(!s)throw new t(`INVALID_ARGS`,`Unsupported archive: ${e}`);let c=await d.mkdtemp(p.join(f.tmpdir(),`agent-device-archive-`)),l=p.join(c,`extracted`);try{return await o({archivePath:e,outputRoot:l,type:s,budget:n,depth:r,signal:i}),{outputPath:l,cleanup:async()=>await d.rm(c,{recursive:!0,force:!0})}}catch(e){throw await d.rm(c,{recursive:!0,force:!0}),e}}async function b(e,t){let n=[],r=[{path:e,depth:0}];for(;r.length>0;){let e=r.shift();if(!e)continue;let i=await d.readdir(e.path,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i){if(a.name===`__MACOSX`||a.name.startsWith(`._`))continue;let i=p.join(e.path,a.name);t(i,a)?n.push(i):a.isDirectory()&&e.depth<5&&r.push({path:i,depth:e.depth+1})}}return[...new Set(n)]}function x(e){return a(e)!==void 0}const S=new u;async function C(e){return await S.run({budget:new i,depth:0},e)}function w(){return S.getStore()?.budget}function T(){return S.getStore()?.depth??0}function E(e){let t=S.getStore();t&&(t.depth=Math.max(t.depth,e))}async function D(e){let{createTransferPhaseWatchdog:t,isTransferPhaseTimeoutError:n,TRANSFER_BODY_INACTIVITY_TIMEOUT_MS:r,TRANSFER_CONNECT_TIMEOUT_MS:i,TRANSFER_RESPONSE_HEADER_TIMEOUT_MS:a}=await import(`./transport.js`).then(e=>e.t);return{watchdog:t(e),connectTimeoutMs:i,responseHeaderTimeoutMs:a,bodyInactivityTimeoutMs:r,isPhaseTimeout:n}}const O=new Set([301,302,303,307,308]),k=/^[A-Z][A-Z0-9_]{0,63}$/,A=new Set([`accept-encoding`,`connection`,`content-length`,`host`,`keep-alive`,`proxy-connection`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`]);async function j(e){let t=await D(e.signal),{watchdog:n}=t;try{let r=U(e.url),i=z(R(e.headers));for(let a=0;;a+=1){n.arm(`connect`,t.connectTimeoutMs);let o=await M(r,i,t,e.environment);try{let s=P(o,r,a);if(s){s.origin!==r.origin&&(i=B(i)),r=s;continue}return F(o),n.arm(`response-body`,t.bodyInactivityTimeoutMs),await I(e.tempDir,r,o,t)}finally{await o.close()}}}finally{n.dispose()}}async function M(e,n,r,i){let{watchdog:a}=r;try{let t=await c(e,a.signal);return await l({url:e,approvedAddress:t.address,family:t.family,headers:{...n,"accept-encoding":`identity`},signal:a.signal,environment:i,onConnected:()=>a.arm(`response-headers`,r.responseHeaderTimeoutMs)})}catch(e){if(r.isPhaseTimeout(e))throw e;let n=a.signal.reason;if(n instanceof t&&r.isPhaseTimeout(n))throw new t(n.code,n.message,n.details,e);if(e instanceof t)throw e;let i=N(e);throw new t(`COMMAND_FAILED`,i?`The daemon failed to fetch the app source (network error code: ${i})`:`The daemon failed to fetch the app source`,i?{networkErrorCode:i}:void 0,e)}}function N(e){let t=e?.code;return typeof t==`string`&&k.test(t)?t:void 0}function P(e,n,r){if(!O.has(e.statusCode))return;e.body.resume?.();let i=H(e.headers,`location`);if(!i||r>=5)throw new t(`COMMAND_FAILED`,`App source redirect limit was exceeded`,{status:e.statusCode});let a=new URL(i,n);if(n.protocol===`https:`&&a.protocol!==`https:`)throw new t(`COMMAND_FAILED`,`App source redirect downgraded HTTPS`);return a}function F(e){if(!(e.statusCode>=200&&e.statusCode<300))throw new t(`COMMAND_FAILED`,`Failed to download app source: ${e.statusCode}`,{status:e.statusCode})}async function I(e,n,i,a){let{watchdog:o}=a,c=H(i.headers,`content-encoding`);if(c&&c.toLowerCase()!==`identity`)throw new t(`COMMAND_FAILED`,`App source response used unsupported content encoding`);L(H(i.headers,`content-length`));let l=p.join(e,V(i,n)),u=s({maxBytes:r,createLimitError:()=>new t(`COMMAND_FAILED`,`App source exceeds maximum size of ${r} bytes`,{reason:`ARTIFACT_BYTE_LIMIT`})}),f=new m({transform(e,t,n){o.touchBody(),n(null,e)}});try{return await h(i.body,f,u,ee(l,{flags:`wx`}),{signal:o.signal}),l}catch(e){throw await d.rm(l,{force:!0}).catch(()=>{}),a.isPhaseTimeout(e)?e:a.isPhaseTimeout(o.signal.reason)?o.signal.reason:e}}function L(e){if(e===null)return;if(!/^\d+$/.test(e))throw new t(`COMMAND_FAILED`,`App source response had invalid content-length`);let n=Number(e);if(!Number.isSafeInteger(n)||n>2147483648)throw new t(`COMMAND_FAILED`,`App source response exceeded the byte limit`,{reason:`ARTIFACT_BYTE_LIMIT`})}function R(e){let t=new Set(Object.entries(e??{}).filter(([e])=>e.toLowerCase()===`connection`).flatMap(([,e])=>e.split(`,`).map(e=>e.trim().toLowerCase())));return Object.fromEntries(Object.entries(e??{}).filter(([e])=>{let n=e.toLowerCase();return!A.has(n)&&!t.has(n)}))}function z(e){return Object.keys(e).some(e=>e.toLowerCase()===`user-agent`)?e:{...e,"user-agent":`agent-device`}}function B(e){return Object.fromEntries(Object.entries(e).filter(([e])=>[`accept`,`user-agent`].includes(e.toLowerCase())))}function V(e,t){let n=(H(e.headers,`content-disposition`)?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i))?.[1]?.trim()||p.basename(t.pathname)||`downloaded-artifact.bin`;return p.basename(n)}function H(e,t){let n=e[t];return Array.isArray(n)?n[0]??null:n??null}function U(e){let n;try{n=new URL(e)}catch{throw W()}if(n.username||n.password)throw new t(`INVALID_ARGS`,`Source URL credentials are not allowed`);return n}function W(){return new t(`INVALID_ARGS`,`Invalid source URL`)}const G=Object.freeze([`.zip`,`.tar`,`.tar.gz`,`.tgz`]),K=6e5;function q(e,n){return new t(`COMMAND_FAILED`,`App source materialization timed out after ${e}ms`,{reason:`source_materialization_deadline_exceeded`,transferPhase:`materialization`,timeoutMs:e},n)}function J(e,t,n){if(n===void 0)return{signal:e,timeoutMs:t,isDeadlineAbort:t=>e.aborted&&t===e.reason,deadlineError:e=>q(t,e)};let r=Math.min(t,Math.max(0,n-Date.now()));if(r<=0){let t=new AbortController,n=q(0);return t.abort(n),{signal:AbortSignal.any([e,t.signal]),timeoutMs:0,isDeadlineAbort:e=>e===t.signal.reason,deadlineError:e=>q(0,e)}}let i=AbortSignal.timeout(r);return{signal:AbortSignal.any([e,i]),timeoutMs:r,isDeadlineAbort:e=>i.aborted&&e===i.reason,deadlineError:e=>q(r,e)}}async function Y(e){let t=J(AbortSignal.timeout(K),K,e.materializationDeadlineMs),n=e.signal?AbortSignal.any([e.signal,t.signal]):t.signal,r=performance.now()+t.timeoutMs,a=[],o=e=>{a.push(e)};try{n.throwIfAborted();let s=await _(await Z(e.source,{signal:n,environment:e.environment,registerCleanup:o}),{archivePath:void 0,isInstallablePath:e.isInstallablePath,installableLabel:e.installableLabel,registerCleanup:o,budget:w()??new i,archiveDepth:0,onArchiveAccepted:E,signal:n});if(n.throwIfAborted(),performance.now()>=r)throw t.deadlineError();return{archivePath:s.archivePath,...s.containingArchivePath?{containingArchivePath:s.containingArchivePath}:{},installablePath:s.installablePath,cleanup:async()=>{await $(a)}}}catch(e){let r=await Q(e,n,t);throw await $(a),r}}function X(e,t){return n(e,{env:t})}async function Z(e,t){if(e.kind===`path`)return X(e.path,t.environment);let n=await d.mkdtemp(p.join(f.tmpdir(),`agent-device-source-`));return t.registerCleanup(async()=>{await d.rm(n,{recursive:!0,force:!0})}),t.signal.throwIfAborted(),await j({tempDir:n,url:e.url,headers:e.headers,signal:t.signal,environment:t.environment})}async function Q(t,n,r){let{isTransferPhaseTimeoutError:i}=await import(`./transport.js`).then(e=>e.t);if(i(t)||!n.aborted)return t;let a=n.reason;return t===a||t instanceof Error&&t.cause===a?r.isDeadlineAbort(a)?r.deadlineError(t):e(void 0,t):t}async function te(e){await c(e)}function ne(e){let t=e instanceof URL?e:URL.parse(e);if(!t)throw W();let n=t.hostname.toLowerCase();if(!n)return!1;let r=t.pathname;return re(n,r)||ie(n,r)}function re(e,t){return e===`api.github.com`?/^\/repos\/[^/]+\/[^/]+\/actions\/artifacts\/\d+\/zip$/i.test(t):e===`github.com`&&/^\/[^/]+\/[^/]+\/(?:actions\/runs\/\d+\/artifacts\/\d+|suites\/\d+\/artifacts\/\d+)$/i.test(t)}function ie(e,t){return e!==`expo.dev`&&!e.endsWith(`.expo.dev`)?!1:/^\/(?:artifacts\/eas\/|accounts\/[^/]+\/projects\/[^/]+\/builds\/)/i.test(t)}async function $(e){for(let t of[...e].reverse())await t()}export{w as a,C as c,te as i,ne as n,T as o,Y as r,E as s,G as t};