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 • 8.63 kB
import{v as e}from"./sdk-contracts.js";import t from"node:fs";import n from"node:path";async function r(t,n){let r=await t.text();if(!t.ok){let r=t.status;throw new e(r===401||r===403?`UNAUTHORIZED`:`COMMAND_FAILED`,n.rejectedMessage,{status:r,...r===429||r>=500?{retriable:!0,hint:`Retry the request later. Do not sign in again.`}:{}})}let i={};if(r.trim().length>0)try{i=JSON.parse(r)}catch{throw new e(`COMMAND_FAILED`,n.invalidJsonMessage,{status:t.status})}return i}const i=1e3;async function a(e){return await o({command:e.command,flags:e.flags,stateDir:e.stateDir,allowInteractiveLogin:e.command===`connect`&&!e.flags.noLogin,env:e.env})}async function o(t){let{env:n}=t;if(!t.flags.daemonBaseUrl)return{flags:t.flags,source:`none`};if(A(t.flags.daemonAuthToken))return{flags:t.flags,source:`flag`};if(A(n.AGENT_DEVICE_DAEMON_AUTH_TOKEN))return{flags:t.flags,source:`env`};if(!T(t.flags.daemonBaseUrl,n))return{flags:t.flags,source:`none`};let r=await m({stateDir:t.stateDir,flags:t.flags,env:n,io:t.io});if(r)return{flags:{...t.flags,daemonAuthToken:r.accessToken},source:`cli-session`};if(!t.allowInteractiveLogin)throw t.flags.noLogin?new e(`UNAUTHORIZED`,`Remote daemon authentication is required.`,{hint:`Run agent-device auth login, unset --no-login, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.`}):C(t.command,n);let i=await c({stateDir:t.stateDir,flags:t.flags,env:n,io:t.io});return{flags:{...t.flags,daemonAuthToken:i.accessToken},source:`login`}}async function s(t){let{env:n}=t;if(A(t.flags.daemonAuthToken))return{accessToken:t.flags.daemonAuthToken,cloudBaseUrl:w(n)};if(A(n.AGENT_DEVICE_DAEMON_AUTH_TOKEN))return{accessToken:n.AGENT_DEVICE_DAEMON_AUTH_TOKEN,cloudBaseUrl:w(n)};let r=await m({stateDir:t.stateDir,flags:t.flags,env:n,io:t.io});if(r)return{accessToken:r.accessToken,cloudBaseUrl:r.cloudBaseUrl};if(t.flags.noLogin)throw new e(`UNAUTHORIZED`,`Cloud connection profile authentication is required.`,{hint:`Run agent-device auth login, unset --no-login, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.`});let i=await c({stateDir:t.stateDir,flags:t.flags,env:n,io:t.io,commandLabel:`agent-device connect`});return{accessToken:i.accessToken,cloudBaseUrl:i.session.cloudBaseUrl}}async function c(t){let{env:n}=t,r=b(n,t.io);if(r===`non-interactive`)throw C(t.commandLabel??`agent-device connect`,n);let i=w(n),a=await _({baseUrl:i,pathName:`/api/control-plane/device-auth/start`,body:{client:`agent-device`,tenant:t.flags.tenant,runId:t.flags.runId,daemonBaseUrl:t.flags.daemonBaseUrl,session:t.flags.session},fetchImpl:t.io?.fetch});await v(a);let o=A(a.verificationUriComplete)?a.verificationUriComplete:a.verificationUri;if(r===`local-browser`)O(t.io,`Opening ${a.verificationUri}...\n`),await D(o,t.io);else{let e=E(a.verificationUri,a.userCode);O(t.io,`Open this URL on your machine:\n${e}\n\nWaiting for approval for 10 minutes...\n`)}let s=await g({cloudBaseUrl:i,deviceCode:a.deviceCode,expiresIn:a.expiresIn,interval:a.interval,fetchImpl:t.io?.fetch,now:t.io?.now}),c=s.cliSession?.refreshCredential??s.cliSession?.refreshToken;if(!A(s.accessToken)||!A(c))throw new e(`UNAUTHORIZED`,`Device authorization did not return CLI credentials.`);let l=new Date(t.io?.now?.()??Date.now()).toISOString(),d={version:1,id:s.cliSession?.id??`cli-${Date.now().toString(36)}`,cloudBaseUrl:i,workspaceId:s.cliSession?.workspaceId,accountId:s.cliSession?.accountId,name:s.cliSession?.name,refreshCredential:c,createdAt:l,expiresAt:s.cliSession?.expiresAt};return u({stateDir:t.stateDir,session:d}),{accessToken:s.accessToken,expiresAt:s.expiresAt,session:d}}function l(e){let n=f(e.stateDir);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e.version!==1||!A(e.id)||!A(e.cloudBaseUrl)||!A(e.refreshCredential)||!A(e.createdAt)?null:e}catch{return null}}function u(e){let r=f(e.stateDir);t.mkdirSync(n.dirname(r),{recursive:!0,mode:448}),t.writeFileSync(r,`${JSON.stringify(e.session,null,2)}\n`,{mode:384});try{t.chmodSync(r,384)}catch{}}function d(e){let n=f(e.stateDir);return t.existsSync(n)?(t.rmSync(n,{force:!0}),!0):!1}function f(e){return n.join(e,`auth`,`cli-session.json`)}function p(e){let t=l({stateDir:e.stateDir});return t?{authenticated:!0,source:`cli-session`,sessionId:t.id,cloudBaseUrl:t.cloudBaseUrl,workspaceId:t.workspaceId,accountId:t.accountId,name:t.name,createdAt:t.createdAt,expiresAt:t.expiresAt,expired:k(t.expiresAt,e.now)}:{authenticated:!1,source:`none`}}async function m(e){let t=l({stateDir:e.stateDir});return!t||k(t.expiresAt,e.io?.now)?null:{accessToken:(await h({session:t,flags:e.flags,env:e.env,io:e.io})).accessToken,cloudBaseUrl:w(e.env,t.cloudBaseUrl)}}async function h(t){let n=await _({baseUrl:w(t.env,t.session.cloudBaseUrl),pathName:`/api/control-plane/cli-session/refresh`,body:{refreshCredential:t.session.refreshCredential,tenant:t.flags.tenant,runId:t.flags.runId,daemonBaseUrl:t.flags.daemonBaseUrl,session:t.flags.session},fetchImpl:t.io?.fetch});if(A(n.accessToken))return{accessToken:n.accessToken,expiresAt:n.expiresAt};throw n.status===`revoked`||n.error===`revoked`?new e(`UNAUTHORIZED`,`Stored cloud CLI session was revoked.`,{hint:`Run agent-device auth login again, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.`,status:n.status,error:n.error}):new e(`UNAUTHORIZED`,`Failed to refresh CLI session.`,{hint:`Run agent-device auth login again, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.`,status:n.status,error:n.error})}async function g(t){let n=t.now??Date.now,r=Math.min((t.expiresIn??600)*1e3,6e5),a=n()+r,o=Math.max(i,(t.interval??5)*1e3);for(;n()<a;){let n=await _({baseUrl:t.cloudBaseUrl,pathName:`/api/control-plane/device-auth/poll`,body:{deviceCode:t.deviceCode},fetchImpl:t.fetchImpl});if(n.status===`approved`||A(n.accessToken))return n;if(n.status===`slow_down`||n.error===`slow_down`)o+=i;else if(n.status!==`authorization_pending`&&n.error!==`authorization_pending`)throw new e(`UNAUTHORIZED`,`Device authorization was not approved.`,{status:n.status,error:n.error});await j(o)}throw new e(`TIMEOUT`,`Device authorization expired before approval.`)}async function _(e){let t=await(e.fetchImpl??fetch)(new URL(e.pathName,e.baseUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e.body),signal:AbortSignal.timeout(15e3)});return await r(t,{invalidJsonMessage:`Cloud auth endpoint returned invalid JSON (${t.status}).`,rejectedMessage:`Cloud auth endpoint rejected the request.`})}async function v(e){if(!A(e.deviceCode))throw y(`deviceCode`);if(!A(e.userCode))throw y(`userCode`);if(!A(e.verificationUri))throw y(`verificationUri`);let{isSafeBrowserUrl:t}=await import(`./browser-launch.js`);if(!t(e.verificationUri))throw y(`verificationUri`);if(A(e.verificationUriComplete)&&!t(e.verificationUriComplete))throw y(`verificationUriComplete`)}function y(t){return new e(`COMMAND_FAILED`,`Cloud auth start returned an unusable response.`,{field:t})}function b(e,t){let n=t?.stdinIsTTY??process.stdin.isTTY,r=t?.stdoutIsTTY??process.stdout.isTTY;return x(e)||!n||!r?`non-interactive`:S(e)?`device-code`:`local-browser`}function x(e){return e.CI===`true`||e.GITHUB_ACTIONS===`true`||e.BUILDKITE===`true`}function S(e){return!!(e.SSH_TTY||e.SSH_CONNECTION||e.CODESPACES===`true`||e.GITPOD_WORKSPACE_ID||e.REMOTE_CONTAINERS===`true`)}function C(t,n){let r=w(n);return new e(`UNAUTHORIZED`,`${t} cannot perform interactive login in CI or a non-interactive shell.`,{hint:`Create a service/API token: ${new URL(`/api-keys`,r).toString()} Then set AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_...`})}function w(t,n){let r=t.AGENT_DEVICE_CLOUD_BASE_URL??n??`https://cloud.agent-device.dev`;try{return new URL(r).toString().replace(/\/+$/,``)}catch(t){throw new e(`INVALID_ARGS`,`Invalid AGENT_DEVICE_CLOUD_BASE_URL.`,{cloudBaseUrl:r},t instanceof Error?t:void 0)}}function T(e,t){if(t.AGENT_DEVICE_CLOUD_AUTH===`1`||t.AGENT_DEVICE_CLOUD_AUTH===`true`||A(t.AGENT_DEVICE_CLOUD_BASE_URL))return!0;try{let t=new URL(e).hostname.toLowerCase();return t===`agent-device.dev`||t.endsWith(`.agent-device.dev`)}catch{return!1}}function E(e,t){let n=new URL(e);return n.searchParams.set(`user_code`,t),n.toString()}async function D(e,t){if(t?.openBrowser){await t.openBrowser(e);return}let{openUrlInBrowser:n}=await import(`./browser-launch.js`);await n(e)||O(t,`Open this URL on your machine:\n${e}\n`)}function O(e,t){(e?.stderr??process.stderr).write(t)}function k(e,t){if(!e)return!1;let n=Date.parse(e);return!Number.isFinite(n)||n<=(t?.()??Date.now())}function A(e){return typeof e==`string`&&e.trim().length>0}async function j(e){await new Promise(t=>setTimeout(t,e))}export{p as a,a as i,d as n,r as o,s as r,c as t};