// OpenAI protocol portions are adapted in TypeScript; see third-party-notices.md. import { classifyOpenAiChatGptLimit } from './smartai.chatgpt.limits.js'; import { createOpenAiChatGptInstructionsMiddleware } from './smartai.chatgpt.middleware.js'; import type { IOpenAiModelConnection } from './index.js'; export const OPENAI_CHATGPT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex'; export const OPENAI_CHATGPT_DEFAULT_ORIGINATOR = 'smartai'; /** Whether a failed ChatGPT request reached the provider: `notSent` never did, `outcomeUnknown` may have. */ export type TOpenAiChatGptRequestOutcome = 'notSent' | 'outcomeUnknown'; export class OpenAiChatGptAuthError extends Error { public status?: number; public body?: string; public requestOutcome?: TOpenAiChatGptRequestOutcome; public retryAfterMs?: number; constructor(message: string, options: { status?: number; body?: string; requestOutcome?: TOpenAiChatGptRequestOutcome; retryAfterMs?: number; } = {}) { super(message); this.name = 'OpenAiChatGptAuthError'; this.status = options.status; this.body = options.body; this.requestOutcome = options.requestOutcome; this.retryAfterMs = options.retryAfterMs; } } /** * Access to ChatGPT with its identity stated by whoever issued it. * * `accountId` is optional only because a legacy login's token may carry no workspace claim; a request * then goes out without a `ChatGPT-Account-ID` header. Model connections require the workspace and take * `IOpenAiChatGptAccess`. */ export interface IOpenAiChatGptReadAccess { readonly accessToken: string; /** The ChatGPT workspace the token was issued for, sent as `ChatGPT-Account-ID`. */ readonly accountId?: string; /** Sent as `X-OpenAI-Fedramp: true` when set. */ readonly isFedrampAccount: boolean; } /** * Access to one ChatGPT workspace, as an account authority resolves it. * * The workspace and residency are the authority's statement and are used as given: this package never * reads them back out of the token, because the claims have one owner, and it is the authority. */ export interface IOpenAiChatGptAccess extends IOpenAiChatGptReadAccess { readonly accountId: string; } /** Resolved access, optionally stamped with the authority's generation of that access token. */ export interface IOpenAiChatGptAccessGrant extends IOpenAiChatGptAccess { /** * The authority's generation of this access token. When it is set and the provider rejects the token, * the connection resolves once more naming this generation, so the authority can renew exactly that * token, and sends the request again. */ readonly generation?: number; } export interface IOpenAiChatGptAccessResolveRequest { /** The provider request signal. A resolver should pass it through to its authority. */ readonly signal: AbortSignal; /** The generation of the access token the provider has just rejected with 401. */ readonly rejectedGeneration?: number; } /** The workspace and residency a connection is pinned to for its lifetime. */ export interface IOpenAiChatGptWorkspaceIdentity { readonly accountId: string; readonly isFedrampAccount: boolean; } export interface IOpenAiChatGptAccessConnectionOptions { /** Stable provider originator header. Defaults to `smartai`. */ readonly originator?: string; /** Optional underlying transport. Defaults to the current global fetch. */ readonly fetch?: typeof fetch; } export interface IOpenAiChatGptResolvingConnectionOptions extends IOpenAiChatGptAccessConnectionOptions { /** Every resolved access must state exactly this workspace and residency. */ readonly expectedIdentity: IOpenAiChatGptWorkspaceIdentity; /** Resolves current access immediately before every provider network request. */ readonly resolveAccess: ( request: IOpenAiChatGptAccessResolveRequest, ) => Promise; } const codexBaseUrl = new URL(OPENAI_CHATGPT_CODEX_BASE_URL); const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.length > 0; const isGeneration = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 1; function assertCodexRequestUrl(normalizedUrlArg: string): void { const url = new URL(normalizedUrlArg); const isCodexPath = url.pathname === codexBaseUrl.pathname || url.pathname.startsWith(`${codexBaseUrl.pathname}/`); if ( url.origin !== codexBaseUrl.origin || url.username !== '' || url.password !== '' || !isCodexPath ) { throw new OpenAiChatGptAuthError('OpenAI ChatGPT inference URL is outside the Codex endpoint.'); } } function requireWorkspaceIdentity(identityArg: IOpenAiChatGptWorkspaceIdentity | undefined): IOpenAiChatGptWorkspaceIdentity { if ( !identityArg || !isNonEmptyString(identityArg.accountId) || typeof identityArg.isFedrampAccount !== 'boolean' ) { throw new OpenAiChatGptAuthError('OpenAI ChatGPT workspace identity is invalid.'); } return Object.freeze({ accountId: identityArg.accountId, isFedrampAccount: identityArg.isFedrampAccount, }); } function assertGrant( grantArg: IOpenAiChatGptAccessGrant, expectedIdentityArg: IOpenAiChatGptWorkspaceIdentity, ): void { if ( !grantArg || !isNonEmptyString(grantArg.accessToken) || (grantArg.generation !== undefined && !isGeneration(grantArg.generation)) ) { throw new OpenAiChatGptAuthError('OpenAI ChatGPT resolved access is invalid.'); } if ( grantArg.accountId !== expectedIdentityArg.accountId || grantArg.isFedrampAccount !== expectedIdentityArg.isFedrampAccount ) { throw new OpenAiChatGptAuthError('OpenAI ChatGPT resolved access identity does not match the connection.'); } } /** The headers a ChatGPT backend request authenticates with. Shared by inference and the model catalog. */ export function createOpenAiChatGptAccessHeaders( accessArg: IOpenAiChatGptReadAccess, originatorArg: string = OPENAI_CHATGPT_DEFAULT_ORIGINATOR, ): Record { return { Authorization: `Bearer ${accessArg.accessToken}`, originator: originatorArg, ...(accessArg.accountId ? { 'ChatGPT-Account-ID': accessArg.accountId } : {}), ...(accessArg.isFedrampAccount ? { 'X-OpenAI-Fedramp': 'true' } : {}), }; } const accessRejected = (): OpenAiChatGptAuthError => new OpenAiChatGptAuthError( 'OpenAI ChatGPT rejected the access token.', { status: 401 }, ); /** * A ChatGPT connection that resolves its access before every provider HTTP request. * * The workspace and residency are pinned at construction; an access that states anything else stops the * request before the transport is called. A provider 401 is answered once: when the rejected access carried * a `generation`, the connection resolves again with `rejectedGeneration` and sends the request a second * time with the new access. A 401 that cannot be retried, and a second 401, fail with an * `OpenAiChatGptAuthError` whose `status` is 401. */ export const createOpenAiChatGptResolvingModelConnection = ( optionsArg: IOpenAiChatGptResolvingConnectionOptions, ): IOpenAiModelConnection => { if (!optionsArg || typeof optionsArg.resolveAccess !== 'function') { throw new OpenAiChatGptAuthError('OpenAI ChatGPT access resolver is required.'); } const expectedIdentity = requireWorkspaceIdentity(optionsArg.expectedIdentity); const resolveAccess = optionsArg.resolveAccess; const originator = optionsArg.originator ?? OPENAI_CHATGPT_DEFAULT_ORIGINATOR; const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') { throw new OpenAiChatGptAuthError('fetch is not available for OpenAI ChatGPT inference.'); } const resolveGrant = async ( requestArg: IOpenAiChatGptAccessResolveRequest, ): Promise => { const grant = await resolveAccess(requestArg); requestArg.signal.throwIfAborted(); assertGrant(grant, expectedIdentity); return grant; }; const send = async (requestArg: Request, grantArg: IOpenAiChatGptAccessGrant): Promise => { const headers = new Headers(requestArg.headers); for (const [name, value] of Object.entries(createOpenAiChatGptAccessHeaders(grantArg, originator))) { headers.set(name, value); } if (!grantArg.isFedrampAccount) headers.delete('X-OpenAI-Fedramp'); const authenticatedRequest = new Request(requestArg, { headers }); authenticatedRequest.signal.throwIfAborted(); return transport(authenticatedRequest); }; const fetchWithCurrentAccess: typeof fetch = async (inputArg, initArg) => { const request = new Request(inputArg, { ...initArg, redirect: 'error', }); assertCodexRequestUrl(request.url); request.signal.throwIfAborted(); const grant = await resolveGrant({ signal: request.signal }); // A replay needs the body the first attempt consumes, so it is kept only when a replay can happen. const replay = grant.generation === undefined ? undefined : request.clone(); const response = await send(request, grant); if (response.status !== 401) return response; await response.body?.cancel().catch(() => undefined); if (!replay) throw accessRejected(); const renewed = await resolveGrant({ signal: replay.signal, rejectedGeneration: grant.generation }); const replayed = await send(replay, renewed); if (replayed.status !== 401) return replayed; await replayed.body?.cancel().catch(() => undefined); throw accessRejected(); }; return { settings: { apiKey: '', baseURL: OPENAI_CHATGPT_CODEX_BASE_URL, fetch: fetchWithCurrentAccess, }, middleware: createOpenAiChatGptInstructionsMiddleware(), // the ChatGPT Codex backend serves the Responses API only apis: ['responses'], classifyLimit: classifyOpenAiChatGptLimit, }; }; /** * A ChatGPT connection for one fixed access, with the workspace and residency its issuer stated. * * It sends exactly the access it was given, and a provider 401 fails with an `OpenAiChatGptAuthError` * whose `status` is 401. Use `createOpenAiChatGptResolvingModelConnection` when an authority renews the * access. */ export const createOpenAiChatGptAccessModelConnection = ( accessArg: IOpenAiChatGptAccess, optionsArg: IOpenAiChatGptAccessConnectionOptions = {}, ): IOpenAiModelConnection => { if (!accessArg || !isNonEmptyString(accessArg.accessToken)) { throw new OpenAiChatGptAuthError('OpenAI ChatGPT access is invalid.'); } const access: IOpenAiChatGptAccess = Object.freeze({ accessToken: accessArg.accessToken, accountId: accessArg.accountId, isFedrampAccount: accessArg.isFedrampAccount, }); return createOpenAiChatGptResolvingModelConnection({ ...optionsArg, expectedIdentity: access, resolveAccess: async () => access, }); };