UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

1 lines • 2.71 kB
import{extractCodexAccountIdFromToken,extractCodexAccountLabelFromToken,readCodexJwtExpirationMs}from"./auth.js";import{isObject}from"#shared/guards.js";const CHATGPT_ISSUER=`https://auth.openai.com`,CHATGPT_CLIENT_ID=`app_EMoamEEZ73f0CkXaXp7hrann`,CHATGPT_LOGIN_HINT="Open `/model` in `eve dev` and select ChatGPT subscription to sign in.";var ChatGptSignInRequiredError=class extends Error{constructor(){super(`ChatGPT subscription login expired or was revoked. ${CHATGPT_LOGIN_HINT}`)}};async function requestChatGptTokens(e,t={}){let n=AbortSignal.any([AbortSignal.timeout(3e4),...t.signal?[t.signal]:[]]),r;try{r=await(t.fetch??fetch)(`${CHATGPT_ISSUER}/oauth/token`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:CHATGPT_CLIENT_ID,...e}),signal:n,redirect:`error`})}catch{throw t.signal?.throwIfAborted(),Error(`Could not reach ChatGPT authentication. Check your connection and retry.`)}if(!r.ok)throw t.previous&&[400,401,403].includes(r.status)?new ChatGptSignInRequiredError:Error(`ChatGPT authentication failed (HTTP ${r.status}). Retry sign-in from /login.`);let i=await readChatGptAuthResponse(r),a=isObject(i)&&typeof i.access_token==`string`?i.access_token:void 0,o=isObject(i)&&typeof i.refresh_token==`string`?i.refresh_token:t.previous?.refreshToken;if(!a||!o||!isObject(i))throw Error(`ChatGPT authentication did not return a usable session. Retry sign-in from /login.`);let s=typeof i.id_token==`string`?i.id_token:void 0,c=extractCodexAccountIdFromToken(s)??extractCodexAccountIdFromToken(a)??t.previous?.accountId,l=extractCodexAccountLabelFromToken(s)??extractCodexAccountLabelFromToken(a)??t.previous?.accountLabel,u=(t.now??Date.now)(),d=typeof i.expires_in==`number`&&Number.isFinite(i.expires_in)&&i.expires_in>0?u+i.expires_in*1e3:readCodexJwtExpirationMs(a)??u+36e5;if(!Number.isFinite(d)||d<=u)throw Error(`ChatGPT authentication returned an expired session. Retry sign-in from /login.`);return{accessToken:a,refreshToken:o,expiresAt:d,...c&&{accountId:c},...l&&{accountLabel:l}}}async function readChatGptAuthResponse(e){let t=e.body?.getReader();if(!t)throw Error(`ChatGPT authentication returned an empty response. Retry from /login.`);try{let e=[],n=0;for(;;){let{value:r,done:i}=await t.read();if(i)break;if(n+=r.byteLength,n>65536)throw Error(`Response too large.`);e.push(r)}return JSON.parse(Buffer.concat(e).toString(`utf8`))}catch{throw await t.cancel().catch(()=>{}),Error(`ChatGPT authentication returned an invalid response. Retry from /login.`)}finally{t.releaseLock()}}export{CHATGPT_CLIENT_ID,CHATGPT_ISSUER,CHATGPT_LOGIN_HINT,ChatGptSignInRequiredError,readChatGptAuthResponse,requestChatGptTokens};