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.

2 lines • 13.1 kB
import{B as e,v as t}from"./sdk-contracts.js";import{S as n,a as r,c as i,d as a,h as o,i as s,l as c,m as l,n as u,o as d,r as f,s as ee,t as te,u as p,x as m,y as ne}from"./daemon-http.js";import{p as h}from"./transport.js";import{r as g}from"./src4.js";import{n as re,t as ie}from"./color.js";import{n as ae}from"./shared.js";import{randomBytes as oe,randomUUID as _}from"node:crypto";import se from"node:http";function ce(e){let t=ue(e);if(!t)return!1;let n=y(t.meta);return de(n)?!1:v(t.source)||v(n?.installSource)}function le(n){let r=new t(`INVALID_ARGS`,`Invalid params: an install source of kind "path" names a file on the daemon host and is not accepted through the proxy`,{hint:`Upload the artifact, or use a "url" or "github-actions-artifact" source.`});return Response.json({jsonrpc:`2.0`,id:n,error:{code:-32602,message:r.message,data:e(r)}},{status:400})}function ue(e){if(e)try{return y(y(JSON.parse(e))?.params)}catch{return}}function de(e){let t=e?.uploadedArtifactId;return typeof t==`string`&&t.trim().length>0}function v(e){return y(e)?.kind===`path`}function y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}const fe=Object.keys(p(`client`)),b=i,x=`${te}/`,S=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,d],C=[`content-type`,`content-disposition`,`x-request-id`,f],w=[`range`,`x-upload-offset`],T=[`content-length`];function E(e){let t=_e(e),n=_();return{instanceId:n,handle:async e=>{try{return await k(e,t,n)}catch(t){return Le(t,e)}}}}function D(e){return se.createServer(O(E(e)))}function O(e){return(t,n)=>{import(`./node-http.js`).then(({serveProxyRequest:r})=>r(e,t,n)).catch(e=>{n.destroyed||n.destroy(e instanceof Error?e:void 0)})}}async function k(e,t,n){let r=U(e.url);if(e.method===`GET`&&r===`/health`)return await I(e,t,n);if(!ye(r,e.method))return new Response(new TextEncoder().encode(`Not found`),{status:404});if(r!==`/rpc`)return await A(e,r,t,n);let i;try{i=await we(e,t.maxRpcBodyBytes,`Proxy request body is too large.`)}catch(e){return Z(null,e)}let a=Ie(i);if(a)return a;try{return await A(e,r,t,n,i)}catch(e){return Z(Y(i),e)}}async function A(e,t,n,r,i){let a=await j(e,n,i);return a?a.tenantId&&!N(t,a.tenantId)?Response.json({ok:!1,error:`Session is outside this tenant`,code:`UNAUTHORIZED`},{status:401}):a.tenantId&&t===`/rpc`&&!F(i)?Fe(Y(i)):Me(e,t,Y(i),r)||(ce(i)?le(Y(i)):await R({request:e,route:t,options:n,rpcBody:i,caller:a})):Pe(t,Y(i))}async function j(e,r,i){if(!r.authenticate)return Te(e,r.clientToken??``,i)?{uploadHeaders:p(r.clientToken)}:null;let a=await r.authenticate(new Request(e.url,{method:e.method,headers:e.headers,signal:e.signal,...i===void 0?{}:{body:i}}));if(!a)return null;let o=n(typeof a.tenantId==`string`?a.tenantId:void 0);if(!o)throw new t(`COMMAND_FAILED`,`Proxy authenticate returned an invalid tenantId`,{hint:`Return a tenantId of 1-128 letters, digits, ".", "_" or "-".`});return{tenantId:o,uploadHeaders:a.uploadHeaders??M(e)}}function M(e){let t={};for(let n of fe){let r=e.headers.get(n);r!==null&&(t[n]=r)}return t}function N(e,t){if(!W(e))return!0;try{return ne(t,decodeURIComponent(e.split(`/`)[2]??``))}catch{return!1}}const P=new Set([`agent_device.command`,`agent-device.command`,`agent_device.lease.allocate`,`agent-device.lease.allocate`,`agent_device.lease.heartbeat`,`agent-device.lease.heartbeat`,`agent_device.lease.release`,`agent-device.lease.release`]);function F(e){let t=Ae(e);return t!==void 0&&P.has(t)}async function I(e,t,n){let[r,{readVersion:i},{readHostCpuArch:a}]=await Promise.all([L(e,t),import(`./version.js`).then(e=>e.t),import(`./sdk-io.js`).then(e=>e.r)]);return Response.json(c(`agent-device-proxy`,i(),{upstream:r,instanceId:n,hostArch:await a()}))}async function L(e,t){let n=await t.upstreamFetch(new Request(l(t.upstreamBaseUrl,`health`),{method:`GET`,headers:q(new Headers,t.upstreamToken,`/health`),signal:AbortSignal.any([e.signal,AbortSignal.timeout(5e3)])})),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function R(e){let{request:t,route:n,options:r,rpcBody:i,caller:a}=e,o=Ce(t,n,i,r.upstreamToken,a.tenantId),s=await r.upstreamTransport(n,new Request(xe(r.upstreamBaseUrl,n,t.url),{method:t.method,headers:q(t.headers,r.upstreamToken,n,a.tenantId),signal:z(t,r),...o?{body:o,duplex:`half`}:{}})),c=B(s,t,n);return K(n)?await pe({request:t,upstreamResponse:s,headers:c,uploadHeaders:a.uploadHeaders,publicOrigin:r.publicOrigin}):new Response(s.body,{status:s.status,headers:c})}function z(e,t){return t.upstreamTimeoutMs===void 0?e.signal:AbortSignal.any([e.signal,AbortSignal.timeout(t.upstreamTimeoutMs)])}function B(e,t,n){let r=new Headers;for(let t of[...C,...V(n)]){let n=e.headers.get(t);n&&r.set(t,n)}return r.has(`x-request-id`)||r.set(`x-request-id`,je(t)),r}function V(e){return e.startsWith(`/upload/direct/`)?w:e.startsWith(`/artifacts/`)?T:[]}async function pe(e){let{request:t,upstreamResponse:n,headers:r,uploadHeaders:i,publicOrigin:a}=e,o=await n.text();return r.set(`content-type`,n.headers.get(`content-type`)??`application/json`),new Response(me(o,t,i,a,n.ok),{status:n.status,headers:r})}function me(e,t,n,r,i){let a;try{a=JSON.parse(e)}catch{if(!i)return e;throw Error(`Invalid upstream upload ticket`)}if(!i&&(!a||typeof a!=`object`||!(`upload`in a)))return e;if(!a||typeof a!=`object`)throw Error(`Invalid upstream upload ticket`);let o=a;if(typeof o.uploadId!=`string`||!o.uploadId||o.uploadId.trim()!==o.uploadId||o.uploadId.includes(`/`)||!o.upload||typeof o.upload!=`object`)throw Error(`Invalid upstream upload ticket`);let s=typeof o.upload.url==`string`?ge(o.upload.url,o.uploadId,t,r):null;if(!s)throw Error(`Invalid upstream upload ticket`);return JSON.stringify({...a,upload:{...o.upload,url:s,headers:{...he(o.upload.headers),...n}}})}function he(e){if(!e||typeof e!=`object`)return{};for(let[t,n]of Object.entries(e))if(t.toLowerCase()===`content-type`&&typeof n==`string`)return{"content-type":n};return{}}function ge(e,t,n,r){let i;try{i=new URL(e)}catch{return null}if(![`http:`,`https:`].includes(i.protocol)||i.username||i.password||i.hash||i.pathname!==`/upload/direct/${t}`)return null;let a=new URL(n.url),o=a.pathname.lastIndexOf(`/upload/preflight`),s=o>=0?a.pathname.slice(0,o):``,c=new URL(r??a.origin);return c.pathname=`${s}${i.pathname}`,c.search=i.search,c.toString()}function _e(e){let t=ve(e.upstreamBaseUrl,`upstreamBaseUrl`),n=H(e.upstreamToken,`upstreamToken`),r=e.authenticate?void 0:H(e.clientToken??``,`clientToken`),i=e.upstreamFetch??(e=>fetch(e)),a=e.upstreamFetch;return{upstreamBaseUrl:t,publicOrigin:e.publicOrigin===void 0?void 0:m(e.publicOrigin),upstreamToken:n,clientToken:r,authenticate:e.authenticate,maxRpcBodyBytes:e.maxRpcBodyBytes??b,upstreamTimeoutMs:e.upstreamTimeoutMs,upstreamFetch:i,upstreamTransport:async(e,t)=>{if(!G(e,t.method))return i(t);let{createNodeTransferFetch:n,settleUpstreamFetch:r}=await import(`./transfer-transport.js`);return a?r(a,t):n()(t)}}}function ve(e,n){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`);return t.toString().replace(/\/+$/,``)}catch(r){throw new t(`INVALID_ARGS`,`Invalid ${n}`,{[n]:e},r)}}function H(e,n){let r=e.trim();if(!r)throw new t(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function U(e){let t=new URL(e).pathname;return t===`/agent-device`?`/`:t.startsWith(x)?`/${t.slice(x.length)}`:t}function ye(e,t){return e===`/rpc`?t===`POST`:G(e,t)?!0:W(e)?t===`GET`:!1}function W(e){let t=e.split(`/`);return t.length===6&&t[1]===`sessions`&&t[3]===`requests`&&t[5]===`diagnostics`&&t[2]!==``&&t[4]!==``}function G(e,t){return be(e,t)||t===`GET`&&(e===`/artifacts`||e.startsWith(`/artifacts/`))}function be(e,t){return e===`/upload`||K(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function K(e){return e===`/upload/preflight`}function xe(e,t,n){let r=new URL(l(e,t));return r.search=new URL(n).search,r}function Se(e){let t=e.get(ee);return t===null?{}:{[u]:t}}function q(e,t,n,i){let a=new Headers;for(let t of S){let n=e.get(t);n?.trim()&&a.set(t,n)}if(i&&a.set(d,i),n===`/rpc`&&!a.has(`content-type`)&&a.set(`content-type`,`application/json`),n===`/rpc`){a.set(s,r);for(let[t,n]of Object.entries(Se(e)))a.set(t,n)}for(let[e,n]of Object.entries(p(t)))a.set(e,n);return a}function Ce(e,t,n,r,i){return e.method===`GET`||e.method===`HEAD`?null:t===`/rpc`?De(n??``,r,i):e.body}async function we(e,n,r){if(!e.body)return``;let i=e.body.getReader(),a=[],o=0;for(;;){let{done:e,value:s}=await i.read();if(e)break;if(o+=s.byteLength,o>n)throw await i.cancel(),new t(`INVALID_ARGS`,r);a.push(s)}return Buffer.concat(a).toString(`utf8`)}function Te(e,t,n){let r=Ee(e,n);return r.length>0&&h(r,t)}function Ee(e,t){let n=e.headers.get(`authorization`)??``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers.get(`x-agent-device-token`);if(r!==null)return r;if(t){let e=ke(t);if(e)return e}return``}function De(e,t,n){let r=JSON.parse(e);return r.params={...r.params??{},token:t},n&&Oe(r.params,n),JSON.stringify(r)}function Oe(e,t){e.tenantId=t,e.meta={...J(e.meta),tenantId:t,sessionIsolation:`tenant`};let n=J(e.flags);n.tenant!==void 0&&(n.tenant=t),n.sessionIsolation!==void 0&&(n.sessionIsolation=`tenant`)}function J(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function ke(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function Ae(e){if(e)try{let{method:t}=JSON.parse(e);return typeof t==`string`?t:void 0}catch{return}}function Y(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function je(e){let t=e.headers.get(`x-request-id`);return t?.trim()?t.trim().slice(0,128):_()}function Me(e,t,n,r){if(t!==`/rpc`)return null;let i=e.headers.get(u);return i===null||i===r?null:Ne(n)}function Ne(n){return Response.json(o(n,`Proxy instance changed`,e(new t(`COMMAND_FAILED`,`Proxy instance changed`,{reason:`remote_instance_mismatch`}))),{status:409,headers:{[f]:`true`}})}function Pe(n,r){return n===`/rpc`?Response.json({jsonrpc:`2.0`,id:r,error:{code:-32001,message:`Invalid proxy token`,data:e(new t(`UNAUTHORIZED`,`Invalid proxy token`))}},{status:401}):Response.json({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`},{status:401})}function Fe(n){let r=new t(`UNAUTHORIZED`,`This RPC method cannot act as an authenticated tenant through the proxy`,{hint:`Use agent_device.command or the agent_device.lease methods.`});return Response.json({jsonrpc:`2.0`,id:n,error:{code:-32001,message:r.message,data:e(r)}},{status:401})}function Ie(e){let t;try{t=JSON.parse(e)}catch{return X(-32700,`Parse error`)}return t&&typeof t==`object`&&!Array.isArray(t)?null:X(-32600,`Invalid Request`)}function X(n,r){return Response.json({jsonrpc:`2.0`,id:null,error:{code:n,message:r,data:e(new t(`INVALID_ARGS`,r))}},{status:400})}function Z(t,n){let r=e(n),i=r.code===`INVALID_ARGS`;return Response.json({jsonrpc:`2.0`,id:t,error:{code:i?-32602:-32e3,message:r.message,data:r}},{status:i?400:500})}async function Le(t,n){let r=G(U(n.url),n.method)?(await import(`./transfer-transport.js`)).transferWireDetails(t):{},i=e(t);return Response.json({ok:!1,error:i.message,code:i.code,...r},{status:i.code===`INVALID_ARGS`?400:500})}const Re=async({positionals:e,flags:n,host:r})=>{if(e.length>0)throw new t(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let i=await Q(n,r);return await ae(n,i,()=>Ue(i)),await We(),!0};async function Q(e,n){let r;if(e.publicOrigin!==void 0)try{r=m(e.publicOrigin)}catch(e){throw new t(`INVALID_ARGS`,`Invalid --public-origin`,{},e)}let i=await g({stateDir:e.stateDir,host:n}),o=ze(i.httpPort),s=Be(e),c=D({upstreamBaseUrl:o,upstreamToken:i.token,clientToken:s,publicOrigin:r});await Ve(c,e.proxyHost?.trim()||`127.0.0.1`,e.proxyPort??0);let l=c.address();if(!l||typeof l==`string`)throw new t(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let u=`http://${He(l.address)}:${l.port}`;return{proxyBaseUrl:u,agentDeviceBaseUrl:a(u),token:s,upstreamBaseUrl:o,stateDir:i.stateDir}}function ze(e){if(!e)throw new t(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${e}`}function Be(e){return e.daemonAuthToken?.trim()||oe(32).toString(`hex`)}function Ve(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function He(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function Ue(e,t={}){let n=t.useColor??re(process.env,process.stdout),r=$(`✓`,`green`,n),i=$(e.proxyBaseUrl,`cyan`,n),a=$(`<tunnel URL>`,`cyan`,n),o=$(e.token,`yellow`,n);return[`${r} Proxy listening at ${i}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${a}`,`Daemon auth token: ${o}`].join(` `)}function $(e,t,n){return n?ie(e,t,{validateStream:!1}):e}function We(){return new Promise(()=>{})}export{Re as proxyCommand};