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 • 8.41 kB
JavaScript
import{ct as e}from"./sdk-batch.js";import{C as t,j as n,m as r,v as i}from"./sdk-contracts.js";import{St as a}from"./sdk-io.js";import"./diagnostics.js";import{R as o}from"./sdk-device.js";import{b as s,d as c,f as l,g as u,p as d,u as f,y as p}from"./lease-scope.js";import{n as m}from"./catalog.js";import{c as h}from"./device-shell.js";import{r as g}from"./artifact-tracking.js";import{_,f as v,g as y,l as b,m as x}from"./lease-registry-scope.js";import{d as S,f as C}from"./request.js";import{a as w,i as T}from"./lease-context.js";import{n as E}from"./context.js";import{n as D,r as O}from"./lease-release.js";async function k(t){let{req:n,sessionName:r,sessionStore:i,leaseRegistry:a,providerRuntimeIds:o,failedPlugins:c,providerCredentials:l,leaseLifecycleProvider:u,cloudArtifactProvider:d,endSessionsForLease:f}=t,p=T(n);switch(n.command){case m.artifacts:return{ok:!0,data:await V(n,w(n,i.get(r)),a,d,t.host.env)};case`lease_allocate`:{J(p.leaseBackend);let r=y(p.leaseProvider);z(r,o??[],c??[]),B({leaseProvider:r,leaseBackend:p.leaseBackend},n.meta?.providerCredentialFingerprint,l);let{lease:i,reused:s}=await A(n,{...p,leaseProvider:r},a,t.host),d=n.meta?.requestId;return await a.runDeviceMutation(i,async()=>{let r,o=u?.allocate?a.retainLeaseWork(i,()=>!C(d)):void 0;try{r=await u?.allocate?.(i,{...R(n,t.host),signal:S(d),deadline:Date.now()+e}),D(a,i,r)}catch(e){throw await N(i,s,d,u,a),e}finally{o?.release()}if(C(d))throw await P(i,u,a);return{ok:!0,data:{lease:a.getLease(b(i))??i,reused:s,...r?{provider:r}:{}}}})}case`lease_heartbeat`:return await F(t,p);case`lease_release`:{let e=s(p),r=a.getLease(e);q(r);let i=await a.runDeviceMutation(r,async()=>await O(a,u,r,e,R(n,t.host)));return r&&i.registryReleased&&await f?.(r.leaseId),{ok:!0,data:{released:i.registryReleased,...i.provider?{provider:i.provider}:{}}}}default:return null}}async function A(e,t,n,r){let i=u(t),a=e.meta?.devicePin&&c(t),o=a?void 0:n.renewRequestedLease(i);if(o)return{lease:o,reused:!0};let s=a&&t.leaseId?_(t.leaseId):void 0,l=s?n.listActiveLeases().find(e=>e.leaseId===s):void 0,d=await j(e,{...t,deviceKey:v(t.deviceKey)??l?.deviceKey},r.env),f=new Set(n.listActiveLeases().map(e=>e.leaseId)),p=n.allocateLease(d?{...i,deviceKey:d}:i);return{lease:p,reused:f.has(p.leaseId)}}async function j(e,t,n){let i=e.meta?.devicePin;if(!c(t)||t.deviceKey&&!i)return;let a=i?await import(`./device-selection-resolver.js`).then(e=>e.t):void 0,s=e.flags??{},u=i&&a?a.effectiveDevicePinSelector(i,s):s,d={platform:u.platform,target:s.target,device:u.device,udid:u.udid,serial:u.serial,iosSimulatorDeviceSet:s.iosSimulatorDeviceSet,androidDeviceAllowlist:s.androidDeviceAllowlist};if(t.deviceKey&&i)return await M(t.deviceKey,i,d,n);let{hasDeviceSelectionInput:f}=await import(`./device-selector-intent.js`).then(e=>e.t);if(!f(d))return;let{resolveTargetDevice:p}=await import(`./dispatch-resolve.js`).then(e=>e.n),m=await p({...d,platform:d.platform??(t.leaseBackend?r(t.leaseBackend):void 0)},{env:n});return i&&a&&a.assertDeviceHonorsPin(i,m,d),l({platform:o(m),target:m.target,id:m.id})}async function M(e,t,n,r){let{listDeviceInventory:a}=await import(`./device-inventory-context.js`).then(e=>e.t),{buildDeviceInventoryRequestFromFlags:s}=await import(`./dispatch-resolve.js`).then(e=>e.n),{assertDeviceHonorsPin:c}=await import(`./device-selection-resolver.js`).then(e=>e.t),u=(await a(s(n,r))).find(t=>l({...t,platform:o(t)})===e);if(!u)throw new i(`INVALID_ARGS`,`The lease device key does not match an available pinned device.`,{reason:`device_pin_conflict`,pin:t.selector,pinSource:`${t.source.kind===`project`?`project `:``}config file ${t.source.path}`,deviceKey:e});return c(t,u,n),e}async function N(e,t,n,r,i){if(!t){i.releaseLease(b(e));return}if(C(n))throw await P(e,r,i)}async function P(e,t,r){let i=b(e),a,o;try{a=await O(r,t,e,i)}catch(e){o=n(e),a={registryReleased:r.releaseLease(i).released}}return I(e,a,o)}async function F(e,t){let{leaseRegistry:r,leaseLifecycleProvider:o,req:s,endSessionsForLease:c}=e,l=r.heartbeatLease(p(t)),u,d;try{u=await o?.heartbeat?.(l,{...R(s,e.host),signal:S(s.meta?.requestId)})}catch(e){if(!(e instanceof i)||!f(e))throw e;r.endProviderLease(b(l)),d=e}if(d){try{await c?.(l.leaseId,`PROVIDER_INSTANCE_ENDED`)}catch(e){a({level:`warn`,phase:`lease_provider_ended_session_teardown_failed`,data:{leaseId:l.leaseId,error:n(e)}})}throw d}return{ok:!0,data:{lease:l,...u?{provider:u}:{}}}}function I(e,n,r){let i=n.provider?.providerSessionId,a=Array.isArray(n.provider?.warnings)?n.provider.warnings:[],o=n.registryReleased&&r===void 0&&a.length===0;return t({leaseId:e.leaseId,leaseProvider:e.leaseProvider,released:o,registryReleased:n.registryReleased,providerSessionId:i,...a.length>0?{warnings:a}:{},...r===void 0?{}:{releaseError:r},hint:L(o,e.leaseId,i)})}function L(e,t,n){return e?`The lease request was canceled while the provider was still allocating; the session it produced was released.`:`The lease request was canceled while the provider was still allocating, and the session it produced could NOT be confirmed released — it may still be running and billing. Stop provider session ${String(n??`(unknown)`)} for lease ${t} by hand.`}function R(e,t){return{flags:e.flags,...typeof e.flags?.providerApp==`string`?{initialApp:e.flags.providerApp}:{},cwd:E(e,t),...e.internal?.publicNetworkOnly?{publicNetworkOnly:!0}:{}}}function z(e,t,n){let r=d({leaseProvider:e});if(r===void 0||t.includes(r))return;let a=n.flatMap(e=>e.state===`failed`&&(e.provider===r||e.provider===void 0)?[{...e.provider===void 0?{}:{provider:e.provider},...e.package===void 0?{}:{package:e.package},code:e.error.code,...e.error.reason===void 0?{}:{reason:e.error.reason},message:e.error.message}]:[]);throw new i(`UNSUPPORTED_OPERATION`,`Provider "${r}" is not available in this daemon runtime.`,{reason:`provider-not-registered`,provider:r,registeredProviders:[...t],...a.length>0?{failedPlugins:a}:{},hint:a.length>0?`Fix the plugin that failed to register (see failedPlugins or agent-device daemon status), restart the daemon, then retry lease allocation.`:`Restart the daemon with ${r} configured, then retry lease allocation.`})}function B({leaseProvider:e,leaseBackend:t},n,r){if(!r||!e||!n)return;let a=r.fingerprint(e,t);if(n!==a)throw new i(`INVALID_ARGS`,a?`The running daemon holds different ${e} credentials than this shell.`:`The running daemon was started without the ${e} credentials this shell holds.`,{reason:`provider-credentials-changed`,provider:e,hint:`Stop it with agent-device daemon stop --state-dir ${h(r.stateDir)}, then rerun the command so a new daemon starts with this shell's environment.`})}async function V(e,t,n,r,i){let a=K(e.flags,`providerSessionId`);return H(t,a)?await U(t.tenantId,i):await W(t,a,n,r)}function H(e,t){return c(e)||!e.leaseProvider&&!t}async function U(e,t){let n=await g(e,t);return{source:`daemon`,status:`ready`,artifacts:n,...n.length===0?{message:`No daemon artifacts available.`}:{}}}async function W(e,t,n,r){if(!e.leaseProvider)throw new i(`INVALID_ARGS`,`artifacts requires --provider for provider session lookup or an active cloud connection.`);if(!e.leaseId&&!t)throw new i(`INVALID_ARGS`,`artifacts requires an active cloud lease or --provider-session <id>.`);let a=G(n,e,t),o=await r?.listCloudArtifacts?.({provider:e.leaseProvider,leaseId:a?.leaseId??e.leaseId,providerSessionId:t});if(!o)throw new i(`UNSUPPORTED_OPERATION`,`Cloud artifacts are not available for provider "${e.leaseProvider}".`);return o}function G(e,t,n){if(!n)return;let r=e.resolveProviderSession({provider:t.leaseProvider,providerSessionId:n,tenantId:t.tenantId});if(r)return r;throw new i(`UNAUTHORIZED`,`Provider session is not owned by the request tenant`,{reason:`PROVIDER_SESSION_NOT_OWNED`})}function K(e,t){let n=e?.[t];return typeof n==`string`&&n.trim().length>0?n.trim():void 0}function q(e){if(e?.backend===`macos-app`)throw new i(`UNAUTHORIZED`,`A macos-app lease is released by the host administrator.`,{reason:`MACOS_APP_LEASE_HOST_OWNED`,retriable:!1,hint:`Disconnect only drops the client connection; the host ends the lease.`})}function J(e){if(x(e)===`macos-app`)throw new i(`UNAUTHORIZED`,`A macos-app lease is allocated by the host administrator.`,{reason:`MACOS_APP_LEASE_HOST_ALLOCATED`,retriable:!1,hint:`Ask the host administrator for a macos-app lease and connect with its leaseId.`})}export{k as handleLeaseCommands};