MCPcopy Create free account
hub / github.com/freecodexyz/free-code / createCodexFetch

Function createCodexFetch

src/services/api/codex-fetch-adapter.ts:746–812  ·  view source on GitHub ↗
(
  accessToken: string,
)

Source from the content-addressed store, hash-verified

744 * @returns A fetch function that translates Anthropic requests to Codex format
745 */
746export function createCodexFetch(
747 accessToken: string,
748): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {
749 const accountId = extractAccountId(accessToken)
750
751 return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
752 const url = input instanceof Request ? input.url : String(input)
753
754 // Only intercept Anthropic API message calls
755 if (!url.includes('/v1/messages')) {
756 return globalThis.fetch(input, init)
757 }
758
759 // Parse the Anthropic request body
760 let anthropicBody: Record<string, unknown>
761 try {
762 const bodyText =
763 init?.body instanceof ReadableStream
764 ? await new Response(init.body).text()
765 : typeof init?.body === 'string'
766 ? init.body
767 : '{}'
768 anthropicBody = JSON.parse(bodyText)
769 } catch {
770 anthropicBody = {}
771 }
772
773 // Get current token (may have been refreshed)
774 const tokens = getCodexOAuthTokens()
775 const currentToken = tokens?.accessToken || accessToken
776
777 // Translate to Codex format
778 const { codexBody, codexModel } = translateToCodexBody(anthropicBody)
779
780 // Call Codex API
781 const codexResponse = await globalThis.fetch(CODEX_BASE_URL, {
782 method: 'POST',
783 headers: {
784 'Content-Type': 'application/json',
785 Accept: 'text/event-stream',
786 Authorization: `Bearer ${currentToken}`,
787 'chatgpt-account-id': accountId,
788 originator: 'pi',
789 'OpenAI-Beta': 'responses=experimental',
790 },
791 body: JSON.stringify(codexBody),
792 })
793
794 if (!codexResponse.ok) {
795 const errorText = await codexResponse.text()
796 const errorBody = {
797 type: 'error',
798 error: {
799 type: 'api_error',
800 message: `Codex API error (${codexResponse.status}): ${errorText}`,
801 },
802 }
803 return new Response(JSON.stringify(errorBody), {

Callers 1

getAnthropicClientFunction · 0.85

Calls 5

extractAccountIdFunction · 0.85
getCodexOAuthTokensFunction · 0.85
translateToCodexBodyFunction · 0.85
textMethod · 0.80

Tested by

no test coverage detected