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 • 6.83 kB
import{v as e}from"./sdk-contracts.js";import{C as t,I as n,N as r,R as i,_ as a,at as o,g as s,p as c}from"./sdk-io.js";import{n as l,o as u}from"./file.js";import{t as d}from"./base-url.js";import"./command.js";import{a as ee,c as f,d as p,f as m,i as h,l as g,n as _,o as v,r as y,s as b,u as x}from"./client-companion-tunnel-contract.js";import{createHash as S}from"node:crypto";import C from"node:fs";import w from"node:path";import{fileURLToPath as T}from"node:url";const E=`companion-tunnel`;function D(e){return S(`sha256`).update(e).digest(`hex`)}function O(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function k(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.tenantId==`string`&&typeof t.runId==`string`&&typeof t.leaseId==`string`)return{tenantId:t.tenantId,runId:t.runId,leaseId:t.leaseId}}function A(e,t){return e.tenantId===t.tenantId&&e.runId===t.runId&&e.leaseId===t.leaseId}function j(e,t,n,r){let i=r??w.join(e,`.agent-device`),a=w.join(i,`${t.slug}.lock`);if(!n)return{statePath:w.join(i,`${t.slug}.json`),logPath:w.join(i,`${t.slug}.log`),lockPath:a};let o=D(n).slice(0,12),s=w.join(i,t.slug);return{statePath:w.join(s,`${t.slug}-${o}.json`),logPath:w.join(s,`${t.slug}-${o}.log`),lockPath:a}}async function M(e,t,n){let r=c();return await u({acquire:()=>l({lockDirPath:e.lockPath,owner:{pid:r.pid,startTime:r.startTime,acquiredAtMs:Date.now()},description:`${t.displayName} state`}),task:n})}function N(e){try{let t=JSON.parse(C.readFileSync(e,`utf8`));if(!Number.isInteger(t.pid)||Number(t.pid)<=0||typeof t.serverBaseUrl!=`string`||typeof t.localBaseUrl!=`string`||typeof t.tokenHash!=`string`||t.tokenHash.length===0)return null;let n=Array.isArray(t.consumers)?t.consumers.filter(e=>typeof e==`string`&&e.length>0):[];return{pid:Number(t.pid),startTime:typeof t.startTime==`string`?t.startTime:void 0,command:typeof t.command==`string`?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:O(t.launchUrl),registerPath:O(t.registerPath),unregisterPath:O(t.unregisterPath),bridgeScope:k(t.bridgeScope),tokenHash:t.tokenHash,consumers:n}}catch{return null}}function P(e,t){C.mkdirSync(w.dirname(e),{recursive:!0}),C.writeFileSync(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}function F(e){C.mkdirSync(w.dirname(e),{recursive:!0}),C.closeSync(C.openSync(e,`a`))}function I(e){try{C.unlinkSync(e)}catch{}}function L(e){try{C.readdirSync(e).length===0&&C.rmdirSync(e)}catch{}}function R(e){let t=w.dirname(e.statePath),n=w.dirname(e.logPath);I(e.statePath),I(e.logPath),t!==w.dirname(e.lockPath)&&L(t),n!==t&&L(n)}function z(e,t){return e.includes(t.runArg)}function B(e,i){if(!t(e.pid))return!1;if(e.startTime){let t=n(e.pid);if(!t||t!==e.startTime)return!1}let a=r(e.pid);return!a||!z(a,i.definition)||!e.bridgeScope?!1:e.serverBaseUrl===d(i.serverBaseUrl)&&e.localBaseUrl===d(i.localBaseUrl)&&e.launchUrl===O(i.launchUrl)&&e.registerPath===O(i.registerPath)&&e.unregisterPath===O(i.unregisterPath)&&A(e.bridgeScope,i.bridgeScope)&&e.tokenHash===D(i.bearerToken)}function V(e){return O(e.consumerKey)??O(e.profileKey)??null}function H(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}function U(e,t){return t?{...e,consumers:e.consumers.filter(e=>e!==t)}:{...e,consumers:[]}}async function W(e,t,n){let r=await i({pid:e.pid,identity:{startTime:e.startTime,matches:e=>z(e,t)}},{termTimeoutMs:1e3,killTimeoutMs:1e3});if(r.status===`retained`)throw G({...r,pid:e.pid},t,n)}function G(t,n,r){let i=t.reason===`identity-unverified`?`${n.displayName} ${a(t.pid,`the ${n.displayName} this profile started`)}. Stop it yourself, as its owner if needed.`:`${n.displayName} pid ${t.pid} is still running${t.reason===`exit-timeout`?`: it survived ${t.signal}.`:t.errno===`EPERM`?`: it refused ${t.signal} (${t.errno}), so it belongs to another user or was started with elevated privileges. Stop it as that user, e.g. \`sudo kill ${t.pid}\`.`:`: it refused ${t.signal} (${t.errno}).`}`;return new e(`COMMAND_FAILED`,i,{...s(t,t.pid),statePath:r.statePath,logPath:r.logPath,hint:`${r.statePath} still tracks this pid, so a retry acts on that same companion instead of starting a second one.`})}function K(e,t){try{P(e,t)}catch{}}function q(e,t,n){n===void 0?delete e[t]:e[t]=n}function J(e,t){let n={...t};return n[g]=d(e.serverBaseUrl),n[_]=e.bearerToken,n[h]=d(e.localBaseUrl),n[x]=j(e.projectRoot,e.definition,e.profileKey,e.stateDir).statePath,n[f]=e.bridgeScope.tenantId,n[b]=e.bridgeScope.runId,n[v]=e.bridgeScope.leaseId,q(n,y,O(e.launchUrl)),q(n,ee,O(e.registerPath)),q(n,p,O(e.unregisterPath)),n}function Y(e){let t=T(import.meta.url),n=w.extname(t)||`.js`,r=[w.join(w.dirname(t),`${E}${n}`),w.join(w.dirname(t),`internal`,`${E}${n}`)].find(e=>C.existsSync(e));if(!r)throw Error(`${e.displayName} entrypoint not found. Rebuild the package to include the companion worker entry.`);return r}function X(e,t){let i=Y(e.definition),a=i.endsWith(`.ts`)?[`--experimental-strip-types`]:[];C.mkdirSync(w.dirname(t),{recursive:!0});let s=C.openSync(t,`a`),c=0;try{c=o(process.execPath,[...a,i,e.definition.runArg],{cwd:e.cwd,env:J(e,e.env),stdio:[`ignore`,s,s]})}finally{C.closeSync(s)}if(!Number.isInteger(c)||c<=0)throw Error(`Failed to start ${e.definition.displayName} process.`);return{pid:c,startTime:n(c)??void 0,command:r(c)??void 0,serverBaseUrl:d(e.serverBaseUrl),localBaseUrl:d(e.localBaseUrl),launchUrl:O(e.launchUrl),registerPath:O(e.registerPath),unregisterPath:O(e.unregisterPath),bridgeScope:e.bridgeScope,tokenHash:D(e.bearerToken),consumers:[]}}async function Z(e){let t=V(e),n=j(e.projectRoot,e.definition,e.profileKey,e.stateDir);return await M(n,e.definition,async()=>await Q(e,t,n))}async function Q(t,n,r){let i=N(r.statePath);if(i&&B(i,t)){let e=H(i,n);return e!==i&&P(r.statePath,e),{pid:i.pid,spawned:!1,statePath:r.statePath,logPath:r.logPath}}i&&(await W(i,t.definition,r),R(r)),F(r.statePath);let a;try{a=X(t,r.logPath),P(r.statePath,H(a,n))}catch(n){if(a)try{await W(a,t.definition,r)}catch(t){throw K(r.statePath,a),t instanceof e&&(t.cause=n),t}throw R(r),n}return{pid:a.pid,spawned:!0,statePath:r.statePath,logPath:r.logPath}}async function te(e){let t=V(e),n=j(e.projectRoot,e.definition,e.profileKey,e.stateDir);return await M(n,e.definition,async()=>{let r=N(n.statePath);if(!r)return R(n),{stopped:!1,statePath:n.statePath};let i=U(r,t);return i.consumers.length>0?(P(n.statePath,i),{stopped:!1,statePath:n.statePath}):(await W(r,e.definition,n),R(n),{stopped:!0,statePath:n.statePath})})}const $={slug:`metro-companion`,runArg:m,displayName:`Metro companion`};async function ne(e){return await Z({...e,definition:$,registerPath:e.registerPath??`/api/metro/companion/register`})}async function re(e){return await te({...e,definition:$})}export{ne as ensureMetroCompanion,re as stopMetroCompanion};