eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 1.98 kB
JavaScript
import{getDefaultCodexTokenBroker}from"./token-broker.js";import{isObject}from"#shared/guards.js";const CODEX_API_ENDPOINT=`https://chatgpt.com/backend-api/codex/responses`;function createCodexFetch(e={}){let t=e.fetch??fetch,n=e.broker??getDefaultCodexTokenBroker(),r=e.codexApiEndpoint??CODEX_API_ENDPOINT;return async(e,i)=>{let a=rewriteCodexEndpoint(requestUrl(e),r),o=stripInputItemIds(i),s=await n.getToken({reason:`request`}),c=await t(a,authenticatedInit(e,o,s));if(c.status!==401||!isReplayable(e,i))return c;await c.body?.cancel();let l=await n.getToken({reason:`rejected`});return t(a,authenticatedInit(e,o,l))}}function stripInputItemIds(e){if(typeof e?.body!=`string`)return e;let t;try{t=JSON.parse(e.body)}catch{return e}if(!isObject(t)||!Array.isArray(t.input))return e;let n=!1;for(let e of t.input)isObject(e)&&`id`in e&&(delete e.id,n=!0);return n?{...e,body:JSON.stringify(t)}:e}function rewriteCodexEndpoint(e,t=CODEX_API_ENDPOINT){let n=new URL(e);return n.pathname.includes(`/v1/responses`)||n.pathname.includes(`/chat/completions`)?t:e}function authenticatedInit(e,t,n){let r=cloneHeaders(t?.headers??(e instanceof Request?e.headers:void 0));return r.delete(`authorization`),r.delete(`Authorization`),r.set(`authorization`,`Bearer ${n.token}`),r.set(`originator`,`eve`),n.accountId===void 0?r.delete(`ChatGPT-Account-Id`):r.set(`ChatGPT-Account-Id`,n.accountId),fetchInit(e,t,r)}function isReplayable(e,t){return e instanceof Request?!1:!(t?.body instanceof ReadableStream)}function cloneHeaders(e){return new Headers(e)}function requestUrl(e){return e instanceof Request?e.url:e.toString()}function fetchInit(e,t,n){return t===void 0?e instanceof Request?{body:e.body,cache:e.cache,credentials:e.credentials,headers:n,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}:{headers:n}:{...t,headers:n}}export{createCodexFetch,rewriteCodexEndpoint};